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 | mit | error: pathspec 'src/com/haxademic/sketch/particle/ParticleAlphaShape.java' did not match any file(s) known to git
| fa781737f236209c786308738516aa96cdb9867a | 1 | cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic | package com.haxademic.sketch.particle;
import java.util.ArrayList;
import java.util.List;
import processing.core.PVector;
import toxi.color.TColor;
import ProGAL.geom3d.Point;
import ProGAL.geom3d.complex.CTriangle;
import ProGAL.geom3d.complex.alphaComplex.AlphaComplex;
import ProGAL.geom3d.complex.alphaComplex.AlphaFiltration;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.draw.color.TColorInit;
import com.haxademic.core.draw.particle.VectorFlyer;
import com.haxademic.core.draw.shapes.BoxBetween;
import com.haxademic.core.draw.util.OpenGLUtil;
import com.haxademic.core.math.MathUtil;
import com.haxademic.core.render.JoonsWrapper;
@SuppressWarnings("serial")
public class ParticleAlphaShape
extends PAppletHax {
protected TColor MODE_SET_BLUE = TColorInit.newRGBA( 0, 200, 234, 255 );
protected TColor MODE_SET_BLUE_TRANS = TColorInit.newRGBA( 0, 200, 234, 100 );
protected TColor BLACK = TColor.BLACK.copy();
public ArrayList<VectorFlyer> boxes;
public ArrayList<Attractor> attractors;
public ArrayList<PVector> attractorsPositions;
protected float _numAttractors = 10;
protected float _numParticles = 50;
List<Point> points;
protected void overridePropsFile() {
_appConfig.setProperty( "sunflow", "true" );
_appConfig.setProperty( "sunflow_active", "true" );
_appConfig.setProperty( "sunflow_quality", "low" );
_appConfig.setProperty( "width", "1280" );
_appConfig.setProperty( "height", "720" );
_appConfig.setProperty( "rendering", "true" );
_appConfig.setProperty( "fps", "30" );
}
public void setup() {
super.setup();
p.smooth(OpenGLUtil.SMOOTH_HIGH);
initFlyers();
}
protected void initFlyers() {
attractors = new ArrayList<Attractor>();
attractorsPositions = new ArrayList<PVector>();
for( int i=0; i < _numAttractors; i++ ) {
attractors.add( new Attractor( new PVector() ) );
attractorsPositions.add( attractors.get(i).position() );
}
boxes = new ArrayList<VectorFlyer>();
for( int i=0; i < _numParticles; i++ ) {
PVector pos = new PVector( MathUtil.randRange(-600, 600), MathUtil.randRange(-600, 600), -2500 );
boxes.add( new VectorFlyer( p.random(3.5f, 5.5f), p.random(10f, 50f), pos ) );
boxes.get(i).setVector( new PVector( MathUtil.randRange(-10, 10), MathUtil.randRange(-10, 10), MathUtil.randRange(-10, 10) ) );
}
points = new ArrayList<Point>();
for( int i=0; i < _numParticles; i++ ) {
points.add( new Point(0,0,0) );
}
}
public void drawApp() {
p.background(0);
p.lights();
// _jw.jr.background(25, 25, 25);
_jw.jr.background(JoonsWrapper.BACKGROUND_GI);
setUpRoom();
translate(0, 0, -400);
// set target of particle to closest attractor
VectorFlyer box = null;
for( int i=0; i < boxes.size(); i++ ) {
box = boxes.get(i);
box.setTarget( box.findClosestPoint( attractorsPositions ) );
box.update( p, false );
}
for( int i=0; i < attractors.size(); i++ ) attractors.get(i).update( false );
// drawProximitySticks();
drawAlphaShape( true );
}
protected void setUpRoom() {
pushMatrix();
translate(0, 0, -2000);
float radiance = 20;
int samples = 16;
_jw.jr.background("cornell_box",
4000, 3000, 3000, // width, height, depth
radiance, radiance, radiance, samples, // radiance rgb & samples
40, 40, 40, // left rgb
40, 40, 40, // right rgb
60, 60, 60, // back rgb
60, 60, 60, // top rgb
60, 60, 60 // bottom rgb
);
popMatrix();
}
protected void drawProximitySticks() {
// set target of particle to closest attractor
VectorFlyer box = null;
VectorFlyer boxCheck = null;
for( int i=0; i < boxes.size(); i++ ) {
for( int j=0; j < boxes.size(); j++ ) {
box = boxes.get(i);
boxCheck = boxes.get(j);
if( box != boxCheck ) {
if( box.position().dist( boxCheck.position() ) < 200 ) {
_jw.jr.fill(JoonsWrapper.MATERIAL_SHINY, 190, 190, 190, 0.55f);
BoxBetween.draw(p, box.position(), boxCheck.position(), 20 );
_jw.jr.fill(JoonsWrapper.MATERIAL_DIFFUSE, 90, 90, 90);
p.pushMatrix();
p.translate(box.position().x, box.position().y, box.position().z);
p.sphere(15);
p.popMatrix();
p.pushMatrix();
p.translate(boxCheck.position().x, boxCheck.position().y, boxCheck.position().z);
p.sphere(15);
p.popMatrix();
}
}
}
}
}
protected void drawAlphaShape( boolean complex ) {
for( int i=0; i < _numParticles; i++ ) {
points.get(i).setX( boxes.get(i).position().x );
points.get(i).setY( boxes.get(i).position().y );
points.get(i).setZ( boxes.get(i).position().z );
}
if( complex == false ) {
AlphaFiltration af = new AlphaFiltration(points);
List<CTriangle> triangles = af.getAlphaShape(200.8);
for(CTriangle tri: triangles) {
p.fill( 50, 200, 50 );
_jw.jr.fill(JoonsWrapper.MATERIAL_SHINY, 50, 200, 50, 0.75f);
beginShape(TRIANGLES);
vertex( (float) tri.getP1().x(), (float) tri.getP1().y(), (float) tri.getP1().z() );
vertex( (float) tri.getP2().x(), (float) tri.getP2().y(), (float) tri.getP2().z() );
vertex( (float) tri.getP3().x(), (float) tri.getP3().y(), (float) tri.getP3().z() );
endShape();
}
} else {
// draw alpha complex
AlphaComplex ac = new AlphaComplex(points, 200.8);
for(CTriangle tri: ac.getTriangles()){
p.fill( 50, 200, 50 );
// if(MathUtil.randBoolean(p) == true) {
_jw.jr.fill(JoonsWrapper.MATERIAL_SHINY, 190, 210, 190, 0.25f);
// } else {
// _jw.jr.fill(JoonsWrapper.MATERIAL_GLASS, 255, 255, 255);
// }
beginShape(TRIANGLES);
vertex( (float) tri.getP1().x(), (float) tri.getP1().y(), (float) tri.getP1().z() );
vertex( (float) tri.getP2().x(), (float) tri.getP2().y(), (float) tri.getP2().z() );
vertex( (float) tri.getP3().x(), (float) tri.getP3().y(), (float) tri.getP3().z() );
endShape();
}
}
}
public class Attractor {
protected PVector position = new PVector();
protected float randDivisor;
public Attractor( PVector newPosition ) {
position.set( newPosition );
randDivisor = MathUtil.randRangeDecimel(600, 1000);
resetPos();
}
public PVector position() {
return position;
}
public void resetPos() {
position.x = MathUtil.randRange(-600, 600);
position.y = MathUtil.randRange(-600, 600);
position.z = MathUtil.randRange(-2500, -3000);
}
public void update( boolean draws ) {
// position.x = P.sin(p.millis() / randDivisor) * 500;
// position.y = P.sin(p.millis() / (randDivisor*2)) * 500;
// position.z = -2000 + P.sin(p.millis() / (randDivisor*2.5f)) * 500;
if(p.frameCount % 100 == 0) {
resetPos();
}
if( draws == true ) {
p.fill( 255, 255, 255 );
p.noStroke();
p.pushMatrix();
p.translate(position.x, position.y, position.z);
p.box(30);
p.popMatrix();
}
}
}
} | src/com/haxademic/sketch/particle/ParticleAlphaShape.java | Particles + Alpha Shapes... | src/com/haxademic/sketch/particle/ParticleAlphaShape.java | Particles + Alpha Shapes... | <ide><path>rc/com/haxademic/sketch/particle/ParticleAlphaShape.java
<add>package com.haxademic.sketch.particle;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>import processing.core.PVector;
<add>import toxi.color.TColor;
<add>import ProGAL.geom3d.Point;
<add>import ProGAL.geom3d.complex.CTriangle;
<add>import ProGAL.geom3d.complex.alphaComplex.AlphaComplex;
<add>import ProGAL.geom3d.complex.alphaComplex.AlphaFiltration;
<add>
<add>import com.haxademic.core.app.PAppletHax;
<add>import com.haxademic.core.draw.color.TColorInit;
<add>import com.haxademic.core.draw.particle.VectorFlyer;
<add>import com.haxademic.core.draw.shapes.BoxBetween;
<add>import com.haxademic.core.draw.util.OpenGLUtil;
<add>import com.haxademic.core.math.MathUtil;
<add>import com.haxademic.core.render.JoonsWrapper;
<add>
<add>@SuppressWarnings("serial")
<add>public class ParticleAlphaShape
<add>extends PAppletHax {
<add>
<add> protected TColor MODE_SET_BLUE = TColorInit.newRGBA( 0, 200, 234, 255 );
<add> protected TColor MODE_SET_BLUE_TRANS = TColorInit.newRGBA( 0, 200, 234, 100 );
<add> protected TColor BLACK = TColor.BLACK.copy();
<add>
<add> public ArrayList<VectorFlyer> boxes;
<add> public ArrayList<Attractor> attractors;
<add> public ArrayList<PVector> attractorsPositions;
<add>
<add> protected float _numAttractors = 10;
<add> protected float _numParticles = 50;
<add>
<add> List<Point> points;
<add>
<add> protected void overridePropsFile() {
<add> _appConfig.setProperty( "sunflow", "true" );
<add> _appConfig.setProperty( "sunflow_active", "true" );
<add> _appConfig.setProperty( "sunflow_quality", "low" );
<add>
<add>
<add> _appConfig.setProperty( "width", "1280" );
<add> _appConfig.setProperty( "height", "720" );
<add> _appConfig.setProperty( "rendering", "true" );
<add> _appConfig.setProperty( "fps", "30" );
<add> }
<add>
<add> public void setup() {
<add> super.setup();
<add> p.smooth(OpenGLUtil.SMOOTH_HIGH);
<add>
<add> initFlyers();
<add> }
<add>
<add> protected void initFlyers() {
<add> attractors = new ArrayList<Attractor>();
<add> attractorsPositions = new ArrayList<PVector>();
<add> for( int i=0; i < _numAttractors; i++ ) {
<add> attractors.add( new Attractor( new PVector() ) );
<add> attractorsPositions.add( attractors.get(i).position() );
<add> }
<add>
<add> boxes = new ArrayList<VectorFlyer>();
<add> for( int i=0; i < _numParticles; i++ ) {
<add> PVector pos = new PVector( MathUtil.randRange(-600, 600), MathUtil.randRange(-600, 600), -2500 );
<add> boxes.add( new VectorFlyer( p.random(3.5f, 5.5f), p.random(10f, 50f), pos ) );
<add> boxes.get(i).setVector( new PVector( MathUtil.randRange(-10, 10), MathUtil.randRange(-10, 10), MathUtil.randRange(-10, 10) ) );
<add> }
<add>
<add> points = new ArrayList<Point>();
<add> for( int i=0; i < _numParticles; i++ ) {
<add> points.add( new Point(0,0,0) );
<add> }
<add> }
<add>
<add>
<add> public void drawApp() {
<add> p.background(0);
<add> p.lights();
<add>
<add>// _jw.jr.background(25, 25, 25);
<add> _jw.jr.background(JoonsWrapper.BACKGROUND_GI);
<add>
<add> setUpRoom();
<add>
<add> translate(0, 0, -400);
<add>
<add> // set target of particle to closest attractor
<add> VectorFlyer box = null;
<add> for( int i=0; i < boxes.size(); i++ ) {
<add> box = boxes.get(i);
<add> box.setTarget( box.findClosestPoint( attractorsPositions ) );
<add> box.update( p, false );
<add> }
<add> for( int i=0; i < attractors.size(); i++ ) attractors.get(i).update( false );
<add>
<add>// drawProximitySticks();
<add> drawAlphaShape( true );
<add> }
<add>
<add> protected void setUpRoom() {
<add> pushMatrix();
<add> translate(0, 0, -2000);
<add> float radiance = 20;
<add> int samples = 16;
<add> _jw.jr.background("cornell_box",
<add> 4000, 3000, 3000, // width, height, depth
<add> radiance, radiance, radiance, samples, // radiance rgb & samples
<add> 40, 40, 40, // left rgb
<add> 40, 40, 40, // right rgb
<add> 60, 60, 60, // back rgb
<add> 60, 60, 60, // top rgb
<add> 60, 60, 60 // bottom rgb
<add> );
<add> popMatrix();
<add> }
<add>
<add> protected void drawProximitySticks() {
<add> // set target of particle to closest attractor
<add> VectorFlyer box = null;
<add> VectorFlyer boxCheck = null;
<add> for( int i=0; i < boxes.size(); i++ ) {
<add> for( int j=0; j < boxes.size(); j++ ) {
<add> box = boxes.get(i);
<add> boxCheck = boxes.get(j);
<add> if( box != boxCheck ) {
<add> if( box.position().dist( boxCheck.position() ) < 200 ) {
<add> _jw.jr.fill(JoonsWrapper.MATERIAL_SHINY, 190, 190, 190, 0.55f);
<add> BoxBetween.draw(p, box.position(), boxCheck.position(), 20 );
<add> _jw.jr.fill(JoonsWrapper.MATERIAL_DIFFUSE, 90, 90, 90);
<add> p.pushMatrix();
<add> p.translate(box.position().x, box.position().y, box.position().z);
<add> p.sphere(15);
<add> p.popMatrix();
<add> p.pushMatrix();
<add> p.translate(boxCheck.position().x, boxCheck.position().y, boxCheck.position().z);
<add> p.sphere(15);
<add> p.popMatrix();
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> protected void drawAlphaShape( boolean complex ) {
<add> for( int i=0; i < _numParticles; i++ ) {
<add> points.get(i).setX( boxes.get(i).position().x );
<add> points.get(i).setY( boxes.get(i).position().y );
<add> points.get(i).setZ( boxes.get(i).position().z );
<add> }
<add>
<add> if( complex == false ) {
<add> AlphaFiltration af = new AlphaFiltration(points);
<add> List<CTriangle> triangles = af.getAlphaShape(200.8);
<add> for(CTriangle tri: triangles) {
<add> p.fill( 50, 200, 50 );
<add> _jw.jr.fill(JoonsWrapper.MATERIAL_SHINY, 50, 200, 50, 0.75f);
<add> beginShape(TRIANGLES);
<add>
<add> vertex( (float) tri.getP1().x(), (float) tri.getP1().y(), (float) tri.getP1().z() );
<add> vertex( (float) tri.getP2().x(), (float) tri.getP2().y(), (float) tri.getP2().z() );
<add> vertex( (float) tri.getP3().x(), (float) tri.getP3().y(), (float) tri.getP3().z() );
<add>
<add> endShape();
<add> }
<add> } else {
<add> // draw alpha complex
<add> AlphaComplex ac = new AlphaComplex(points, 200.8);
<add> for(CTriangle tri: ac.getTriangles()){
<add> p.fill( 50, 200, 50 );
<add>// if(MathUtil.randBoolean(p) == true) {
<add> _jw.jr.fill(JoonsWrapper.MATERIAL_SHINY, 190, 210, 190, 0.25f);
<add>// } else {
<add>// _jw.jr.fill(JoonsWrapper.MATERIAL_GLASS, 255, 255, 255);
<add>// }
<add> beginShape(TRIANGLES);
<add>
<add> vertex( (float) tri.getP1().x(), (float) tri.getP1().y(), (float) tri.getP1().z() );
<add> vertex( (float) tri.getP2().x(), (float) tri.getP2().y(), (float) tri.getP2().z() );
<add> vertex( (float) tri.getP3().x(), (float) tri.getP3().y(), (float) tri.getP3().z() );
<add>
<add> endShape();
<add> }
<add> }
<add> }
<add>
<add>
<add> public class Attractor {
<add> protected PVector position = new PVector();
<add> protected float randDivisor;
<add>
<add> public Attractor( PVector newPosition ) {
<add> position.set( newPosition );
<add> randDivisor = MathUtil.randRangeDecimel(600, 1000);
<add> resetPos();
<add> }
<add>
<add> public PVector position() {
<add> return position;
<add> }
<add>
<add> public void resetPos() {
<add> position.x = MathUtil.randRange(-600, 600);
<add> position.y = MathUtil.randRange(-600, 600);
<add> position.z = MathUtil.randRange(-2500, -3000);
<add> }
<add>
<add> public void update( boolean draws ) {
<add>// position.x = P.sin(p.millis() / randDivisor) * 500;
<add>// position.y = P.sin(p.millis() / (randDivisor*2)) * 500;
<add>// position.z = -2000 + P.sin(p.millis() / (randDivisor*2.5f)) * 500;
<add> if(p.frameCount % 100 == 0) {
<add> resetPos();
<add> }
<add>
<add> if( draws == true ) {
<add> p.fill( 255, 255, 255 );
<add> p.noStroke();
<add> p.pushMatrix();
<add> p.translate(position.x, position.y, position.z);
<add> p.box(30);
<add> p.popMatrix();
<add> }
<add> }
<add> }
<add>
<add>
<add>} |
|
Java | apache-2.0 | faa65fc069be880f67797522f930557178b7388a | 0 | fogbeam/cas_mirror,rkorn86/cas,philliprower/cas,Jasig/cas,leleuj/cas,pdrados/cas,rkorn86/cas,philliprower/cas,Jasig/cas,rkorn86/cas,pdrados/cas,Jasig/cas,philliprower/cas,rkorn86/cas,apereo/cas,fogbeam/cas_mirror,philliprower/cas,fogbeam/cas_mirror,pdrados/cas,pdrados/cas,apereo/cas,apereo/cas,apereo/cas,leleuj/cas,philliprower/cas,Jasig/cas,apereo/cas,pdrados/cas,leleuj/cas,leleuj/cas,leleuj/cas,apereo/cas,apereo/cas,fogbeam/cas_mirror,philliprower/cas,fogbeam/cas_mirror,philliprower/cas,fogbeam/cas_mirror,pdrados/cas,leleuj/cas | package org.apereo.cas.support.saml.web.idp.profile.builders.enc;
import com.google.common.base.Throwables;
import net.shibboleth.utilities.java.support.resolver.CriteriaSet;
import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties;
import org.apereo.cas.support.saml.SamlException;
import org.apereo.cas.support.saml.SamlIdPUtils;
import org.apereo.cas.support.saml.SamlUtils;
import org.apereo.cas.support.saml.services.SamlRegisteredService;
import org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade;
import org.apereo.cas.util.crypto.PrivateKeyFactoryBean;
import org.opensaml.core.criterion.EntityIdCriterion;
import org.opensaml.messaging.context.MessageContext;
import org.opensaml.saml.common.SAMLException;
import org.opensaml.saml.common.SAMLObject;
import org.opensaml.saml.common.binding.impl.SAMLOutboundDestinationHandler;
import org.opensaml.saml.common.binding.security.impl.EndpointURLSchemeSecurityHandler;
import org.opensaml.saml.common.binding.security.impl.SAMLOutboundProtocolMessageSigningHandler;
import org.opensaml.saml.common.messaging.context.SAMLPeerEntityContext;
import org.opensaml.saml.common.messaging.context.SAMLProtocolContext;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.opensaml.saml.criterion.EntityRoleCriterion;
import org.opensaml.saml.criterion.RoleDescriptorCriterion;
import org.opensaml.saml.metadata.resolver.MetadataResolver;
import org.opensaml.saml.metadata.resolver.RoleDescriptorResolver;
import org.opensaml.saml.metadata.resolver.impl.BasicRoleDescriptorResolver;
import org.opensaml.saml.saml2.binding.security.impl.SAML2HTTPRedirectDeflateSignatureSecurityHandler;
import org.opensaml.saml.saml2.core.RequestAbstractType;
import org.opensaml.saml.saml2.metadata.RoleDescriptor;
import org.opensaml.saml.saml2.metadata.SPSSODescriptor;
import org.opensaml.saml.security.impl.MetadataCredentialResolver;
import org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver;
import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator;
import org.opensaml.security.credential.Credential;
import org.opensaml.security.credential.CredentialResolver;
import org.opensaml.security.credential.UsageType;
import org.opensaml.security.credential.impl.StaticCredentialResolver;
import org.opensaml.security.criteria.UsageCriterion;
import org.opensaml.security.x509.BasicX509Credential;
import org.opensaml.xmlsec.SignatureSigningConfiguration;
import org.opensaml.xmlsec.SignatureSigningParameters;
import org.opensaml.xmlsec.SignatureValidationConfiguration;
import org.opensaml.xmlsec.SignatureValidationParameters;
import org.opensaml.xmlsec.config.DefaultSecurityConfigurationBootstrap;
import org.opensaml.xmlsec.context.SecurityParametersContext;
import org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion;
import org.opensaml.xmlsec.criterion.SignatureValidationConfigurationCriterion;
import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration;
import org.opensaml.xmlsec.impl.BasicSignatureValidationConfiguration;
import org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver;
import org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver;
import org.opensaml.xmlsec.signature.Signature;
import org.opensaml.xmlsec.signature.support.SignatureTrustEngine;
import org.opensaml.xmlsec.signature.support.SignatureValidator;
import org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
/**
* This is {@link SamlObjectSigner}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
public class SamlObjectSigner {
protected transient Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* The Override signature reference digest methods.
*/
protected List overrideSignatureReferenceDigestMethods;
/**
* The Override signature algorithms.
*/
protected List overrideSignatureAlgorithms;
/**
* The Override black listed signature algorithms.
*/
protected List overrideBlackListedSignatureAlgorithms;
/**
* The Override white listed signature signing algorithms.
*/
protected List overrideWhiteListedAlgorithms;
@Autowired
private CasConfigurationProperties casProperties;
/**
* Encode a given saml object by invoking a number of outbound security handlers on the context.
*
* @param <T> the type parameter
* @param samlObject the saml object
* @param service the service
* @param adaptor the adaptor
* @param response the response
* @param request the request
* @return the t
* @throws SamlException the saml exception
*/
public <T extends SAMLObject> T encode(final T samlObject,
final SamlRegisteredService service,
final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
final HttpServletResponse response,
final HttpServletRequest request) throws SamlException {
try {
logger.debug("Attempting to encode [{}] for [{}]", samlObject.getClass().getName(), adaptor.getEntityId());
final MessageContext<T> outboundContext = new MessageContext<>();
prepareOutboundContext(samlObject, adaptor, outboundContext);
prepareSecurityParametersContext(adaptor, outboundContext);
prepareEndpointURLSchemeSecurityHandler(outboundContext);
prepareSamlOutboundDestinationHandler(outboundContext);
prepareSamlOutboundProtocolMessageSigningHandler(outboundContext);
return samlObject;
} catch (final Exception e) {
throw new SamlException(e.getMessage(), e);
}
}
/**
* Prepare saml outbound protocol message signing handler.
*
* @param <T> the type parameter
* @param outboundContext the outbound context
* @throws Exception the exception
*/
protected <T extends SAMLObject> void prepareSamlOutboundProtocolMessageSigningHandler(final MessageContext<T> outboundContext)
throws Exception {
logger.debug("Attempting to sign the outbound SAML message...");
final SAMLOutboundProtocolMessageSigningHandler handler = new SAMLOutboundProtocolMessageSigningHandler();
handler.setSignErrorResponses(casProperties.getAuthn().getSamlIdp().getResponse().isSignError());
handler.invoke(outboundContext);
logger.debug("Signed SAML message successfully");
}
/**
* Prepare saml outbound destination handler.
*
* @param <T> the type parameter
* @param outboundContext the outbound context
* @throws Exception the exception
*/
protected <T extends SAMLObject> void prepareSamlOutboundDestinationHandler(final MessageContext<T> outboundContext)
throws Exception {
final SAMLOutboundDestinationHandler handlerDest = new SAMLOutboundDestinationHandler();
handlerDest.initialize();
handlerDest.invoke(outboundContext);
}
/**
* Prepare endpoint url scheme security handler.
*
* @param <T> the type parameter
* @param outboundContext the outbound context
* @throws Exception the exception
*/
protected <T extends SAMLObject> void prepareEndpointURLSchemeSecurityHandler(final MessageContext<T> outboundContext)
throws Exception {
final EndpointURLSchemeSecurityHandler handlerEnd = new EndpointURLSchemeSecurityHandler();
handlerEnd.initialize();
handlerEnd.invoke(outboundContext);
}
/**
* Prepare security parameters context.
*
* @param <T> the type parameter
* @param adaptor the adaptor
* @param outboundContext the outbound context
* @throws SAMLException the saml exception
*/
protected <T extends SAMLObject> void prepareSecurityParametersContext(final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
final MessageContext<T> outboundContext) throws SAMLException {
final SecurityParametersContext secParametersContext = outboundContext.getSubcontext(SecurityParametersContext.class, true);
if (secParametersContext == null) {
throw new RuntimeException("No signature signing parameters could be determined");
}
final SignatureSigningParameters signingParameters = buildSignatureSigningParameters(adaptor.getSsoDescriptor());
secParametersContext.setSignatureSigningParameters(signingParameters);
}
/**
* Prepare outbound context.
*
* @param <T> the type parameter
* @param samlObject the saml object
* @param adaptor the adaptor
* @param outboundContext the outbound context
* @throws SamlException the saml exception
*/
protected <T extends SAMLObject> void prepareOutboundContext(final T samlObject,
final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
final MessageContext<T> outboundContext) throws SamlException {
logger.debug("Outbound saml object to use is [{}]", samlObject.getClass().getName());
outboundContext.setMessage(samlObject);
SamlIdPUtils.preparePeerEntitySamlEndpointContext(outboundContext, adaptor);
}
/**
* Build signature signing parameters signature signing parameters.
*
* @param descriptor the descriptor
* @return the signature signing parameters
* @throws SAMLException the saml exception
*/
protected SignatureSigningParameters buildSignatureSigningParameters(final RoleDescriptor descriptor) throws SAMLException {
try {
final CriteriaSet criteria = new CriteriaSet();
criteria.add(new SignatureSigningConfigurationCriterion(getSignatureSigningConfiguration()));
criteria.add(new RoleDescriptorCriterion(descriptor));
final SAMLMetadataSignatureSigningParametersResolver resolver = new SAMLMetadataSignatureSigningParametersResolver();
logger.debug("Resolving signature signing parameters for [{}]", descriptor.getElementQName().getLocalPart());
final SignatureSigningParameters params = resolver.resolveSingle(criteria);
if (params == null) {
throw new SAMLException("No signature signing parameter is available");
}
logger.debug("Created signature signing parameters."
+ "\nSignature algorithm: [{}]"
+ "\nSignature canonicalization algorithm: [{}]"
+ "\nSignature reference digest methods: [{}]",
params.getSignatureAlgorithm(), params.getSignatureCanonicalizationAlgorithm(),
params.getSignatureReferenceDigestMethod());
return params;
} catch (final Exception e) {
throw new SAMLException(e.getMessage(), e);
}
}
/**
* Gets signature validation configuration.
*
* @return the signature validation configuration
* @throws Exception the exception
*/
protected SignatureValidationConfiguration getSignatureValidationConfiguration() throws Exception {
final BasicSignatureValidationConfiguration config =
DefaultSecurityConfigurationBootstrap.buildDefaultSignatureValidationConfiguration();
final SamlIdPProperties samlIdp = casProperties.getAuthn().getSamlIdp();
if (this.overrideBlackListedSignatureAlgorithms != null
&& !samlIdp.getResponse().getOverrideSignatureCanonicalizationAlgorithm().isEmpty()) {
config.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
config.setWhitelistMerge(true);
}
if (this.overrideWhiteListedAlgorithms != null && !this.overrideWhiteListedAlgorithms.isEmpty()) {
config.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
config.setBlacklistMerge(true);
}
logger.debug("Signature validation blacklisted algorithms: [{}]", config.getBlacklistedAlgorithms());
logger.debug("Signature validation whitelisted algorithms: {}", config.getWhitelistedAlgorithms());
return config;
}
/**
* Gets signature signing configuration.
*
* @return the signature signing configuration
* @throws Exception the exception
*/
protected SignatureSigningConfiguration getSignatureSigningConfiguration() throws Exception {
final BasicSignatureSigningConfiguration config =
DefaultSecurityConfigurationBootstrap.buildDefaultSignatureSigningConfiguration();
final SamlIdPProperties samlIdp = casProperties.getAuthn().getSamlIdp();
if (this.overrideBlackListedSignatureAlgorithms != null
&& !samlIdp.getResponse().getOverrideSignatureCanonicalizationAlgorithm().isEmpty()) {
config.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
}
if (this.overrideSignatureAlgorithms != null && !this.overrideSignatureAlgorithms.isEmpty()) {
config.setSignatureAlgorithms(this.overrideSignatureAlgorithms);
}
if (this.overrideSignatureReferenceDigestMethods != null && !this.overrideSignatureReferenceDigestMethods.isEmpty()) {
config.setSignatureReferenceDigestMethods(this.overrideSignatureReferenceDigestMethods);
}
if (this.overrideWhiteListedAlgorithms != null && !this.overrideWhiteListedAlgorithms.isEmpty()) {
config.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
}
if (StringUtils.isNotBlank(samlIdp.getResponse().getOverrideSignatureCanonicalizationAlgorithm())) {
config.setSignatureCanonicalizationAlgorithm(samlIdp.getResponse().getOverrideSignatureCanonicalizationAlgorithm());
}
logger.debug("Signature signing blacklisted algorithms: [{}]", config.getBlacklistedAlgorithms());
logger.debug("Signature signing signature algorithms: [{}]", config.getSignatureAlgorithms());
logger.debug("Signature signing signature canonicalization algorithm: [{}]", config.getSignatureCanonicalizationAlgorithm());
logger.debug("Signature signing whitelisted algorithms: {}", config.getWhitelistedAlgorithms());
logger.debug("Signature signing reference digest methods: [{}]", config.getSignatureReferenceDigestMethods());
final PrivateKey privateKey = getSigningPrivateKey();
final X509Certificate certificate = getSigningCertificate();
final List<Credential> creds = new ArrayList<>();
creds.add(new BasicX509Credential(certificate, privateKey));
config.setSigningCredentials(creds);
logger.debug("Signature signing credentials configured");
return config;
}
/**
* Gets signing certificate.
*
* @return the signing certificate
*/
protected X509Certificate getSigningCertificate() {
final SamlIdPProperties samlIdp = casProperties.getAuthn().getSamlIdp();
logger.debug("Locating signature signing certificate file from [{}]", samlIdp.getMetadata().getSigningCertFile());
return SamlUtils.readCertificate(new FileSystemResource(samlIdp.getMetadata().getSigningCertFile()));
}
/**
* Gets signing private key.
*
* @return the signing private key
* @throws Exception the exception
*/
protected PrivateKey getSigningPrivateKey() throws Exception {
final SamlIdPProperties samlIdp = casProperties.getAuthn().getSamlIdp();
final PrivateKeyFactoryBean privateKeyFactoryBean = new PrivateKeyFactoryBean();
privateKeyFactoryBean.setLocation(new FileSystemResource(samlIdp.getMetadata().getSigningKeyFile()));
privateKeyFactoryBean.setAlgorithm(samlIdp.getMetadata().getPrivateKeyAlgName());
privateKeyFactoryBean.setSingleton(false);
logger.debug("Locating signature signing key file from [{}]", samlIdp.getMetadata().getSigningKeyFile());
return privateKeyFactoryBean.getObject();
}
/**
* Validate authn request signature.
*
* @param profileRequest the authn request
* @param metadataResolver the metadata resolver
* @param request the request
* @param context the context
* @throws Exception the exception
*/
public void verifySamlProfileRequestIfNeeded(final RequestAbstractType profileRequest,
final MetadataResolver metadataResolver,
final HttpServletRequest request,
final MessageContext context) throws Exception {
final BasicRoleDescriptorResolver roleDescriptorResolver = new BasicRoleDescriptorResolver(metadataResolver);
roleDescriptorResolver.initialize();
logger.debug("Validating signature for [{}]", profileRequest.getClass().getName());
final Signature signature = profileRequest.getSignature();
if (signature != null) {
final SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator();
logger.debug("Validating profile signature for {} via {}...", profileRequest.getIssuer(), validator.getClass().getSimpleName());
validator.validate(signature);
logger.debug("Successfully validated profile signature for {}.", profileRequest.getIssuer());
final Credential credential = getSigningCredential(roleDescriptorResolver, profileRequest);
if (credential == null) {
throw new SamlException("Signing credential for validation could not be resolved");
}
logger.debug("Validating signature using credentials for [{}]", credential.getEntityId());
SignatureValidator.validate(signature, credential);
logger.info("Successfully validated the request signature.");
} else {
final SAML2HTTPRedirectDeflateSignatureSecurityHandler handler = new SAML2HTTPRedirectDeflateSignatureSecurityHandler();
final SAMLPeerEntityContext peer = context.getSubcontext(SAMLPeerEntityContext.class, true);
peer.setEntityId(SamlIdPUtils.getIssuerFromSamlRequest(profileRequest));
logger.debug("Validating request signature for {} via {}...", peer.getEntityId(), handler.getClass().getSimpleName());
logger.debug("Resolving role descriptor for {}", peer.getEntityId());
final RoleDescriptor roleDescriptor = roleDescriptorResolver.resolveSingle(
new CriteriaSet(new EntityIdCriterion(peer.getEntityId()),
new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME)));
peer.setRole(roleDescriptor.getElementQName());
final SAMLProtocolContext protocol = context.getSubcontext(SAMLProtocolContext.class, true);
protocol.setProtocol(SAMLConstants.SAML20P_NS);
logger.debug("Building security parameters context for signature validation of {}", peer.getEntityId());
final SecurityParametersContext secCtx = context.getSubcontext(SecurityParametersContext.class, true);
final SignatureValidationParameters validationParams = new SignatureValidationParameters();
if (overrideBlackListedSignatureAlgorithms != null && !overrideBlackListedSignatureAlgorithms.isEmpty()) {
validationParams.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
logger.debug("Validation override blacklisted algorithms are {}", this.overrideWhiteListedAlgorithms);
}
if (overrideWhiteListedAlgorithms != null && !overrideWhiteListedAlgorithms.isEmpty()) {
validationParams.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
logger.debug("Validation override whitelisted algorithms are {}", this.overrideWhiteListedAlgorithms);
}
logger.debug("Resolving signing credentials for {}", peer.getEntityId());
final Credential credential = getSigningCredential(roleDescriptorResolver, profileRequest);
if (credential == null) {
throw new SamlException("Signing credential for validation could not be resolved");
}
final CredentialResolver resolver = new StaticCredentialResolver(credential);
final KeyInfoCredentialResolver keyResolver = new StaticKeyInfoCredentialResolver(credential);
final SignatureTrustEngine trustEngine = new ExplicitKeySignatureTrustEngine(resolver, keyResolver);
validationParams.setSignatureTrustEngine(trustEngine);
secCtx.setSignatureValidationParameters(validationParams);
handler.setHttpServletRequest(request);
logger.debug("Initializing {} to execute signature validation for {}", handler.getClass().getSimpleName(), peer.getEntityId());
handler.initialize();
logger.debug("Invoking {} to handle signature validation for {}", handler.getClass().getSimpleName(), peer.getEntityId());
handler.invoke(context);
logger.debug("Successfully validated request signature for {}.", profileRequest.getIssuer());
}
}
public void setOverrideSignatureReferenceDigestMethods(final List overrideSignatureReferenceDigestMethods) {
this.overrideSignatureReferenceDigestMethods = overrideSignatureReferenceDigestMethods;
}
public void setOverrideSignatureAlgorithms(final List overrideSignatureAlgorithms) {
this.overrideSignatureAlgorithms = overrideSignatureAlgorithms;
}
public void setOverrideBlackListedSignatureAlgorithms(final List overrideBlackListedSignatureAlgorithms) {
this.overrideBlackListedSignatureAlgorithms = overrideBlackListedSignatureAlgorithms;
}
public void setOverrideWhiteListedAlgorithms(final List overrideWhiteListedAlgorithms) {
this.overrideWhiteListedAlgorithms = overrideWhiteListedAlgorithms;
}
private Credential getSigningCredential(final RoleDescriptorResolver resolver, final RequestAbstractType profileRequest) {
try {
final MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver();
final SignatureValidationConfiguration config = getSignatureValidationConfiguration();
kekCredentialResolver.setRoleDescriptorResolver(resolver);
kekCredentialResolver.setKeyInfoCredentialResolver(
DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver());
kekCredentialResolver.initialize();
final CriteriaSet criteriaSet = new CriteriaSet();
criteriaSet.add(new SignatureValidationConfigurationCriterion(config));
criteriaSet.add(new EntityIdCriterion(SamlIdPUtils.getIssuerFromSamlRequest(profileRequest)));
criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
return kekCredentialResolver.resolveSingle(criteriaSet);
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
}
| support/cas-server-support-saml-idp/src/main/java/org/apereo/cas/support/saml/web/idp/profile/builders/enc/SamlObjectSigner.java | package org.apereo.cas.support.saml.web.idp.profile.builders.enc;
import com.google.common.base.Throwables;
import net.shibboleth.utilities.java.support.resolver.CriteriaSet;
import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.support.saml.SamlException;
import org.apereo.cas.support.saml.SamlIdPUtils;
import org.apereo.cas.support.saml.SamlUtils;
import org.apereo.cas.support.saml.services.SamlRegisteredService;
import org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade;
import org.apereo.cas.util.crypto.PrivateKeyFactoryBean;
import org.opensaml.core.criterion.EntityIdCriterion;
import org.opensaml.messaging.context.MessageContext;
import org.opensaml.saml.common.SAMLException;
import org.opensaml.saml.common.SAMLObject;
import org.opensaml.saml.common.binding.impl.SAMLOutboundDestinationHandler;
import org.opensaml.saml.common.binding.security.impl.EndpointURLSchemeSecurityHandler;
import org.opensaml.saml.common.binding.security.impl.SAMLOutboundProtocolMessageSigningHandler;
import org.opensaml.saml.common.messaging.context.SAMLPeerEntityContext;
import org.opensaml.saml.common.messaging.context.SAMLProtocolContext;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.opensaml.saml.criterion.EntityRoleCriterion;
import org.opensaml.saml.criterion.RoleDescriptorCriterion;
import org.opensaml.saml.metadata.resolver.MetadataResolver;
import org.opensaml.saml.metadata.resolver.RoleDescriptorResolver;
import org.opensaml.saml.metadata.resolver.impl.BasicRoleDescriptorResolver;
import org.opensaml.saml.saml2.binding.security.impl.SAML2HTTPRedirectDeflateSignatureSecurityHandler;
import org.opensaml.saml.saml2.core.RequestAbstractType;
import org.opensaml.saml.saml2.metadata.RoleDescriptor;
import org.opensaml.saml.saml2.metadata.SPSSODescriptor;
import org.opensaml.saml.security.impl.MetadataCredentialResolver;
import org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver;
import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator;
import org.opensaml.security.credential.Credential;
import org.opensaml.security.credential.CredentialResolver;
import org.opensaml.security.credential.UsageType;
import org.opensaml.security.credential.impl.StaticCredentialResolver;
import org.opensaml.security.criteria.UsageCriterion;
import org.opensaml.security.x509.BasicX509Credential;
import org.opensaml.xmlsec.SignatureSigningConfiguration;
import org.opensaml.xmlsec.SignatureSigningParameters;
import org.opensaml.xmlsec.SignatureValidationConfiguration;
import org.opensaml.xmlsec.SignatureValidationParameters;
import org.opensaml.xmlsec.config.DefaultSecurityConfigurationBootstrap;
import org.opensaml.xmlsec.context.SecurityParametersContext;
import org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion;
import org.opensaml.xmlsec.criterion.SignatureValidationConfigurationCriterion;
import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration;
import org.opensaml.xmlsec.impl.BasicSignatureValidationConfiguration;
import org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver;
import org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver;
import org.opensaml.xmlsec.signature.Signature;
import org.opensaml.xmlsec.signature.support.SignatureTrustEngine;
import org.opensaml.xmlsec.signature.support.SignatureValidator;
import org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
/**
* This is {@link SamlObjectSigner}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
public class SamlObjectSigner {
protected transient Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* The Override signature reference digest methods.
*/
protected List overrideSignatureReferenceDigestMethods;
/**
* The Override signature algorithms.
*/
protected List overrideSignatureAlgorithms;
/**
* The Override black listed signature algorithms.
*/
protected List overrideBlackListedSignatureAlgorithms;
/**
* The Override white listed signature signing algorithms.
*/
protected List overrideWhiteListedAlgorithms;
@Autowired
private CasConfigurationProperties casProperties;
/**
* Encode a given saml object by invoking a number of outbound security handlers on the context.
*
* @param <T> the type parameter
* @param samlObject the saml object
* @param service the service
* @param adaptor the adaptor
* @param response the response
* @param request the request
* @return the t
* @throws SamlException the saml exception
*/
public <T extends SAMLObject> T encode(final T samlObject,
final SamlRegisteredService service,
final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
final HttpServletResponse response,
final HttpServletRequest request) throws SamlException {
try {
logger.debug("Attempting to encode [{}] for [{}]", samlObject.getClass().getName(), adaptor.getEntityId());
final MessageContext<T> outboundContext = new MessageContext<>();
prepareOutboundContext(samlObject, adaptor, outboundContext);
prepareSecurityParametersContext(adaptor, outboundContext);
prepareEndpointURLSchemeSecurityHandler(outboundContext);
prepareSamlOutboundDestinationHandler(outboundContext);
prepareSamlOutboundProtocolMessageSigningHandler(outboundContext);
return samlObject;
} catch (final Exception e) {
throw new SamlException(e.getMessage(), e);
}
}
/**
* Prepare saml outbound protocol message signing handler.
*
* @param <T> the type parameter
* @param outboundContext the outbound context
* @throws Exception the exception
*/
protected <T extends SAMLObject> void prepareSamlOutboundProtocolMessageSigningHandler(final MessageContext<T> outboundContext)
throws Exception {
logger.debug("Attempting to sign the outbound SAML message...");
final SAMLOutboundProtocolMessageSigningHandler handler = new SAMLOutboundProtocolMessageSigningHandler();
handler.setSignErrorResponses(casProperties.getAuthn().getSamlIdp().getResponse().isSignError());
handler.invoke(outboundContext);
logger.debug("Signed SAML message successfully");
}
/**
* Prepare saml outbound destination handler.
*
* @param <T> the type parameter
* @param outboundContext the outbound context
* @throws Exception the exception
*/
protected <T extends SAMLObject> void prepareSamlOutboundDestinationHandler(final MessageContext<T> outboundContext)
throws Exception {
final SAMLOutboundDestinationHandler handlerDest = new SAMLOutboundDestinationHandler();
handlerDest.initialize();
handlerDest.invoke(outboundContext);
}
/**
* Prepare endpoint url scheme security handler.
*
* @param <T> the type parameter
* @param outboundContext the outbound context
* @throws Exception the exception
*/
protected <T extends SAMLObject> void prepareEndpointURLSchemeSecurityHandler(final MessageContext<T> outboundContext)
throws Exception {
final EndpointURLSchemeSecurityHandler handlerEnd = new EndpointURLSchemeSecurityHandler();
handlerEnd.initialize();
handlerEnd.invoke(outboundContext);
}
/**
* Prepare security parameters context.
*
* @param <T> the type parameter
* @param adaptor the adaptor
* @param outboundContext the outbound context
* @throws SAMLException the saml exception
*/
protected <T extends SAMLObject> void prepareSecurityParametersContext(final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
final MessageContext<T> outboundContext) throws SAMLException {
final SecurityParametersContext secParametersContext = outboundContext.getSubcontext(SecurityParametersContext.class, true);
if (secParametersContext == null) {
throw new RuntimeException("No signature signing parameters could be determined");
}
final SignatureSigningParameters signingParameters = buildSignatureSigningParameters(adaptor.getSsoDescriptor());
secParametersContext.setSignatureSigningParameters(signingParameters);
}
/**
* Prepare outbound context.
*
* @param <T> the type parameter
* @param samlObject the saml object
* @param adaptor the adaptor
* @param outboundContext the outbound context
* @throws SamlException the saml exception
*/
protected <T extends SAMLObject> void prepareOutboundContext(final T samlObject,
final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
final MessageContext<T> outboundContext) throws SamlException {
logger.debug("Outbound saml object to use is [{}]", samlObject.getClass().getName());
outboundContext.setMessage(samlObject);
SamlIdPUtils.preparePeerEntitySamlEndpointContext(outboundContext, adaptor);
}
/**
* Build signature signing parameters signature signing parameters.
*
* @param descriptor the descriptor
* @return the signature signing parameters
* @throws SAMLException the saml exception
*/
protected SignatureSigningParameters buildSignatureSigningParameters(final RoleDescriptor descriptor) throws SAMLException {
try {
final CriteriaSet criteria = new CriteriaSet();
criteria.add(new SignatureSigningConfigurationCriterion(getSignatureSigningConfiguration()));
criteria.add(new RoleDescriptorCriterion(descriptor));
final SAMLMetadataSignatureSigningParametersResolver resolver = new SAMLMetadataSignatureSigningParametersResolver();
logger.debug("Resolving signature signing parameters for [{}]", descriptor.getElementQName().getLocalPart());
final SignatureSigningParameters params = resolver.resolveSingle(criteria);
if (params == null) {
throw new SAMLException("No signature signing parameter is available");
}
logger.debug("Created signature signing parameters."
+ "\nSignature algorithm: [{}]"
+ "\nSignature canonicalization algorithm: [{}]"
+ "\nSignature reference digest methods: [{}]",
params.getSignatureAlgorithm(), params.getSignatureCanonicalizationAlgorithm(),
params.getSignatureReferenceDigestMethod());
return params;
} catch (final Exception e) {
throw new SAMLException(e.getMessage(), e);
}
}
/**
* Gets signature validation configuration.
*
* @return the signature validation configuration
* @throws Exception the exception
*/
protected SignatureValidationConfiguration getSignatureValidationConfiguration() throws Exception {
final BasicSignatureValidationConfiguration config =
DefaultSecurityConfigurationBootstrap.buildDefaultSignatureValidationConfiguration();
if (this.overrideBlackListedSignatureAlgorithms != null
&& !casProperties.getAuthn().getSamlIdp().getResponse().getOverrideSignatureCanonicalizationAlgorithm().isEmpty()) {
config.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
config.setWhitelistMerge(true);
}
if (this.overrideWhiteListedAlgorithms != null && !this.overrideWhiteListedAlgorithms.isEmpty()) {
config.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
config.setBlacklistMerge(true);
}
logger.debug("Signature validation blacklisted algorithms: [{}]", config.getBlacklistedAlgorithms());
logger.debug("Signature validation whitelisted algorithms: {}", config.getWhitelistedAlgorithms());
return config;
}
/**
* Gets signature signing configuration.
*
* @return the signature signing configuration
* @throws Exception the exception
*/
protected SignatureSigningConfiguration getSignatureSigningConfiguration() throws Exception {
final BasicSignatureSigningConfiguration config =
DefaultSecurityConfigurationBootstrap.buildDefaultSignatureSigningConfiguration();
if (this.overrideBlackListedSignatureAlgorithms != null
&& !casProperties.getAuthn().getSamlIdp().getResponse().getOverrideSignatureCanonicalizationAlgorithm().isEmpty()) {
config.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
}
if (this.overrideSignatureAlgorithms != null && !this.overrideSignatureAlgorithms.isEmpty()) {
config.setSignatureAlgorithms(this.overrideSignatureAlgorithms);
}
if (this.overrideSignatureReferenceDigestMethods != null && !this.overrideSignatureReferenceDigestMethods.isEmpty()) {
config.setSignatureReferenceDigestMethods(this.overrideSignatureReferenceDigestMethods);
}
if (this.overrideWhiteListedAlgorithms != null && !this.overrideWhiteListedAlgorithms.isEmpty()) {
config.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
}
if (StringUtils.isNotBlank(
casProperties.getAuthn().getSamlIdp().getResponse().getOverrideSignatureCanonicalizationAlgorithm())) {
config.setSignatureCanonicalizationAlgorithm(
casProperties.getAuthn().getSamlIdp().getResponse().getOverrideSignatureCanonicalizationAlgorithm());
}
logger.debug("Signature signing blacklisted algorithms: [{}]", config.getBlacklistedAlgorithms());
logger.debug("Signature signing signature algorithms: [{}]", config.getSignatureAlgorithms());
logger.debug("Signature signing signature canonicalization algorithm: [{}]", config.getSignatureCanonicalizationAlgorithm());
logger.debug("Signature signing whitelisted algorithms: {}", config.getWhitelistedAlgorithms());
logger.debug("Signature signing reference digest methods: [{}]", config.getSignatureReferenceDigestMethods());
final PrivateKey privateKey = getSigningPrivateKey();
final X509Certificate certificate = getSigningCertificate();
final List<Credential> creds = new ArrayList<>();
creds.add(new BasicX509Credential(certificate, privateKey));
config.setSigningCredentials(creds);
logger.debug("Signature signing credentials configured");
return config;
}
/**
* Gets signing certificate.
*
* @return the signing certificate
*/
protected X509Certificate getSigningCertificate() {
logger.debug("Locating signature signing certificate file from [{}]",
casProperties.getAuthn().getSamlIdp().getMetadata().getSigningCertFile());
return SamlUtils.readCertificate(
new FileSystemResource(casProperties.getAuthn().getSamlIdp().getMetadata().getSigningCertFile()));
}
/**
* Gets signing private key.
*
* @return the signing private key
* @throws Exception the exception
*/
protected PrivateKey getSigningPrivateKey() throws Exception {
final PrivateKeyFactoryBean privateKeyFactoryBean = new PrivateKeyFactoryBean();
privateKeyFactoryBean.setLocation(
new FileSystemResource(casProperties.getAuthn().getSamlIdp().getMetadata().getSigningKeyFile()));
privateKeyFactoryBean.setAlgorithm(
casProperties.getAuthn().getSamlIdp().getMetadata().getPrivateKeyAlgName());
privateKeyFactoryBean.setSingleton(false);
logger.debug("Locating signature signing key file from [{}]",
casProperties.getAuthn().getSamlIdp().getMetadata().getSigningKeyFile());
return privateKeyFactoryBean.getObject();
}
/**
* Validate authn request signature.
*
* @param profileRequest the authn request
* @param metadataResolver the metadata resolver
* @param request the request
* @param context the context
* @throws Exception the exception
*/
public void verifySamlProfileRequestIfNeeded(final RequestAbstractType profileRequest,
final MetadataResolver metadataResolver,
final HttpServletRequest request,
final MessageContext context) throws Exception {
final BasicRoleDescriptorResolver roleDescriptorResolver = new BasicRoleDescriptorResolver(metadataResolver);
roleDescriptorResolver.initialize();
logger.debug("Validating signature for [{}]", profileRequest.getClass().getName());
final Signature signature = profileRequest.getSignature();
if (signature != null) {
final SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator();
logger.debug("Validating profile signature for {} via {}...", profileRequest.getIssuer(), validator.getClass().getSimpleName());
validator.validate(signature);
logger.debug("Successfully validated profile signature for {}.", profileRequest.getIssuer());
final Credential credential = getSigningCredential(roleDescriptorResolver, profileRequest);
if (credential == null) {
throw new SamlException("Signing credential for validation could not be resolved");
}
logger.debug("Validating signature using credentials for [{}]", credential.getEntityId());
SignatureValidator.validate(signature, credential);
logger.info("Successfully validated the request signature.");
} else {
final SAML2HTTPRedirectDeflateSignatureSecurityHandler handler = new SAML2HTTPRedirectDeflateSignatureSecurityHandler();
final SAMLPeerEntityContext peer = context.getSubcontext(SAMLPeerEntityContext.class, true);
peer.setEntityId(SamlIdPUtils.getIssuerFromSamlRequest(profileRequest));
logger.debug("Validating request signature for {} via {}...", peer.getEntityId(), handler.getClass().getSimpleName());
logger.debug("Resolving role descriptor for {}", peer.getEntityId());
final RoleDescriptor roleDescriptor = roleDescriptorResolver.resolveSingle(
new CriteriaSet(new EntityIdCriterion(peer.getEntityId()),
new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME)));
peer.setRole(roleDescriptor.getElementQName());
final SAMLProtocolContext protocol = context.getSubcontext(SAMLProtocolContext.class, true);
protocol.setProtocol(SAMLConstants.SAML20P_NS);
logger.debug("Building security parameters context for signature validation of {}", peer.getEntityId());
final SecurityParametersContext secCtx = context.getSubcontext(SecurityParametersContext.class, true);
final SignatureValidationParameters validationParams = new SignatureValidationParameters();
if (!overrideBlackListedSignatureAlgorithms.isEmpty()) {
validationParams.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
logger.debug("Validation override blacklisted algorithms are {}", this.overrideWhiteListedAlgorithms);
}
if (!overrideWhiteListedAlgorithms.isEmpty()) {
validationParams.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
logger.debug("Validation override whitelisted algorithms are {}", this.overrideWhiteListedAlgorithms);
}
logger.debug("Resolving signing credentials for {}", peer.getEntityId());
final Credential credential = getSigningCredential(roleDescriptorResolver, profileRequest);
if (credential == null) {
throw new SamlException("Signing credential for validation could not be resolved");
}
final CredentialResolver resolver = new StaticCredentialResolver(credential);
final KeyInfoCredentialResolver keyResolver = new StaticKeyInfoCredentialResolver(credential);
final SignatureTrustEngine trustEngine = new ExplicitKeySignatureTrustEngine(resolver, keyResolver);
validationParams.setSignatureTrustEngine(trustEngine);
secCtx.setSignatureValidationParameters(validationParams);
handler.setHttpServletRequest(request);
logger.debug("Initializing {} to execute signature validation for {}", handler.getClass().getSimpleName(), peer.getEntityId());
handler.initialize();
logger.debug("Invoking {} to handle signature validation for {}", handler.getClass().getSimpleName(), peer.getEntityId());
handler.invoke(context);
logger.debug("Successfully validated request signature for {}.", profileRequest.getIssuer());
}
}
public void setOverrideSignatureReferenceDigestMethods(final List overrideSignatureReferenceDigestMethods) {
this.overrideSignatureReferenceDigestMethods = overrideSignatureReferenceDigestMethods;
}
public void setOverrideSignatureAlgorithms(final List overrideSignatureAlgorithms) {
this.overrideSignatureAlgorithms = overrideSignatureAlgorithms;
}
public void setOverrideBlackListedSignatureAlgorithms(final List overrideBlackListedSignatureAlgorithms) {
this.overrideBlackListedSignatureAlgorithms = overrideBlackListedSignatureAlgorithms;
}
public void setOverrideWhiteListedAlgorithms(final List overrideWhiteListedAlgorithms) {
this.overrideWhiteListedAlgorithms = overrideWhiteListedAlgorithms;
}
private Credential getSigningCredential(final RoleDescriptorResolver resolver, final RequestAbstractType profileRequest) {
try {
final MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver();
final SignatureValidationConfiguration config = getSignatureValidationConfiguration();
kekCredentialResolver.setRoleDescriptorResolver(resolver);
kekCredentialResolver.setKeyInfoCredentialResolver(
DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver());
kekCredentialResolver.initialize();
final CriteriaSet criteriaSet = new CriteriaSet();
criteriaSet.add(new SignatureValidationConfigurationCriterion(config));
criteriaSet.add(new EntityIdCriterion(SamlIdPUtils.getIssuerFromSamlRequest(profileRequest)));
criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
return kekCredentialResolver.resolveSingle(criteriaSet);
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
}
| Fixed test cases
| support/cas-server-support-saml-idp/src/main/java/org/apereo/cas/support/saml/web/idp/profile/builders/enc/SamlObjectSigner.java | Fixed test cases | <ide><path>upport/cas-server-support-saml-idp/src/main/java/org/apereo/cas/support/saml/web/idp/profile/builders/enc/SamlObjectSigner.java
<ide> import net.shibboleth.utilities.java.support.resolver.CriteriaSet;
<ide> import org.apache.commons.lang3.StringUtils;
<ide> import org.apereo.cas.configuration.CasConfigurationProperties;
<add>import org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties;
<ide> import org.apereo.cas.support.saml.SamlException;
<ide> import org.apereo.cas.support.saml.SamlIdPUtils;
<ide> import org.apereo.cas.support.saml.SamlUtils;
<ide> */
<ide> public class SamlObjectSigner {
<ide> protected transient Logger logger = LoggerFactory.getLogger(this.getClass());
<del>
<add>
<ide> /**
<ide> * The Override signature reference digest methods.
<ide> */
<ide> protected SignatureValidationConfiguration getSignatureValidationConfiguration() throws Exception {
<ide> final BasicSignatureValidationConfiguration config =
<ide> DefaultSecurityConfigurationBootstrap.buildDefaultSignatureValidationConfiguration();
<del>
<add> final SamlIdPProperties samlIdp = casProperties.getAuthn().getSamlIdp();
<ide>
<ide> if (this.overrideBlackListedSignatureAlgorithms != null
<del> && !casProperties.getAuthn().getSamlIdp().getResponse().getOverrideSignatureCanonicalizationAlgorithm().isEmpty()) {
<add> && !samlIdp.getResponse().getOverrideSignatureCanonicalizationAlgorithm().isEmpty()) {
<ide> config.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
<ide> config.setWhitelistMerge(true);
<ide> }
<del>
<add>
<ide> if (this.overrideWhiteListedAlgorithms != null && !this.overrideWhiteListedAlgorithms.isEmpty()) {
<ide> config.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
<ide> config.setBlacklistMerge(true);
<ide> }
<del>
<add>
<ide> logger.debug("Signature validation blacklisted algorithms: [{}]", config.getBlacklistedAlgorithms());
<ide> logger.debug("Signature validation whitelisted algorithms: {}", config.getWhitelistedAlgorithms());
<ide>
<ide> return config;
<ide> }
<del>
<add>
<ide> /**
<ide> * Gets signature signing configuration.
<ide> *
<ide> protected SignatureSigningConfiguration getSignatureSigningConfiguration() throws Exception {
<ide> final BasicSignatureSigningConfiguration config =
<ide> DefaultSecurityConfigurationBootstrap.buildDefaultSignatureSigningConfiguration();
<del>
<add> final SamlIdPProperties samlIdp = casProperties.getAuthn().getSamlIdp();
<ide>
<ide> if (this.overrideBlackListedSignatureAlgorithms != null
<del> && !casProperties.getAuthn().getSamlIdp().getResponse().getOverrideSignatureCanonicalizationAlgorithm().isEmpty()) {
<add> && !samlIdp.getResponse().getOverrideSignatureCanonicalizationAlgorithm().isEmpty()) {
<ide> config.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
<ide> }
<ide>
<ide> config.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
<ide> }
<ide>
<del> if (StringUtils.isNotBlank(
<del> casProperties.getAuthn().getSamlIdp().getResponse().getOverrideSignatureCanonicalizationAlgorithm())) {
<del> config.setSignatureCanonicalizationAlgorithm(
<del> casProperties.getAuthn().getSamlIdp().getResponse().getOverrideSignatureCanonicalizationAlgorithm());
<add> if (StringUtils.isNotBlank(samlIdp.getResponse().getOverrideSignatureCanonicalizationAlgorithm())) {
<add> config.setSignatureCanonicalizationAlgorithm(samlIdp.getResponse().getOverrideSignatureCanonicalizationAlgorithm());
<ide> }
<ide> logger.debug("Signature signing blacklisted algorithms: [{}]", config.getBlacklistedAlgorithms());
<ide> logger.debug("Signature signing signature algorithms: [{}]", config.getSignatureAlgorithms());
<ide> * @return the signing certificate
<ide> */
<ide> protected X509Certificate getSigningCertificate() {
<del> logger.debug("Locating signature signing certificate file from [{}]",
<del> casProperties.getAuthn().getSamlIdp().getMetadata().getSigningCertFile());
<del> return SamlUtils.readCertificate(
<del> new FileSystemResource(casProperties.getAuthn().getSamlIdp().getMetadata().getSigningCertFile()));
<add> final SamlIdPProperties samlIdp = casProperties.getAuthn().getSamlIdp();
<add> logger.debug("Locating signature signing certificate file from [{}]", samlIdp.getMetadata().getSigningCertFile());
<add> return SamlUtils.readCertificate(new FileSystemResource(samlIdp.getMetadata().getSigningCertFile()));
<ide> }
<ide>
<ide> /**
<ide> * @throws Exception the exception
<ide> */
<ide> protected PrivateKey getSigningPrivateKey() throws Exception {
<add> final SamlIdPProperties samlIdp = casProperties.getAuthn().getSamlIdp();
<ide> final PrivateKeyFactoryBean privateKeyFactoryBean = new PrivateKeyFactoryBean();
<del> privateKeyFactoryBean.setLocation(
<del> new FileSystemResource(casProperties.getAuthn().getSamlIdp().getMetadata().getSigningKeyFile()));
<del> privateKeyFactoryBean.setAlgorithm(
<del> casProperties.getAuthn().getSamlIdp().getMetadata().getPrivateKeyAlgName());
<add> privateKeyFactoryBean.setLocation(new FileSystemResource(samlIdp.getMetadata().getSigningKeyFile()));
<add> privateKeyFactoryBean.setAlgorithm(samlIdp.getMetadata().getPrivateKeyAlgName());
<ide> privateKeyFactoryBean.setSingleton(false);
<del> logger.debug("Locating signature signing key file from [{}]",
<del> casProperties.getAuthn().getSamlIdp().getMetadata().getSigningKeyFile());
<add> logger.debug("Locating signature signing key file from [{}]", samlIdp.getMetadata().getSigningKeyFile());
<ide> return privateKeyFactoryBean.getObject();
<ide> }
<ide>
<ide> final HttpServletRequest request,
<ide> final MessageContext context) throws Exception {
<ide>
<del>
<add>
<ide> final BasicRoleDescriptorResolver roleDescriptorResolver = new BasicRoleDescriptorResolver(metadataResolver);
<ide> roleDescriptorResolver.initialize();
<del>
<add>
<ide> logger.debug("Validating signature for [{}]", profileRequest.getClass().getName());
<del>
<add>
<ide> final Signature signature = profileRequest.getSignature();
<ide> if (signature != null) {
<ide> final SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator();
<ide> logger.debug("Validating signature using credentials for [{}]", credential.getEntityId());
<ide> SignatureValidator.validate(signature, credential);
<ide> logger.info("Successfully validated the request signature.");
<del>
<add>
<ide> } else {
<ide> final SAML2HTTPRedirectDeflateSignatureSecurityHandler handler = new SAML2HTTPRedirectDeflateSignatureSecurityHandler();
<ide> final SAMLPeerEntityContext peer = context.getSubcontext(SAMLPeerEntityContext.class, true);
<ide> peer.setEntityId(SamlIdPUtils.getIssuerFromSamlRequest(profileRequest));
<ide> logger.debug("Validating request signature for {} via {}...", peer.getEntityId(), handler.getClass().getSimpleName());
<del>
<add>
<ide> logger.debug("Resolving role descriptor for {}", peer.getEntityId());
<del>
<add>
<ide> final RoleDescriptor roleDescriptor = roleDescriptorResolver.resolveSingle(
<del> new CriteriaSet(new EntityIdCriterion(peer.getEntityId()),
<del> new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME)));
<add> new CriteriaSet(new EntityIdCriterion(peer.getEntityId()),
<add> new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME)));
<ide> peer.setRole(roleDescriptor.getElementQName());
<ide> final SAMLProtocolContext protocol = context.getSubcontext(SAMLProtocolContext.class, true);
<ide> protocol.setProtocol(SAMLConstants.SAML20P_NS);
<ide> logger.debug("Building security parameters context for signature validation of {}", peer.getEntityId());
<ide> final SecurityParametersContext secCtx = context.getSubcontext(SecurityParametersContext.class, true);
<ide> final SignatureValidationParameters validationParams = new SignatureValidationParameters();
<del>
<del> if (!overrideBlackListedSignatureAlgorithms.isEmpty()) {
<add>
<add> if (overrideBlackListedSignatureAlgorithms != null && !overrideBlackListedSignatureAlgorithms.isEmpty()) {
<ide> validationParams.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
<ide> logger.debug("Validation override blacklisted algorithms are {}", this.overrideWhiteListedAlgorithms);
<ide> }
<del>
<del> if (!overrideWhiteListedAlgorithms.isEmpty()) {
<add>
<add> if (overrideWhiteListedAlgorithms != null && !overrideWhiteListedAlgorithms.isEmpty()) {
<ide> validationParams.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
<ide> logger.debug("Validation override whitelisted algorithms are {}", this.overrideWhiteListedAlgorithms);
<ide> }
<ide> if (credential == null) {
<ide> throw new SamlException("Signing credential for validation could not be resolved");
<ide> }
<del>
<add>
<ide> final CredentialResolver resolver = new StaticCredentialResolver(credential);
<ide> final KeyInfoCredentialResolver keyResolver = new StaticKeyInfoCredentialResolver(credential);
<ide> final SignatureTrustEngine trustEngine = new ExplicitKeySignatureTrustEngine(resolver, keyResolver);
<ide> validationParams.setSignatureTrustEngine(trustEngine);
<ide> secCtx.setSignatureValidationParameters(validationParams);
<del>
<add>
<ide> handler.setHttpServletRequest(request);
<ide> logger.debug("Initializing {} to execute signature validation for {}", handler.getClass().getSimpleName(), peer.getEntityId());
<ide> handler.initialize();
<ide> public void setOverrideWhiteListedAlgorithms(final List overrideWhiteListedAlgorithms) {
<ide> this.overrideWhiteListedAlgorithms = overrideWhiteListedAlgorithms;
<ide> }
<del>
<add>
<ide> private Credential getSigningCredential(final RoleDescriptorResolver resolver, final RequestAbstractType profileRequest) {
<ide> try {
<ide> final MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver(); |
|
Java | epl-1.0 | 8286e35336da3f0ef0ef55aa79380f95196be2f6 | 0 | moliz/moliz.fuml,moliz/moliz.fuml | package org.modeldriven.fuml.test;
import java.io.File;
import junit.framework.Test;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.modeldriven.fuml.FUML;
import org.modeldriven.fuml.environment.Environment;
import org.modeldriven.fuml.environment.ExecutionEnvironment;
import fUML.Syntax.Activities.IntermediateActivities.Activity;
import fUML.Syntax.CommonBehaviors.BasicBehaviors.Behavior;
/**
*
*/
public class MagicDrawExecutionTestCase extends FUMLTest {
private static Log log = LogFactory.getLog(MagicDrawExecutionTestCase.class);
private static Environment environment; // JUnit creates a new test class for every test!
public static Test suite() {
return FUMLTestSetup.newTestSetup(MagicDrawExecutionTestCase.class);
}
public void setUp() throws Exception {
if (environment == null)
{
String filename = "./test/mdxml/fUML-Tests.mdxml";
File file = new File(filename);
assertTrue("file '" + filename + "' does not exist", file.exists());
FUML.load(file);
environment = Environment.getInstance();
log.info("done");
}
}
public void testCopier() throws Exception {
execute("Copier");
log.info("done");
}
public void testCopierCaller() throws Exception {
execute("CopierCaller");
log.info("done");
}
public void testSimpleDecision() throws Exception {
execute("SimpleDecision");
log.info("done");
}
public void testForkJoin() throws Exception {
execute("ForkJoin");
log.info("done");
}
public void testDecisionJoin() throws Exception {
execute("DecisionJoin");
log.info("done");
}
public void testForkMerge() throws Exception {
execute("ForkMerge");
log.info("done");
}
public void testTestClassExtentReader() throws Exception {
execute("TestClassExtentReader");
log.info("done");
}
public void testSelfReader() throws Exception {
execute("SelfReader");
log.info("done");
}
public void testIdentityTester() throws Exception {
execute("IdentityTester");
log.info("done");
}
public void testTestClassObjectCreator() throws Exception {
execute("TestClassObjectCreator");
log.info("done");
}
public void testObjectDestroyer() throws Exception {
execute("ObjectDestroyer");
log.info("done");
}
public void testTestClassWriterReader() throws Exception {
execute("TestClassWriterReader");
log.info("done");
}
public void testTestClassAttributeWriter() throws Exception {
execute("TestClassAttributeWriter");
log.info("done");
}
public void testTestSimpleActivities() throws Exception {
execute("TestSimpleActivities");
log.info("done");
}
private void execute(String activityName)
{
Behavior behavior = environment.findBehavior(activityName);
if (behavior == null)
throw new RuntimeException("invalid behavior, " + activityName);
log.info("executing behavior: " + behavior.name);
ExecutionEnvironment execution = new ExecutionEnvironment(environment);
execution.execute(behavior);
}
} | test/org/modeldriven/fuml/test/MagicDrawExecutionTestCase.java | package org.modeldriven.fuml.test;
import java.io.File;
import junit.framework.Test;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.modeldriven.fuml.FUML;
import org.modeldriven.fuml.environment.Environment;
import org.modeldriven.fuml.environment.ExecutionEnvironment;
import fUML.Syntax.Activities.IntermediateActivities.Activity;
import fUML.Syntax.CommonBehaviors.BasicBehaviors.Behavior;
/**
*
*/
public class MagicDrawExecutionTestCase extends FUMLTest {
private static Log log = LogFactory.getLog(MagicDrawExecutionTestCase.class);
private static Environment environment; // JUnit creates a new test class for every test!
public static Test suite() {
return FUMLTestSetup.newTestSetup(MagicDrawExecutionTestCase.class);
}
public void setUp() throws Exception {
if (environment == null)
{
String filename = "./test/uml/magicdraw/fUML-Tests.uml";
File file = new File(filename);
assertTrue("file '" + filename + "' does not exist", file.exists());
FUML.load(file);
environment = Environment.getInstance();
log.info("done");
}
}
public void testCopier() throws Exception {
execute("Copier");
log.info("done");
}
public void testCopierCaller() throws Exception {
execute("CopierCaller");
log.info("done");
}
public void testSimpleDecision() throws Exception {
execute("SimpleDecision");
log.info("done");
}
public void testForkJoin() throws Exception {
execute("ForkJoin");
log.info("done");
}
public void testDecisionJoin() throws Exception {
execute("DecisionJoin");
log.info("done");
}
public void testForkMerge() throws Exception {
execute("ForkMerge");
log.info("done");
}
public void testTestClassExtentReader() throws Exception {
execute("TestClassExtentReader");
log.info("done");
}
public void testSelfReader() throws Exception {
execute("SelfReader");
log.info("done");
}
public void testIdentityTester() throws Exception {
execute("IdentityTester");
log.info("done");
}
public void testTestClassObjectCreator() throws Exception {
execute("TestClassObjectCreator");
log.info("done");
}
public void testObjectDestroyer() throws Exception {
execute("ObjectDestroyer");
log.info("done");
}
public void testTestClassWriterReader() throws Exception {
execute("TestClassWriterReader");
log.info("done");
}
public void testTestClassAttributeWriter() throws Exception {
execute("TestClassAttributeWriter");
log.info("done");
}
public void testTestSimpleActivities() throws Exception {
execute("TestSimpleActivities");
log.info("done");
}
private void execute(String activityName)
{
Behavior behavior = environment.findBehavior(activityName);
if (behavior == null)
throw new RuntimeException("invalid behavior, " + activityName);
log.info("executing behavior: " + behavior.name);
ExecutionEnvironment execution = new ExecutionEnvironment(environment);
execution.execute(behavior);
}
} | Updated to use fUML-Tests.mdxml rather than fUML-Tests.uml.
git-svn-id: 9d2bca6aa0bb0e0904bb84cf3b0bc91589e0dc58@20518 ea6537cf-e006-0410-91e3-b5ef31be2fb9
| test/org/modeldriven/fuml/test/MagicDrawExecutionTestCase.java | Updated to use fUML-Tests.mdxml rather than fUML-Tests.uml. | <ide><path>est/org/modeldriven/fuml/test/MagicDrawExecutionTestCase.java
<ide> public void setUp() throws Exception {
<ide> if (environment == null)
<ide> {
<del> String filename = "./test/uml/magicdraw/fUML-Tests.uml";
<add> String filename = "./test/mdxml/fUML-Tests.mdxml";
<ide> File file = new File(filename);
<ide> assertTrue("file '" + filename + "' does not exist", file.exists());
<ide> FUML.load(file); |
|
Java | apache-2.0 | f11a733570d088e706a011cbb712b462315d8a85 | 0 | mduerig/jackrabbit-oak,mduerig/jackrabbit-oak,mduerig/jackrabbit-oak,mduerig/jackrabbit-oak,mduerig/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.plugins.document;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.stats.Clock;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.jackrabbit.oak.plugins.document.Collection.JOURNAL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class JournalGCTest {
private static final Logger LOG = LoggerFactory.getLogger(JournalGCTest.class);
private final ThreadLocal<Boolean> shouldWait = new ThreadLocal<Boolean>();
@Before
public void setup() {
shouldWait.remove();
}
@After
public void tearDown() {
shouldWait.remove();
}
@Rule
public DocumentMKBuilderProvider builderProvider = new DocumentMKBuilderProvider();
@Test
public void gcWithCheckpoint() throws Exception {
Clock c = new Clock.Virtual();
c.waitUntil(System.currentTimeMillis());
DocumentNodeStore ns = builderProvider.newBuilder()
.clock(c).setAsyncDelay(0).getNodeStore();
// perform some change
NodeBuilder builder = ns.getRoot().builder();
builder.child("foo");
ns.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
Revision head = ns.getHeadRevision().getRevision(ns.getClusterId());
assertNotNull(head);
// trigger creation of journal entry
ns.runBackgroundOperations();
String cp = ns.checkpoint(TimeUnit.DAYS.toMillis(1));
JournalEntry entry = ns.getDocumentStore().find(JOURNAL, JournalEntry.asId(head));
assertNotNull(entry);
// wait two hours
c.waitUntil(c.getTime() + TimeUnit.HOURS.toMillis(2));
// instruct journal collector to remove entries older than one hour
ns.getJournalGarbageCollector().gc(1, TimeUnit.HOURS);
// must not remove existing entry, because checkpoint is still valid
entry = ns.getDocumentStore().find(JOURNAL, JournalEntry.asId(head));
assertNotNull(entry);
ns.release(cp);
ns.getJournalGarbageCollector().gc(1, TimeUnit.HOURS);
// now journal GC can remove the entry
entry = ns.getDocumentStore().find(JOURNAL, JournalEntry.asId(head));
assertNull(entry);
}
@Test
public void getTailRevision() throws Exception {
Clock c = new Clock.Virtual();
c.waitUntil(System.currentTimeMillis());
DocumentNodeStore ns = builderProvider.newBuilder()
.clock(c).setAsyncDelay(0).getNodeStore();
JournalGarbageCollector jgc = ns.getJournalGarbageCollector();
assertEquals(new Revision(0, 0, ns.getClusterId()), jgc.getTailRevision());
NodeBuilder builder = ns.getRoot().builder();
builder.child("foo");
ns.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
ns.runBackgroundOperations();
assertEquals(0, jgc.gc(1, TimeUnit.HOURS));
// current time, but without the increment done by getTime()
long now = c.getTime() - 1;
Revision tail = new Revision(now - TimeUnit.HOURS.toMillis(1), 0, ns.getClusterId());
c.waitUntil(c.getTime() + TimeUnit.MINUTES.toMillis(1));
assertEquals(tail, jgc.getTailRevision());
c.waitUntil(c.getTime() + TimeUnit.HOURS.toMillis(1));
// must collect the journal entry created by the background update
assertEquals(1, jgc.gc(1, TimeUnit.HOURS));
// current time, but without the increment done by getTime()
now = c.getTime() - 1;
tail = new Revision(now - TimeUnit.HOURS.toMillis(1), 0, ns.getClusterId());
assertEquals(tail, jgc.getTailRevision());
}
/**
* reproducing OAK-5601:
* <ul>
* <li>have two documentMk's, one to make changes, one does only read</li>
* <li>make a commit, let 1.2 seconds pass, run gc, then read it from the other documentMk</li>
* <li>the gc (1sec timeout) will have cleaned up that 1.2sec old journal entry, resulting in
* a missing journal entry exception when reading from the 2nd documentMk</li>
* </ul>
* What the test has to ensure is that the JournalEntry does the query, then blocks that
* thread to let the GC happen, then continues on with find(). This results in those
* revisions that the JournalEntry got back from the query to be removed and
* thus end up missing by later on in addTo.
*/
@Test
@Ignore("OAK-5601")
public void gcCausingMissingJournalEntries() throws Exception {
// cluster setup
final Semaphore enteringFind = new Semaphore(0);
final Semaphore continuingFind = new Semaphore(100);
DocumentStore sharedDocStore = new MemoryDocumentStore() {
@Override
public <T extends Document> T find(Collection<T> collection, String key) {
if (collection == JOURNAL && (shouldWait.get() == null || shouldWait.get())) {
LOG.info("find(JOURNAL,..): entered... releasing enteringFind semaphore");
enteringFind.release();
try {
LOG.info("find(JOURNAL,..): waiting for OK to continue");
if (!continuingFind.tryAcquire(5, TimeUnit.SECONDS)) {
fail("could not continue within 5 sec");
}
LOG.info("find(JOURNAL,..): continuing");
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
return super.find(collection, key);
}
};
final DocumentNodeStore writingNs = builderProvider.newBuilder()
.setDocumentStore(sharedDocStore)
.setClusterId(1)
.setAsyncDelay(0).getNodeStore();
DocumentNodeStore readingNs = builderProvider.newBuilder()
.setDocumentStore(sharedDocStore)
.setClusterId(2)
.setAsyncDelay(0).getNodeStore();
// 'proper cluster sync': do it a bit too many times
readingNs.runBackgroundOperations();
writingNs.runBackgroundOperations();
readingNs.runBackgroundOperations();
writingNs.runBackgroundOperations();
// perform some change in writingNs - not yet seen by readingNs
NodeBuilder builder = writingNs.getRoot().builder();
NodeBuilder foo = builder.child("foo");
// cause a branch commit
for(int i=0; i<DocumentRootBuilder.UPDATE_LIMIT + 1; i++) {
foo.setProperty(String.valueOf(i), "foobar");
}
writingNs.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
final Revision head = writingNs.getHeadRevision().getRevision(writingNs.getClusterId());
assertNotNull(head);
// trigger creation of journal entry - still not yet seen by readingNs
writingNs.runBackgroundOperations();
JournalEntry entry = writingNs.getDocumentStore().find(JOURNAL, JournalEntry.asId(head));
assertNotNull(entry);
// wait slightly more than 1 sec - readingNs does nothing during this time
Thread.sleep(1200);
// clear up the semaphore
enteringFind.drainPermits();
continuingFind.drainPermits();
final StringBuffer errorMsg = new StringBuffer();
Runnable r = new Runnable() {
@Override
public void run() {
// wait for find(JOURNAL,..) to be entered
LOG.info("waiting for find(JOURNAL,... to be called...");
try {
if (!enteringFind.tryAcquire(5, TimeUnit.SECONDS)) {
errorMsg.append("find(JOURNAL,..) did not get called within 5sec");
return;
}
} catch (InterruptedException e) {
errorMsg.append("Got interrupted: "+e);
return;
}
LOG.info("find(JOURNAL,..) got called, running GC.");
// avoid find to block in this thread - via a ThreadLocal
shouldWait.set(false);
// instruct journal GC to remove entries older than one hour - readingNs hasn't seen it
writingNs.getJournalGarbageCollector().gc(1, TimeUnit.SECONDS);
// entry should be removed
JournalEntry entry = writingNs.getDocumentStore().find(JOURNAL, JournalEntry.asId(head));
assertNull(entry);
// now release the waiting find(JOURNAL,..) thread
continuingFind.release(100);
}
};
Thread th = new Thread(r);
th.start();
// verify that readingNs doesn't have /foo yet
assertFalse(readingNs.getRoot().hasChildNode("foo"));
// now run background ops on readingNs - it should be able to see 'foo'
for(int i=0; i<5; i++) {
readingNs.runBackgroundOperations();
}
assertTrue(readingNs.getRoot().hasChildNode("foo"));
}
}
| oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/JournalGCTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.plugins.document;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.stats.Clock;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.jackrabbit.oak.plugins.document.Collection.JOURNAL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class JournalGCTest {
private static final Logger LOG = LoggerFactory.getLogger(JournalGCTest.class);
private final ThreadLocal<Boolean> shouldWait = new ThreadLocal<Boolean>();
@Before
public void setup() {
shouldWait.remove();
}
@After
public void tearDown() {
shouldWait.remove();
}
@Rule
public DocumentMKBuilderProvider builderProvider = new DocumentMKBuilderProvider();
@Test
public void gcWithCheckpoint() throws Exception {
Clock c = new Clock.Virtual();
c.waitUntil(System.currentTimeMillis());
DocumentNodeStore ns = builderProvider.newBuilder()
.clock(c).setAsyncDelay(0).getNodeStore();
// perform some change
NodeBuilder builder = ns.getRoot().builder();
builder.child("foo");
ns.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
Revision head = ns.getHeadRevision().getRevision(ns.getClusterId());
assertNotNull(head);
// trigger creation of journal entry
ns.runBackgroundOperations();
String cp = ns.checkpoint(TimeUnit.DAYS.toMillis(1));
JournalEntry entry = ns.getDocumentStore().find(JOURNAL, JournalEntry.asId(head));
assertNotNull(entry);
// wait two hours
c.waitUntil(c.getTime() + TimeUnit.HOURS.toMillis(2));
// instruct journal collector to remove entries older than one hour
ns.getJournalGarbageCollector().gc(1, TimeUnit.HOURS);
// must not remove existing entry, because checkpoint is still valid
entry = ns.getDocumentStore().find(JOURNAL, JournalEntry.asId(head));
assertNotNull(entry);
ns.release(cp);
ns.getJournalGarbageCollector().gc(1, TimeUnit.HOURS);
// now journal GC can remove the entry
entry = ns.getDocumentStore().find(JOURNAL, JournalEntry.asId(head));
assertNull(entry);
}
@Test
public void getTailRevision() throws Exception {
Clock c = new Clock.Virtual();
c.waitUntil(System.currentTimeMillis());
DocumentNodeStore ns = builderProvider.newBuilder()
.clock(c).setAsyncDelay(0).getNodeStore();
JournalGarbageCollector jgc = ns.getJournalGarbageCollector();
assertEquals(new Revision(0, 0, ns.getClusterId()), jgc.getTailRevision());
NodeBuilder builder = ns.getRoot().builder();
builder.child("foo");
ns.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
ns.runBackgroundOperations();
assertEquals(0, jgc.gc(1, TimeUnit.HOURS));
// current time, but without the increment done by getTime()
long now = c.getTime() - 1;
Revision tail = new Revision(now - TimeUnit.HOURS.toMillis(1), 0, ns.getClusterId());
c.waitUntil(c.getTime() + TimeUnit.MINUTES.toMillis(1));
assertEquals(tail, jgc.getTailRevision());
c.waitUntil(c.getTime() + TimeUnit.HOURS.toMillis(1));
// must collect the journal entry created by the background update
assertEquals(1, jgc.gc(1, TimeUnit.HOURS));
// current time, but without the increment done by getTime()
now = c.getTime() - 1;
tail = new Revision(now - TimeUnit.HOURS.toMillis(1), 0, ns.getClusterId());
assertEquals(tail, jgc.getTailRevision());
}
/**
* reproducing OAK-5601:
* <ul>
* <li>have two documentMk's, one to make changes, one does only read</li>
* <li>make a commit, let 2 hours pass, run gc, then read it from the other documentMk</li>
* <li>the gc (1h timeout) will have cleaned up that 2h old journal entry, resulting in
* a missing journal entry exception when reading from the 2nd documentMk</li>
* </ul>
*/
@Test
@Ignore("OAK-5601")
public void gcCausingMissingJournalEntries() throws Exception {
// cluster setup
final Semaphore enteringFind = new Semaphore(0);
final Semaphore continuingFind = new Semaphore(100);
DocumentStore sharedDocStore = new MemoryDocumentStore() {
@Override
public <T extends Document> T find(Collection<T> collection, String key) {
if (collection == JOURNAL && (shouldWait.get() == null || shouldWait.get())) {
LOG.info("find(JOURNAL,..): entered... releasing enteringFind semaphore");
enteringFind.release();
try {
LOG.info("find(JOURNAL,..): waiting for OK to continue");
if (!continuingFind.tryAcquire(5, TimeUnit.SECONDS)) {
fail("could not continue within 5 sec");
}
LOG.info("find(JOURNAL,..): continuing");
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
return super.find(collection, key);
}
};
final DocumentNodeStore writingNs = builderProvider.newBuilder()
.setDocumentStore(sharedDocStore)
.setClusterId(1)
.setAsyncDelay(0).getNodeStore();
DocumentNodeStore readingNs = builderProvider.newBuilder()
.setDocumentStore(sharedDocStore)
.setClusterId(2)
.setAsyncDelay(0).getNodeStore();
// 'proper cluster sync': do it a bit too many times
readingNs.runBackgroundOperations();
writingNs.runBackgroundOperations();
readingNs.runBackgroundOperations();
writingNs.runBackgroundOperations();
// perform some change in writingNs - not yet seen by readingNs
NodeBuilder builder = writingNs.getRoot().builder();
NodeBuilder foo = builder.child("foo");
// cause a branch commit
for(int i=0; i<DocumentRootBuilder.UPDATE_LIMIT + 1; i++) {
foo.setProperty(String.valueOf(i), "foobar");
}
writingNs.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
final Revision head = writingNs.getHeadRevision().getRevision(writingNs.getClusterId());
assertNotNull(head);
// trigger creation of journal entry - still not yet seen by readingNs
writingNs.runBackgroundOperations();
JournalEntry entry = writingNs.getDocumentStore().find(JOURNAL, JournalEntry.asId(head));
assertNotNull(entry);
// wait slightly more than 1 sec - readingNs does nothing during this time
Thread.sleep(1200);
// clear up the semaphore
enteringFind.drainPermits();
continuingFind.drainPermits();
final StringBuffer errorMsg = new StringBuffer();
Runnable r = new Runnable() {
@Override
public void run() {
// wait for find(JOURNAL,..) to be entered
LOG.info("waiting for find(JOURNAL,... to be called...");
try {
if (!enteringFind.tryAcquire(5, TimeUnit.SECONDS)) {
errorMsg.append("find(JOURNAL,..) did not get called within 5sec");
return;
}
} catch (InterruptedException e) {
errorMsg.append("Got interrupted: "+e);
return;
}
LOG.info("find(JOURNAL,..) got called, running GC.");
// avoid find to block in this thread - via a ThreadLocal
shouldWait.set(false);
// instruct journal GC to remove entries older than one hour - readingNs hasn't seen it
writingNs.getJournalGarbageCollector().gc(1, TimeUnit.SECONDS);
// entry should be removed
JournalEntry entry = writingNs.getDocumentStore().find(JOURNAL, JournalEntry.asId(head));
assertNull(entry);
// now release the waiting find(JOURNAL,..) thread
continuingFind.release(100);
}
};
Thread th = new Thread(r);
th.start();
// verify that readingNs doesn't have /foo yet
assertFalse(readingNs.getRoot().hasChildNode("foo"));
// now run background ops on readingNs - it should be able to see 'foo'
for(int i=0; i<5; i++) {
readingNs.runBackgroundOperations();
}
assertTrue(readingNs.getRoot().hasChildNode("foo"));
}
}
| OAK-5601 : more explanation for the testcase added
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1782179 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/JournalGCTest.java | OAK-5601 : more explanation for the testcase added | <ide><path>ak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/JournalGCTest.java
<ide> * reproducing OAK-5601:
<ide> * <ul>
<ide> * <li>have two documentMk's, one to make changes, one does only read</li>
<del> * <li>make a commit, let 2 hours pass, run gc, then read it from the other documentMk</li>
<del> * <li>the gc (1h timeout) will have cleaned up that 2h old journal entry, resulting in
<add> * <li>make a commit, let 1.2 seconds pass, run gc, then read it from the other documentMk</li>
<add> * <li>the gc (1sec timeout) will have cleaned up that 1.2sec old journal entry, resulting in
<ide> * a missing journal entry exception when reading from the 2nd documentMk</li>
<ide> * </ul>
<add> * What the test has to ensure is that the JournalEntry does the query, then blocks that
<add> * thread to let the GC happen, then continues on with find(). This results in those
<add> * revisions that the JournalEntry got back from the query to be removed and
<add> * thus end up missing by later on in addTo.
<ide> */
<ide> @Test
<ide> @Ignore("OAK-5601") |
|
Java | epl-1.0 | 1460bcb5b4028007723ddc9a7c65cf4bb496fd8c | 0 | sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt | /*******************************************************************************
* Copyright (c) 2009 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.core.archive.compound.v3;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import org.eclipse.birt.core.archive.cache.CacheListener;
import org.eclipse.birt.core.archive.cache.Cacheable;
import org.eclipse.birt.core.archive.cache.FileCacheManager;
import org.eclipse.birt.core.archive.cache.SystemCacheManager;
import org.eclipse.birt.core.i18n.CoreMessages;
import org.eclipse.birt.core.i18n.ResourceConstants;
/**
*
* SuperBlock structure:
*
*
*
*/
public class Ext2FileSystem
{
private volatile RandomAccessFile rf;
private long length;
private int maxBlockId;
private String fileName;
private boolean readOnly;
private boolean removeOnExit;
/**
* properties saved in the file header
*/
private final HashMap<String, String> properties = new HashMap<String, String>( );
private boolean propertyDirty = true;
protected final FileCacheManager cacheManager = new FileCacheManager( );
/**
* nodes define the logical stream
*/
private final NodeTable nodeTable = new NodeTable( this );
/**
* named entries to define the logical stream
*/
private final EntryTable entryTable = new EntryTable( this );
private final FreeBlockTable freeTable = new FreeBlockTable( this );
/**
* opened streams
*/
private final HashSet<Ext2File> openedFiles = new HashSet<Ext2File>( );
/**
* mode
*
* @param filePath
* @param mode
* defines the archive open mode: "r": read mode "rw": read write
* mode, if the file exist, create a empty one. "rw+": read write
* mode, if the file exist, open the exits file. "rwt": read
* write cache mode, if the file exist, create a empty one. the
* file is removed after the file is closed.
* @throws IOException
*/
public Ext2FileSystem( String filePath, String mode ) throws IOException
{
this( filePath, null, mode );
}
public Ext2FileSystem( String filePath, RandomAccessFile rf, String mode )
throws IOException
{
fileName = new File( filePath ).getCanonicalPath( );
this.rf = rf;
cacheManager.setCacheListener( new Ext2FileSystemCacheListener( ) );
if ( "rw".equals( mode ) )
{
readOnly = false;
removeOnExit = false;
createFileSystem( );
return;
}
if ( "rw+".equals( mode ) )
{
readOnly = false;
removeOnExit = false;
if ( new File( fileName ).exists( ) )
{
openFileSystem( );
}
else
{
createFileSystem( );
}
return;
}
if ( "r".equals( mode ) )
{
readOnly = true;
removeOnExit = false;
openFileSystem( );
return;
}
if ( "rwt".equals( mode ) )
{
readOnly = false;
removeOnExit = true;
createFileSystem( );
return;
}
throw new IOException( CoreMessages.getFormattedString(
ResourceConstants.UNSUPPORTED_FILE_MODE, new Object[]{mode} ) );
}
private void openFileSystem( ) throws IOException
{
if ( rf == null )
{
if ( readOnly )
{
rf = new RandomAccessFile( fileName, "r" );
}
else
{
rf = new RandomAccessFile( fileName, "rw" );
}
}
length = rf.length( );
maxBlockId = (int) ( ( length + BLOCK_SIZE - 1 ) / BLOCK_SIZE ) + 1;
readHeader( );
nodeTable.read( );
entryTable.read( );
freeTable.read( );
readProperties( );
}
private void ensureParentFolderCreated( String fileName )
{
// try to create the parent folder
File parentFile = new File( fileName ).getParentFile( );
if ( parentFile != null && !parentFile.exists( ) )
{
parentFile.mkdirs( );
}
}
private void createFileSystem( ) throws IOException
{
if ( !removeOnExit )
{
if ( rf == null )
{
ensureParentFolderCreated( fileName );
rf = new RandomAccessFile( fileName, "rw" );
}
rf.setLength( 0 );
writeProperties( );
entryTable.write( );
freeTable.write( );
nodeTable.write( );
writeHeader( );
}
length = 0;
maxBlockId = 2;
}
public void setRemoveOnExit( boolean mode )
{
removeOnExit = mode;
}
synchronized public void close( ) throws IOException
{
try
{
closeFiles( );
if ( !readOnly && !removeOnExit )
{
writeProperties( );
entryTable.write( );
nodeTable.write( );
freeTable.write( );
nodeTable.write( NodeTable.INODE_FREE_TABLE );
cacheManager.touchAllCaches( );
writeHeader( );
}
properties.clear( );
entryTable.clear( );
nodeTable.clear( );
cacheManager.clear( );
freeTable.clear( );
}
finally
{
if ( rf != null )
{
rf.close( );
rf = null;
}
if ( removeOnExit )
{
new File( fileName ).delete( );
}
}
}
private void closeFiles( ) throws IOException
{
if ( openedFiles != null )
{
ArrayList<Ext2File> files = new ArrayList<Ext2File>( openedFiles );
for ( Ext2File file : files )
{
if ( file != null )
{
file.close( );
}
}
openedFiles.clear( );
}
}
synchronized public void flush( ) throws IOException
{
if ( !removeOnExit )
{
if ( readOnly )
{
throw new IOException(
CoreMessages.getString( ResourceConstants.FILE_IN_READONLY_MODE ) );
}
ensureFileOpened( );
// flush all the cached data into disk
writeProperties( );
entryTable.write( );
nodeTable.write( );
freeTable.write( );
nodeTable.write( NodeTable.INODE_FREE_TABLE );
cacheManager.touchAllCaches( new Ext2FileSystemCacheListener( ) );
}
}
public void refresh( ) throws IOException
{
throw new UnsupportedOperationException( "refresh" );
}
public boolean isReadOnly( )
{
return readOnly;
}
public boolean isRemoveOnExit( )
{
return removeOnExit;
}
synchronized void registerOpenedFile( Ext2File file )
{
openedFiles.add( file );
}
synchronized void unregisterOpenedFile( Ext2File file )
{
openedFiles.remove( file );
}
public void setCacheSize( int cacheSize )
{
cacheManager.setMaxCacheSize( cacheSize );
}
public int getUsedCacheSize( )
{
return cacheManager.getUsedCacheSize( );
}
synchronized public Ext2File createFile( String name ) throws IOException
{
if ( readOnly )
{
throw new IOException(
CoreMessages.getString( ResourceConstants.FILE_IN_READONLY_MODE ) );
}
Ext2Entry entry = entryTable.getEntry( name );
if ( entry == null )
{
Ext2Node node = nodeTable.allocateNode( );
entry = new Ext2Entry( name, node.getNodeId( ) );
entryTable.addEntry( entry );
}
Ext2Node node = nodeTable.getNode( entry.inode );
Ext2File file = new Ext2File( this, entry, node );
file.setLength( 0 );
return file;
}
synchronized public Ext2File openFile( String name ) throws IOException
{
Ext2Entry entry = entryTable.getEntry( name );
if ( entry != null )
{
Ext2Node node = nodeTable.getNode( entry.inode );
return new Ext2File( this, entry, node );
}
if ( !readOnly )
{
return createFile( name );
}
throw new FileNotFoundException( name );
}
synchronized public boolean existFile( String name )
{
return entryTable.getEntry( name ) != null;
}
synchronized public Iterable<String> listAllFiles( )
{
return entryTable.listAllEntries( );
}
synchronized public Iterable<String> listFiles( String fromName )
{
return entryTable.listEntries( fromName );
}
synchronized public void removeFile( String name ) throws IOException
{
if ( readOnly )
{
throw new IOException(
CoreMessages.getString( ResourceConstants.FILE_IN_READONLY_MODE ) );
}
// check if there are any opened stream links with the name,
if ( !openedFiles.isEmpty( ) )
{
ArrayList<Ext2File> removedFiles = new ArrayList<Ext2File>( );
for ( Ext2File file : openedFiles )
{
if ( name.equals( file.getName( ) ) )
{
removedFiles.add( file );
}
}
for ( Ext2File file : removedFiles )
{
file.close( );
}
}
Ext2Entry entry = entryTable.removeEntry( name );
if ( entry != null )
{
nodeTable.releaseNode( entry.inode );
}
}
public String getFileName( )
{
return fileName;
}
public String getProperty( String name )
{
assert name != null;
return properties.get( name );
}
public void setProperty( String name, String value )
{
assert name != null;
if ( value == null )
{
properties.remove( name );
}
else
{
properties.put( name, value );
}
propertyDirty = true;
}
static final int HEADER_SIZE = 1024;
/** the document tag: RPTDOCV2 */
public static final long EXT2_MAGIC_TAG = 0x525054444f435632L;
static final int EXT2_VERSION_0 = 0;
static final int BLOCK_SIZE = 4096;
static final int BLOCK_SIZE_BITS = 12;
static final int BLOCK_OFFSET_MASK = 0xFFF;
private void readHeader( ) throws IOException
{
byte[] bytes = new byte[HEADER_SIZE];
rf.seek( 0 );
rf.readFully( bytes );
DataInputStream in = new DataInputStream( new ByteArrayInputStream(
bytes ) );
long magicTag = in.readLong( );
if ( magicTag != EXT2_MAGIC_TAG )
{
throw new IOException( CoreMessages.getFormattedString(
ResourceConstants.NOT_EXT2_ARCHIVE, new Object[]{magicTag} ) );
}
int version = in.readInt( );
if ( version != EXT2_VERSION_0 )
{
throw new IOException( CoreMessages.getFormattedString(
ResourceConstants.UNSUPPORTED_ARCHIVE_VERSION,
new Object[]{version} ) );
}
int blockSize = in.readInt( );
if ( blockSize != BLOCK_SIZE )
{
throw new IOException( CoreMessages.getFormattedString(
ResourceConstants.UNSUPPORTED_BLOCK_SIZE,
new Object[]{blockSize} ) );
}
}
private void readProperties( ) throws IOException
{
Ext2File file = new Ext2File( this, NodeTable.INODE_SYSTEM_HEAD, false );
try
{
byte[] bytes = new byte[(int) ( file.length( ) - HEADER_SIZE )];
file.seek( HEADER_SIZE );
file.read( bytes, 0, bytes.length );
DataInputStream in = new DataInputStream( new ByteArrayInputStream(
bytes ) );
int count = in.readInt( );
for ( int i = 0; i < count; i++ )
{
String name = in.readUTF( );
String value = in.readUTF( );
if ( !properties.containsKey( name ) )
{
properties.put( name, value );
}
}
}
finally
{
file.close( );
}
propertyDirty = false;
}
private void writeHeader( ) throws IOException
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream( BLOCK_SIZE );
DataOutputStream out = new DataOutputStream( bytes );
out.writeLong( EXT2_MAGIC_TAG );
out.writeInt( EXT2_VERSION_0 );
out.writeInt( BLOCK_SIZE );
rf.seek( 0 );
rf.write( bytes.toByteArray( ) );
}
private void writeProperties( ) throws IOException
{
if ( !propertyDirty )
{
return;
}
propertyDirty = false;
Ext2File file = new Ext2File( this, NodeTable.INODE_SYSTEM_HEAD, false );
try
{
ByteArrayOutputStream buffer = new ByteArrayOutputStream( );
DataOutputStream out = new DataOutputStream( buffer );
out.writeInt( properties.size( ) );
for ( Entry<String, String> entry : properties.entrySet( ) )
{
String name = entry.getKey( );
String value = entry.getValue( );
out.writeUTF( name );
out.writeUTF( value );
}
byte[] bytes = buffer.toByteArray( );
file.seek( HEADER_SIZE );
file.write( bytes, 0, bytes.length );
}
finally
{
file.close( );
}
}
synchronized protected int allocFreeBlock( ) throws IOException
{
int blockId = freeTable.getFreeBlock( );
if ( blockId > 0 )
{
return blockId;
}
return maxBlockId++;
}
void releaseFreeBlocks( Ext2Node node )
{
freeTable.addFreeBlocks( node );
}
synchronized protected FatBlock createFatBlock( ) throws IOException
{
int blockId = allocFreeBlock( );
FatBlock block = new FatBlock( this, blockId );
cacheManager.addCache( block );
return block;
}
synchronized protected DataBlock createDataBlock( ) throws IOException
{
int blockId = allocFreeBlock( );
DataBlock block = new DataBlock( this, blockId );
cacheManager.addCache( block );
return block;
}
synchronized protected void unloadBlock( Block block ) throws IOException
{
cacheManager.releaseCache( block );
}
synchronized protected FatBlock loadFatBlock( int blockId )
throws IOException
{
FatBlock block = (FatBlock) cacheManager.getCache( blockId );
if ( block == null )
{
block = new FatBlock( this, blockId );
block.refresh( );
cacheManager.addCache( block );
}
return block;
}
synchronized DataBlock loadDataBlock( int blockId ) throws IOException
{
Object cacheKey = Integer.valueOf( blockId );
DataBlock block = (DataBlock) cacheManager.getCache( cacheKey );
if ( block == null )
{
block = new DataBlock( this, blockId );
block.refresh( );
cacheManager.addCache( block );
}
return block;
}
void readBlock( int blockId, byte[] buffer, int offset, int size )
throws IOException
{
readBlock( blockId, offset, buffer, offset, size );
}
synchronized void readBlock( int blockId, int blockOff, byte[] buffer,
int offset, int size ) throws IOException
{
assert buffer != null;
assert blockId >= 0;
assert offset >= 0;
assert blockOff >= 0;
assert offset + size <= buffer.length;
assert blockOff + size <= BLOCK_SIZE;
long position = ( ( (long) blockId ) << BLOCK_SIZE_BITS ) + blockOff;
if ( position < length )
{
long remainSize = length - position;
rf.seek( position );
if ( remainSize < size )
{
size = (int) remainSize;
}
rf.readFully( buffer, offset, size );
}
}
void writeBlock( int blockId, byte[] buffer, int offset, int size )
throws IOException
{
writeBlock( blockId, offset, buffer, offset, size );
}
synchronized void writeBlock( int blockId, int blockOff, byte[] buffer,
int offset, int size ) throws IOException
{
assert buffer != null;
assert blockId >= 0;
assert offset >= 0;
assert blockOff >= 0;
assert offset + size <= buffer.length;
assert blockOff + size <= BLOCK_SIZE;
ensureFileOpened( );
long position = ( ( (long) blockId ) << BLOCK_SIZE_BITS ) + blockOff;
rf.seek( position );
rf.write( buffer, offset, size );
position += size;
if ( position > length )
{
length = position;
}
}
public Ext2Entry getEntry( String name )
{
return entryTable.getEntry( name );
}
public Ext2Node getNode( int nodeId )
{
return nodeTable.getNode( nodeId );
}
static class Ext2FileSystemCacheListener implements CacheListener
{
public void onCacheRelease( Cacheable cache )
{
Ext2Block block = (Ext2Block) cache;
try
{
block.flush( );
}
catch ( IOException ex )
{
ex.printStackTrace( );
}
}
}
private void ensureFileOpened( ) throws IOException
{
if ( rf == null )
{
synchronized ( this )
{
if ( rf == null )
{
ensureParentFolderCreated( fileName );
rf = new RandomAccessFile( fileName, "rw" );
rf.setLength( 0 );
}
}
}
}
public long length( )
{
// field length is only updated when archive file is written to disk
// file, so can't use it directly.
return maxBlockId * BLOCK_SIZE;
}
}
| core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/compound/v3/Ext2FileSystem.java | /*******************************************************************************
* Copyright (c) 2009 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.core.archive.compound.v3;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import org.eclipse.birt.core.archive.cache.CacheListener;
import org.eclipse.birt.core.archive.cache.Cacheable;
import org.eclipse.birt.core.archive.cache.FileCacheManager;
import org.eclipse.birt.core.archive.cache.SystemCacheManager;
import org.eclipse.birt.core.i18n.CoreMessages;
import org.eclipse.birt.core.i18n.ResourceConstants;
/**
*
* SuperBlock structure:
*
*
*
*/
public class Ext2FileSystem
{
private volatile RandomAccessFile rf;
private long length;
private int maxBlockId;
private String fileName;
private boolean readOnly;
private boolean removeOnExit;
/**
* properties saved in the file header
*/
private final HashMap<String, String> properties = new HashMap<String, String>( );
private boolean propertyDirty = true;
protected final FileCacheManager cacheManager = new FileCacheManager( );
/**
* nodes define the logical stream
*/
private final NodeTable nodeTable = new NodeTable( this );
/**
* named entries to define the logical stream
*/
private final EntryTable entryTable = new EntryTable( this );
private final FreeBlockTable freeTable = new FreeBlockTable( this );
/**
* opened streams
*/
private final HashSet<Ext2File> openedFiles = new HashSet<Ext2File>( );
/**
* mode
*
* @param filePath
* @param mode
* defines the archive open mode: "r": read mode "rw": read write
* mode, if the file exist, create a empty one. "rw+": read write
* mode, if the file exist, open the exits file. "rwt": read
* write cache mode, if the file exist, create a empty one. the
* file is removed after the file is closed.
* @throws IOException
*/
public Ext2FileSystem( String filePath, String mode ) throws IOException
{
this( filePath, null, mode );
}
public Ext2FileSystem( String filePath, RandomAccessFile rf, String mode )
throws IOException
{
fileName = new File( filePath ).getCanonicalPath( );
this.rf = rf;
cacheManager.setCacheListener( new Ext2FileSystemCacheListener( ) );
if ( "rw".equals( mode ) )
{
readOnly = false;
removeOnExit = false;
createFileSystem( );
return;
}
if ( "rw+".equals( mode ) )
{
readOnly = false;
removeOnExit = false;
if ( new File( fileName ).exists( ) )
{
openFileSystem( );
}
else
{
createFileSystem( );
}
return;
}
if ( "r".equals( mode ) )
{
readOnly = true;
removeOnExit = false;
openFileSystem( );
return;
}
if ( "rwt".equals( mode ) )
{
readOnly = false;
removeOnExit = true;
createFileSystem( );
return;
}
throw new IOException( CoreMessages.getFormattedString(
ResourceConstants.UNSUPPORTED_FILE_MODE, new Object[]{mode} ) );
}
private void openFileSystem( ) throws IOException
{
if ( rf == null )
{
if ( readOnly )
{
rf = new RandomAccessFile( fileName, "r" );
}
else
{
rf = new RandomAccessFile( fileName, "rw" );
}
}
length = rf.length( );
maxBlockId = (int) ( ( length + BLOCK_SIZE - 1 ) / BLOCK_SIZE ) + 1;
readHeader( );
nodeTable.read( );
entryTable.read( );
freeTable.read( );
readProperties( );
}
private void ensureParentFolderCreated( String fileName )
{
// try to create the parent folder
File parentFile = new File( fileName ).getParentFile( );
if ( parentFile != null && !parentFile.exists( ) )
{
parentFile.mkdirs( );
}
}
private void createFileSystem( ) throws IOException
{
if ( !removeOnExit )
{
if ( rf == null )
{
ensureParentFolderCreated( fileName );
rf = new RandomAccessFile( fileName, "rw" );
}
rf.setLength( 0 );
writeProperties( );
entryTable.write( );
freeTable.write( );
nodeTable.write( );
writeHeader( );
}
length = 0;
maxBlockId = 2;
}
public void setRemoveOnExit( boolean mode )
{
removeOnExit = mode;
}
synchronized public void close( ) throws IOException
{
try
{
closeFiles( );
if ( !readOnly && !removeOnExit )
{
writeProperties( );
entryTable.write( );
nodeTable.write( );
freeTable.write( );
nodeTable.write( NodeTable.INODE_FREE_TABLE );
cacheManager.touchAllCaches( );
writeHeader( );
}
properties.clear( );
entryTable.clear( );
nodeTable.clear( );
cacheManager.clear( );
freeTable.clear( );
}
finally
{
if ( rf != null )
{
rf.close( );
rf = null;
}
if ( removeOnExit )
{
new File( fileName ).delete( );
}
}
}
private void closeFiles( ) throws IOException
{
if ( openedFiles != null )
{
ArrayList<Ext2File> files = new ArrayList<Ext2File>( openedFiles );
for ( Ext2File file : files )
{
if ( file != null )
{
file.close( );
}
}
openedFiles.clear( );
}
}
synchronized public void flush( ) throws IOException
{
if ( !removeOnExit )
{
if ( readOnly )
{
throw new IOException(
CoreMessages.getString( ResourceConstants.FILE_IN_READONLY_MODE ) );
}
ensureFileOpened( );
// flush all the cached data into disk
writeProperties( );
entryTable.write( );
nodeTable.write( );
freeTable.write( );
nodeTable.write( NodeTable.INODE_FREE_TABLE );
cacheManager.touchAllCaches( new Ext2FileSystemCacheListener( ) );
}
}
public void refresh( ) throws IOException
{
throw new UnsupportedOperationException( "refresh" );
}
public boolean isReadOnly( )
{
return readOnly;
}
public boolean isRemoveOnExit( )
{
return removeOnExit;
}
synchronized void registerOpenedFile( Ext2File file )
{
openedFiles.add( file );
}
synchronized void unregisterOpenedFile( Ext2File file )
{
openedFiles.remove( file );
}
public void setCacheSize( int cacheSize )
{
cacheManager.setMaxCacheSize( cacheSize );
}
public int getUsedCacheSize( )
{
return cacheManager.getUsedCacheSize( );
}
synchronized public Ext2File createFile( String name ) throws IOException
{
if ( readOnly )
{
throw new IOException(
CoreMessages.getString( ResourceConstants.FILE_IN_READONLY_MODE ) );
}
Ext2Entry entry = entryTable.getEntry( name );
if ( entry == null )
{
Ext2Node node = nodeTable.allocateNode( );
entry = new Ext2Entry( name, node.getNodeId( ) );
entryTable.addEntry( entry );
}
Ext2Node node = nodeTable.getNode( entry.inode );
Ext2File file = new Ext2File( this, entry, node );
file.setLength( 0 );
return file;
}
synchronized public Ext2File openFile( String name ) throws IOException
{
Ext2Entry entry = entryTable.getEntry( name );
if ( entry != null )
{
Ext2Node node = nodeTable.getNode( entry.inode );
return new Ext2File( this, entry, node );
}
if ( !readOnly )
{
return createFile( name );
}
throw new FileNotFoundException( name );
}
synchronized public boolean existFile( String name )
{
return entryTable.getEntry( name ) != null;
}
synchronized public Iterable<String> listAllFiles( )
{
return entryTable.listAllEntries( );
}
synchronized public Iterable<String> listFiles( String fromName )
{
return entryTable.listEntries( fromName );
}
synchronized public void removeFile( String name ) throws IOException
{
if ( readOnly )
{
throw new IOException(
CoreMessages.getString( ResourceConstants.FILE_IN_READONLY_MODE ) );
}
// check if there are any opened stream links with the name,
if ( !openedFiles.isEmpty( ) )
{
ArrayList<Ext2File> removedFiles = new ArrayList<Ext2File>( );
for ( Ext2File file : openedFiles )
{
if ( name.equals( file.getName( ) ) )
{
removedFiles.add( file );
}
}
for ( Ext2File file : removedFiles )
{
file.close( );
}
}
Ext2Entry entry = entryTable.removeEntry( name );
if ( entry != null )
{
nodeTable.releaseNode( entry.inode );
}
}
public String getFileName( )
{
return fileName;
}
public String getProperty( String name )
{
assert name != null;
return properties.get( name );
}
public void setProperty( String name, String value )
{
assert name != null;
if ( value == null )
{
properties.remove( name );
}
else
{
properties.put( name, value );
}
propertyDirty = true;
}
static final int HEADER_SIZE = 1024;
/** the document tag: RPTDOCV2 */
public static final long EXT2_MAGIC_TAG = 0x525054444f435632L;
static final int EXT2_VERSION_0 = 0;
static final int BLOCK_SIZE = 4096;
static final int BLOCK_SIZE_BITS = 12;
static final int BLOCK_OFFSET_MASK = 0xFFF;
private void readHeader( ) throws IOException
{
byte[] bytes = new byte[HEADER_SIZE];
rf.seek( 0 );
rf.readFully( bytes );
DataInputStream in = new DataInputStream( new ByteArrayInputStream(
bytes ) );
long magicTag = in.readLong( );
if ( magicTag != EXT2_MAGIC_TAG )
{
throw new IOException( CoreMessages.getFormattedString(
ResourceConstants.NOT_EXT2_ARCHIVE, new Object[]{magicTag} ) );
}
int version = in.readInt( );
if ( version != EXT2_VERSION_0 )
{
throw new IOException( CoreMessages.getFormattedString(
ResourceConstants.UNSUPPORTED_ARCHIVE_VERSION,
new Object[]{version} ) );
}
int blockSize = in.readInt( );
if ( blockSize != BLOCK_SIZE )
{
throw new IOException( CoreMessages.getFormattedString(
ResourceConstants.UNSUPPORTED_BLOCK_SIZE,
new Object[]{blockSize} ) );
}
}
private void readProperties( ) throws IOException
{
Ext2File file = new Ext2File( this, NodeTable.INODE_SYSTEM_HEAD, false );
try
{
byte[] bytes = new byte[(int) ( file.length( ) - HEADER_SIZE )];
file.seek( HEADER_SIZE );
file.read( bytes, 0, bytes.length );
DataInputStream in = new DataInputStream( new ByteArrayInputStream(
bytes ) );
int count = in.readInt( );
for ( int i = 0; i < count; i++ )
{
String name = in.readUTF( );
String value = in.readUTF( );
if ( !properties.containsKey( name ) )
{
properties.put( name, value );
}
}
}
finally
{
file.close( );
}
propertyDirty = false;
}
private void writeHeader( ) throws IOException
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream( BLOCK_SIZE );
DataOutputStream out = new DataOutputStream( bytes );
out.writeLong( EXT2_MAGIC_TAG );
out.writeInt( EXT2_VERSION_0 );
out.writeInt( BLOCK_SIZE );
rf.seek( 0 );
rf.write( bytes.toByteArray( ) );
}
private void writeProperties( ) throws IOException
{
if ( !propertyDirty )
{
return;
}
propertyDirty = false;
Ext2File file = new Ext2File( this, NodeTable.INODE_SYSTEM_HEAD, false );
try
{
ByteArrayOutputStream buffer = new ByteArrayOutputStream( );
DataOutputStream out = new DataOutputStream( buffer );
out.writeInt( properties.size( ) );
for ( Entry<String, String> entry : properties.entrySet( ) )
{
String name = entry.getKey( );
String value = entry.getValue( );
out.writeUTF( name );
out.writeUTF( value );
}
byte[] bytes = buffer.toByteArray( );
file.seek( HEADER_SIZE );
file.write( bytes, 0, bytes.length );
}
finally
{
file.close( );
}
}
synchronized protected int allocFreeBlock( ) throws IOException
{
int blockId = freeTable.getFreeBlock( );
if ( blockId > 0 )
{
return blockId;
}
return maxBlockId++;
}
void releaseFreeBlocks( Ext2Node node )
{
freeTable.addFreeBlocks( node );
}
synchronized protected FatBlock createFatBlock( ) throws IOException
{
int blockId = allocFreeBlock( );
FatBlock block = new FatBlock( this, blockId );
cacheManager.addCache( block );
return block;
}
synchronized protected DataBlock createDataBlock( ) throws IOException
{
int blockId = allocFreeBlock( );
DataBlock block = new DataBlock( this, blockId );
cacheManager.addCache( block );
return block;
}
synchronized protected void unloadBlock( Block block ) throws IOException
{
cacheManager.releaseCache( block );
}
synchronized protected FatBlock loadFatBlock( int blockId )
throws IOException
{
FatBlock block = (FatBlock) cacheManager.getCache( blockId );
if ( block == null )
{
block = new FatBlock( this, blockId );
block.refresh( );
cacheManager.addCache( block );
}
return block;
}
synchronized DataBlock loadDataBlock( int blockId ) throws IOException
{
Object cacheKey = Integer.valueOf( blockId );
DataBlock block = (DataBlock) cacheManager.getCache( cacheKey );
if ( block == null )
{
block = new DataBlock( this, blockId );
block.refresh( );
cacheManager.addCache( block );
}
return block;
}
void readBlock( int blockId, byte[] buffer, int offset, int size )
throws IOException
{
readBlock( blockId, offset, buffer, offset, size );
}
synchronized void readBlock( int blockId, int blockOff, byte[] buffer,
int offset, int size ) throws IOException
{
assert buffer != null;
assert blockId >= 0;
assert offset >= 0;
assert blockOff >= 0;
assert offset + size <= buffer.length;
assert blockOff + size <= BLOCK_SIZE;
long position = ( ( (long) blockId ) << BLOCK_SIZE_BITS ) + blockOff;
if ( position < length )
{
long remainSize = length - position;
rf.seek( position );
if ( remainSize < size )
{
size = (int) remainSize;
}
rf.readFully( buffer, offset, size );
}
}
void writeBlock( int blockId, byte[] buffer, int offset, int size )
throws IOException
{
writeBlock( blockId, offset, buffer, offset, size );
}
synchronized void writeBlock( int blockId, int blockOff, byte[] buffer,
int offset, int size ) throws IOException
{
assert buffer != null;
assert blockId >= 0;
assert offset >= 0;
assert blockOff >= 0;
assert offset + size <= buffer.length;
assert blockOff + size <= BLOCK_SIZE;
ensureFileOpened( );
long position = ( ( (long) blockId ) << BLOCK_SIZE_BITS ) + blockOff;
rf.seek( position );
rf.write( buffer, offset, size );
position += size;
if ( position > length )
{
length = position;
}
}
public Ext2Entry getEntry( String name )
{
return entryTable.getEntry( name );
}
public Ext2Node getNode( int nodeId )
{
return nodeTable.getNode( nodeId );
}
static class Ext2FileSystemCacheListener implements CacheListener
{
public void onCacheRelease( Cacheable cache )
{
Ext2Block block = (Ext2Block) cache;
try
{
block.flush( );
}
catch ( IOException ex )
{
ex.printStackTrace( );
}
}
}
private void ensureFileOpened( ) throws IOException
{
if ( rf == null )
{
synchronized ( this )
{
if ( rf == null )
{
ensureParentFolderCreated( fileName );
rf = new RandomAccessFile( fileName, "rw" );
rf.setLength( 0 );
}
}
}
}
public long length( )
{
return length;
}
}
| 72136 Correct the algorithm to calculate transitent document size in
javaserver side | core/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/compound/v3/Ext2FileSystem.java | 72136 Correct the algorithm to calculate transitent document size in javaserver side | <ide><path>ore/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/compound/v3/Ext2FileSystem.java
<ide>
<ide> public long length( )
<ide> {
<del> return length;
<add> // field length is only updated when archive file is written to disk
<add> // file, so can't use it directly.
<add> return maxBlockId * BLOCK_SIZE;
<ide> }
<ide> } |
|
Java | apache-2.0 | 7a9c4a066d1b52b26f0fe4090b22bcdd0ffdbd3b | 0 | apache/jmeter,benbenw/jmeter,ham1/jmeter,ham1/jmeter,etnetera/jmeter,benbenw/jmeter,benbenw/jmeter,apache/jmeter,ham1/jmeter,apache/jmeter,apache/jmeter,apache/jmeter,benbenw/jmeter,etnetera/jmeter,etnetera/jmeter,ham1/jmeter,etnetera/jmeter,ham1/jmeter,etnetera/jmeter | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.visualizers;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
//import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
//import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import org.apache.jmeter.config.ConfigTestElement;
import org.apache.jmeter.config.gui.AbstractConfigGui;
import org.apache.jmeter.gui.UnsharedComponent;
import org.apache.jmeter.gui.util.HeaderAsPropertyRenderer;
import org.apache.jmeter.gui.util.MenuFactory;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.gui.ObjectTableModel;
import org.apache.jorphan.reflect.Functor;
public class PropertyControlGui extends AbstractConfigGui
implements ActionListener, UnsharedComponent {
private static final long serialVersionUID = 1L;
private static final String COLUMN_NAMES_0 = "name"; // $NON-NLS-1$
private static final String COLUMN_NAMES_1 = "value"; // $NON-NLS-1$
// TODO: add and delete not currently supported
private static final String ADD = "add"; // $NON-NLS-1$
private static final String DELETE = "delete"; // $NON-NLS-1$
private static final String SYSTEM = "system"; // $NON-NLS-1$
private static final String JMETER = "jmeter"; // $NON-NLS-1$
private JCheckBox systemButton = new JCheckBox("System");
private JCheckBox jmeterButton = new JCheckBox("JMeter");
private JLabel tableLabel = new JLabel("Properties");
/** The table containing the list of arguments. */
private transient JTable table;
/** The model for the arguments table. */
protected transient ObjectTableModel tableModel;
// /** A button for adding new arguments to the table. */
// private JButton add;
//
// /** A button for removing arguments from the table. */
// private JButton delete;
public PropertyControlGui() {
super();
init();
}
public String getLabelResource() {
return "property_visualiser_title"; // $NON-NLS-1$
}
@Override
public Collection<String> getMenuCategories() {
return Arrays.asList(new String[] { MenuFactory.NON_TEST_ELEMENTS });
}
public void actionPerformed(ActionEvent action) {
String command = action.getActionCommand();
if (ADD.equals(command)){
return;
}
if (DELETE.equals(command)){
return;
}
if (SYSTEM.equals(command)){
setUpData();
return;
}
if (JMETER.equals(command)){
setUpData();
return;
}
}
public TestElement createTestElement() {
TestElement el = new ConfigTestElement();
modifyTestElement(el);
return el;
}
@Override
public void configure(TestElement element) {
super.configure(element);
setUpData();
}
private void setUpData(){
tableModel.clearData();
Properties p=null;
if (systemButton.isSelected()){
p = System.getProperties();
}
if (jmeterButton.isSelected()) {
p = JMeterUtils.getJMeterProperties();
}
if (p == null) {
return;
}
Set<Map.Entry<Object, Object>> s = p.entrySet();
ArrayList<Map.Entry<Object, Object>> al = new ArrayList<Map.Entry<Object, Object>>(s);
Collections.sort(al, new Comparator<Map.Entry<Object, Object>>(){
public int compare(Map.Entry<Object, Object> o1, Map.Entry<Object, Object> o2) {
String m1,m2;
m1=(String)o1.getKey();
m2=(String)o2.getKey();
return m1.compareTo(m2);
}
});
Iterator<Map.Entry<Object, Object>> i = al.iterator();
while(i.hasNext()){
tableModel.addRow(i.next());
}
}
public void modifyTestElement(TestElement element) {
configureTestElement(element);
}
private Component makeMainPanel() {
initializeTableModel();
table = new JTable(tableModel);
table.getTableHeader().setDefaultRenderer(new HeaderAsPropertyRenderer());
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
return makeScrollPane(table);
}
/**
* Create a panel containing the title label for the table.
*
* @return a panel containing the title label
*/
private Component makeLabelPanel() {
JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
ButtonGroup bg = new ButtonGroup();
bg.add(systemButton);
bg.add(jmeterButton);
jmeterButton.setSelected(true);
systemButton.setActionCommand(SYSTEM);
jmeterButton.setActionCommand(JMETER);
systemButton.addActionListener(this);
jmeterButton.addActionListener(this);
labelPanel.add(systemButton);
labelPanel.add(jmeterButton);
labelPanel.add(tableLabel);
return labelPanel;
}
// /**
// * Create a panel containing the add and delete buttons.
// *
// * @return a GUI panel containing the buttons
// */
// private JPanel makeButtonPanel() {// Not currently used
// add = new JButton(JMeterUtils.getResString("add")); // $NON-NLS-1$
// add.setActionCommand(ADD);
// add.setEnabled(true);
//
// delete = new JButton(JMeterUtils.getResString("delete")); // $NON-NLS-1$
// delete.setActionCommand(DELETE);
//
// JPanel buttonPanel = new JPanel();
// buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
// add.addActionListener(this);
// delete.addActionListener(this);
// buttonPanel.add(add);
// buttonPanel.add(delete);
// return buttonPanel;
// }
/**
* Initialize the components and layout of this component.
*/
private void init() {
JPanel p = this;
setLayout(new BorderLayout(0, 5));
setBorder(makeBorder());
add(makeTitlePanel(), BorderLayout.NORTH);
p = new JPanel();
p.setLayout(new BorderLayout());
p.add(makeLabelPanel(), BorderLayout.NORTH);
p.add(makeMainPanel(), BorderLayout.CENTER);
// Force a minimum table height of 70 pixels
p.add(Box.createVerticalStrut(70), BorderLayout.WEST);
//p.add(makeButtonPanel(), BorderLayout.SOUTH);
add(p, BorderLayout.CENTER);
table.revalidate();
}
private void initializeTableModel() {
tableModel = new ObjectTableModel(new String[] { COLUMN_NAMES_0, COLUMN_NAMES_1 },
new Functor[] {
new Functor(Map.Entry.class, "getKey"), // $NON-NLS-1$
new Functor(Map.Entry.class, "getValue") }, // $NON-NLS-1$
new Functor[] {
null, //new Functor("setName"), // $NON-NLS-1$
new Functor(Map.Entry.class,"setValue", new Class[] { Object.class }) // $NON-NLS-1$
},
new Class[] { String.class, String.class });
}
} | src/components/org/apache/jmeter/visualizers/PropertyControlGui.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.visualizers;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
//import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
//import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import org.apache.jmeter.config.ConfigTestElement;
import org.apache.jmeter.config.gui.AbstractConfigGui;
import org.apache.jmeter.gui.UnsharedComponent;
import org.apache.jmeter.gui.util.HeaderAsPropertyRenderer;
import org.apache.jmeter.gui.util.MenuFactory;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.gui.ObjectTableModel;
import org.apache.jorphan.reflect.Functor;
public class PropertyControlGui extends AbstractConfigGui
implements ActionListener, UnsharedComponent {
private static final long serialVersionUID = 1L;
private static final String COLUMN_NAMES_0 = "name"; // $NON-NLS-1$
private static final String COLUMN_NAMES_1 = "value"; // $NON-NLS-1$
// TODO: add and delete not currently supported
private static final String ADD = "add"; // $NON-NLS-1$
private static final String DELETE = "delete"; // $NON-NLS-1$
private static final String SYSTEM = "system"; // $NON-NLS-1$
private static final String JMETER = "jmeter"; // $NON-NLS-1$
private JCheckBox systemButton = new JCheckBox("System");
private JCheckBox jmeterButton = new JCheckBox("JMeter");
private JLabel tableLabel = new JLabel("Properties");
/** The table containing the list of arguments. */
private transient JTable table;
/** The model for the arguments table. */
protected transient ObjectTableModel tableModel;
// /** A button for adding new arguments to the table. */
// private JButton add;
//
// /** A button for removing arguments from the table. */
// private JButton delete;
public PropertyControlGui() {
super();
init();
}
public String getLabelResource() {
return "property_visualiser_title"; // $NON-NLS-1$
}
@Override
public Collection<String> getMenuCategories() {
return Arrays.asList(new String[] { MenuFactory.NON_TEST_ELEMENTS });
}
public void actionPerformed(ActionEvent action) {
String command = action.getActionCommand();
if (ADD.equals(command)){
return;
}
if (DELETE.equals(command)){
return;
}
if (SYSTEM.equals(command)){
setUpData();
return;
}
if (JMETER.equals(command)){
setUpData();
return;
}
}
public TestElement createTestElement() {
TestElement el = new ConfigTestElement();
modifyTestElement(el);
return el;
}
@Override
public void configure(TestElement element) {
super.configure(element);
setUpData();
}
private void setUpData(){
tableModel.clearData();
Properties p=null;
if (systemButton.isSelected()){
p = System.getProperties();
}
if (jmeterButton.isSelected()) {
p = JMeterUtils.getJMeterProperties();
}
if (p == null) {
return;
}
Set<Map.Entry<Object, Object>> s = p.entrySet();
ArrayList<Map.Entry<Object, Object>> al = new ArrayList<Map.Entry<Object, Object>>(s);
Collections.sort(al, new Comparator<Map.Entry<Object, Object>>(){
public int compare(Map.Entry<Object, Object> o1, Map.Entry<Object, Object> o2) {
String m1,m2;
m1=(String)o1.getKey();
m2=(String)o2.getKey();
return m1.compareTo(m2);
}
});
Iterator<Map.Entry<Object, Object>> i = al.iterator();
while(i.hasNext()){
tableModel.addRow(i.next());
}
}
public void modifyTestElement(TestElement element) {
configureTestElement(element);
}
private Component makeMainPanel() {
initializeTableModel();
table = new JTable(tableModel);
table.getTableHeader().setDefaultRenderer(new HeaderAsPropertyRenderer());
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
return makeScrollPane(table);
}
/**
* Create a panel containing the title label for the table.
*
* @return a panel containing the title label
*/
private Component makeLabelPanel() {
JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
ButtonGroup bg = new ButtonGroup();
bg.add(systemButton);
bg.add(jmeterButton);
jmeterButton.setSelected(true);
systemButton.setActionCommand(SYSTEM);
jmeterButton.setActionCommand(JMETER);
systemButton.addActionListener(this);
jmeterButton.addActionListener(this);
labelPanel.add(systemButton);
labelPanel.add(jmeterButton);
labelPanel.add(tableLabel);
return labelPanel;
}
// /**
// * Create a panel containing the add and delete buttons.
// *
// * @return a GUI panel containing the buttons
// */
// private JPanel makeButtonPanel() {// Not currently used
// add = new JButton(JMeterUtils.getResString("add")); // $NON-NLS-1$
// add.setActionCommand(ADD);
// add.setEnabled(true);
//
// delete = new JButton(JMeterUtils.getResString("delete")); // $NON-NLS-1$
// delete.setActionCommand(DELETE);
//
// JPanel buttonPanel = new JPanel();
// buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
// add.addActionListener(this);
// delete.addActionListener(this);
// buttonPanel.add(add);
// buttonPanel.add(delete);
// return buttonPanel;
// }
/**
* Initialize the components and layout of this component.
*/
private void init() {
JPanel p = this;
setLayout(new BorderLayout(0, 5));
setBorder(makeBorder());
add(makeTitlePanel(), BorderLayout.NORTH);
p = new JPanel();
p.setLayout(new BorderLayout());
p.add(makeLabelPanel(), BorderLayout.NORTH);
p.add(makeMainPanel(), BorderLayout.CENTER);
// Force a minimum table height of 70 pixels
p.add(Box.createVerticalStrut(70), BorderLayout.WEST);
//p.add(makeButtonPanel(), BorderLayout.SOUTH);
add(p, BorderLayout.CENTER);
table.revalidate();
}
private void initializeTableModel() {
tableModel = new ObjectTableModel(new String[] { COLUMN_NAMES_0, COLUMN_NAMES_1 },
new Functor[] {
new Functor(Map.Entry.class, "getKey"), // $NON-NLS-1$
new Functor(Map.Entry.class, "getValue") }, // $NON-NLS-1$
new Functor[] {
null, //new Functor("setName"), // $NON-NLS-1$
new Functor(Map.Entry.class,"setValue", new Class[] { Object.class }) // $NON-NLS-1$
},
new Class[] { String.class, String.class });
}
} | Unused import
git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1240292 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: bc1cd56ddb94c0e57279d05a8243d82083135664 | src/components/org/apache/jmeter/visualizers/PropertyControlGui.java | Unused import | <ide><path>rc/components/org/apache/jmeter/visualizers/PropertyControlGui.java
<ide> import org.apache.jmeter.gui.UnsharedComponent;
<ide> import org.apache.jmeter.gui.util.HeaderAsPropertyRenderer;
<ide> import org.apache.jmeter.gui.util.MenuFactory;
<del>import org.apache.jmeter.samplers.SampleResult;
<ide> import org.apache.jmeter.testelement.TestElement;
<ide> import org.apache.jmeter.util.JMeterUtils;
<ide> import org.apache.jorphan.gui.ObjectTableModel; |
|
JavaScript | mit | eb75508e8c4c145d58f9f5edcaeed9e73942ce47 | 0 | alexisvincent/systemjs-tools,alexisvincent/systemjs-tools | import 'systemjs-hmr/dist/next.js'
import io from 'socket.io-client'
const storage = {
_socket: null
}
const run = (name, fn, ...args) => (
storage[name] ?
storage[name] :
Promise.resolve(fn.apply(args)).then(result => {
storage[name] = result || true
})
)
const defaultOptions = {
port: 1337
}
let config = {}
const connect = (opts = {}) => {
const options = Object.assign({}, defaultOptions, opts)
if (storage._socket == null) {
let socket = storage._socket = io("https://" + window.location.hostname + ":" + options.port)
socket.on('connect', () => {
socket.emit('identification', navigator.userAgent)
})
socket.on('config', c => {
config = c
})
socket.on('reload', () => {
document.location.reload(true)
})
socket.on('change', (event) => {
System.reload(event.path, {
// Untill systemjs-hmr normalizes roots
roots: config.entries.map(System.normalizeSync)
})
})
}
}
export {storage, run, connect}
| lib/client.js | import 'systemjs-hmr/dist/next.js'
import io from 'socket.io-client'
const storage = {
_socket: null
}
const run = (name, fn, ...args) => (
storage[name] ?
storage[name] :
Promise.resolve(fn.apply(args)).then(result => {
storage[name] = result || true
})
)
const defaultOptions = {
port: 1337
}
let config = {}
const connect = (opts = {}) => {
const options = Object.assign({}, defaultOptions, opts)
if (storage._socket == null) {
let socket = storage._socket = io("https://" + window.location.hostname + ":" + options.port)
socket.on('connect', () => {
socket.emit('identification', navigator.userAgent)
})
socket.on('config', c => {
config = c
})
socket.on('reload', () => {
document.location.reload(true)
})
socket.on('change', (event) => {
System.reload(event.path, {
roots: config.entries
})
})
}
}
export {storage, run, connect}
| Normalize roots
| lib/client.js | Normalize roots | <ide><path>ib/client.js
<ide>
<ide> socket.on('change', (event) => {
<ide> System.reload(event.path, {
<del> roots: config.entries
<add> // Untill systemjs-hmr normalizes roots
<add> roots: config.entries.map(System.normalizeSync)
<ide> })
<ide> })
<ide> } |
|
Java | mit | 1c74641e9144d082206eca1f6973c3b90227915d | 0 | ns163/jenkins,tfennelly/jenkins,DanielWeber/jenkins,SebastienGllmt/jenkins,rsandell/jenkins,viqueen/jenkins,aldaris/jenkins,escoem/jenkins,bkmeneguello/jenkins,1and1/jenkins,morficus/jenkins,svanoort/jenkins,aldaris/jenkins,arcivanov/jenkins,ajshastri/jenkins,godfath3r/jenkins,paulmillar/jenkins,oleg-nenashev/jenkins,elkingtonmcb/jenkins,gitaccountforprashant/gittest,mrooney/jenkins,vvv444/jenkins,aldaris/jenkins,elkingtonmcb/jenkins,rlugojr/jenkins,hemantojhaa/jenkins,FTG-003/jenkins,ydubreuil/jenkins,duzifang/my-jenkins,alvarolobato/jenkins,seanlin816/jenkins,ErikVerheul/jenkins,oleg-nenashev/jenkins,luoqii/jenkins,kohsuke/hudson,kohsuke/hudson,arcivanov/jenkins,SebastienGllmt/jenkins,Vlatombe/jenkins,Jochen-A-Fuerbacher/jenkins,elkingtonmcb/jenkins,aduprat/jenkins,mdonohue/jenkins,everyonce/jenkins,mcanthony/jenkins,lordofthejars/jenkins,liupugong/jenkins,dbroady1/jenkins,huybrechts/hudson,damianszczepanik/jenkins,FTG-003/jenkins,ikedam/jenkins,liupugong/jenkins,ns163/jenkins,bpzhang/jenkins,kohsuke/hudson,duzifang/my-jenkins,lindzh/jenkins,hashar/jenkins,batmat/jenkins,FarmGeek4Life/jenkins,protazy/jenkins,christ66/jenkins,evernat/jenkins,arunsingh/jenkins,svanoort/jenkins,azweb76/jenkins,vijayto/jenkins,1and1/jenkins,MarkEWaite/jenkins,rashmikanta-1984/jenkins,AustinKwang/jenkins,jhoblitt/jenkins,paulwellnerbou/jenkins,andresrc/jenkins,singh88/jenkins,csimons/jenkins,amuniz/jenkins,jglick/jenkins,patbos/jenkins,huybrechts/hudson,recena/jenkins,aduprat/jenkins,batmat/jenkins,tangkun75/jenkins,DanielWeber/jenkins,jpbriend/jenkins,Ykus/jenkins,azweb76/jenkins,kohsuke/hudson,oleg-nenashev/jenkins,gusreiber/jenkins,sathiya-mit/jenkins,batmat/jenkins,mrooney/jenkins,jhoblitt/jenkins,sathiya-mit/jenkins,bpzhang/jenkins,mdonohue/jenkins,amruthsoft9/Jenkis,duzifang/my-jenkins,hemantojhaa/jenkins,daniel-beck/jenkins,tastatur/jenkins,v1v/jenkins,verbitan/jenkins,CodeShane/jenkins,petermarcoen/jenkins,hplatou/jenkins,292388900/jenkins,soenter/jenkins,liupugong/jenkins,jglick/jenkins,MichaelPranovich/jenkins_sc,jenkinsci/jenkins,amuniz/jenkins,ErikVerheul/jenkins,morficus/jenkins,aldaris/jenkins,hplatou/jenkins,ChrisA89/jenkins,seanlin816/jenkins,mcanthony/jenkins,everyonce/jenkins,andresrc/jenkins,arunsingh/jenkins,lindzh/jenkins,MichaelPranovich/jenkins_sc,verbitan/jenkins,arcivanov/jenkins,gitaccountforprashant/gittest,hashar/jenkins,arunsingh/jenkins,SenolOzer/jenkins,patbos/jenkins,NehemiahMi/jenkins,fbelzunc/jenkins,ikedam/jenkins,morficus/jenkins,morficus/jenkins,svanoort/jenkins,arunsingh/jenkins,tastatur/jenkins,tfennelly/jenkins,my7seven/jenkins,csimons/jenkins,rlugojr/jenkins,christ66/jenkins,hplatou/jenkins,ikedam/jenkins,NehemiahMi/jenkins,jglick/jenkins,petermarcoen/jenkins,pjanouse/jenkins,MichaelPranovich/jenkins_sc,aldaris/jenkins,andresrc/jenkins,ndeloof/jenkins,hashar/jenkins,tfennelly/jenkins,intelchen/jenkins,akshayabd/jenkins,jpederzolli/jenkins-1,viqueen/jenkins,varmenise/jenkins,mrooney/jenkins,kzantow/jenkins,rashmikanta-1984/jenkins,aquarellian/jenkins,dennisjlee/jenkins,rsandell/jenkins,seanlin816/jenkins,escoem/jenkins,alvarolobato/jenkins,akshayabd/jenkins,SenolOzer/jenkins,svanoort/jenkins,aldaris/jenkins,SebastienGllmt/jenkins,mcanthony/jenkins,daniel-beck/jenkins,guoxu0514/jenkins,lordofthejars/jenkins,Krasnyanskiy/jenkins,lindzh/jenkins,vvv444/jenkins,pselle/jenkins,CodeShane/jenkins,noikiy/jenkins,protazy/jenkins,dbroady1/jenkins,daniel-beck/jenkins,wuwen5/jenkins,rsandell/jenkins,svanoort/jenkins,lindzh/jenkins,ErikVerheul/jenkins,paulwellnerbou/jenkins,Jimilian/jenkins,DanielWeber/jenkins,paulwellnerbou/jenkins,jenkinsci/jenkins,wuwen5/jenkins,wangyikai/jenkins,noikiy/jenkins,Jimilian/jenkins,yonglehou/jenkins,hplatou/jenkins,CodeShane/jenkins,ydubreuil/jenkins,MichaelPranovich/jenkins_sc,yonglehou/jenkins,aduprat/jenkins,amuniz/jenkins,jpederzolli/jenkins-1,lordofthejars/jenkins,guoxu0514/jenkins,hashar/jenkins,FarmGeek4Life/jenkins,dbroady1/jenkins,oleg-nenashev/jenkins,Jimilian/jenkins,vjuranek/jenkins,guoxu0514/jenkins,vvv444/jenkins,vvv444/jenkins,v1v/jenkins,luoqii/jenkins,protazy/jenkins,SebastienGllmt/jenkins,amuniz/jenkins,samatdav/jenkins,arcivanov/jenkins,ydubreuil/jenkins,khmarbaise/jenkins,luoqii/jenkins,vlajos/jenkins,lilyJi/jenkins,ErikVerheul/jenkins,scoheb/jenkins,khmarbaise/jenkins,viqueen/jenkins,6WIND/jenkins,mattclark/jenkins,fbelzunc/jenkins,damianszczepanik/jenkins,patbos/jenkins,jpederzolli/jenkins-1,wuwen5/jenkins,jk47/jenkins,jhoblitt/jenkins,godfath3r/jenkins,ikedam/jenkins,escoem/jenkins,liupugong/jenkins,vjuranek/jenkins,v1v/jenkins,ajshastri/jenkins,Vlatombe/jenkins,hemantojhaa/jenkins,alvarolobato/jenkins,jpbriend/jenkins,luoqii/jenkins,godfath3r/jenkins,oleg-nenashev/jenkins,fbelzunc/jenkins,msrb/jenkins,kzantow/jenkins,NehemiahMi/jenkins,noikiy/jenkins,escoem/jenkins,dennisjlee/jenkins,292388900/jenkins,ndeloof/jenkins,varmenise/jenkins,amruthsoft9/Jenkis,bpzhang/jenkins,Jochen-A-Fuerbacher/jenkins,Krasnyanskiy/jenkins,azweb76/jenkins,olivergondza/jenkins,mdonohue/jenkins,arcivanov/jenkins,1and1/jenkins,aduprat/jenkins,duzifang/my-jenkins,NehemiahMi/jenkins,CodeShane/jenkins,MichaelPranovich/jenkins_sc,ndeloof/jenkins,escoem/jenkins,292388900/jenkins,hemantojhaa/jenkins,tastatur/jenkins,pjanouse/jenkins,protazy/jenkins,rsandell/jenkins,vijayto/jenkins,Vlatombe/jenkins,1and1/jenkins,vjuranek/jenkins,fbelzunc/jenkins,akshayabd/jenkins,pselle/jenkins,bkmeneguello/jenkins,scoheb/jenkins,dariver/jenkins,tangkun75/jenkins,dennisjlee/jenkins,SenolOzer/jenkins,paulmillar/jenkins,paulwellnerbou/jenkins,khmarbaise/jenkins,rsandell/jenkins,Krasnyanskiy/jenkins,Jimilian/jenkins,jk47/jenkins,wangyikai/jenkins,elkingtonmcb/jenkins,luoqii/jenkins,jpbriend/jenkins,ydubreuil/jenkins,vlajos/jenkins,varmenise/jenkins,fbelzunc/jenkins,MichaelPranovich/jenkins_sc,dennisjlee/jenkins,DanielWeber/jenkins,godfath3r/jenkins,soenter/jenkins,everyonce/jenkins,aquarellian/jenkins,ErikVerheul/jenkins,intelchen/jenkins,msrb/jenkins,lilyJi/jenkins,olivergondza/jenkins,andresrc/jenkins,jpbriend/jenkins,Ykus/jenkins,akshayabd/jenkins,alvarolobato/jenkins,jhoblitt/jenkins,aquarellian/jenkins,akshayabd/jenkins,sathiya-mit/jenkins,recena/jenkins,huybrechts/hudson,kohsuke/hudson,intelchen/jenkins,amuniz/jenkins,azweb76/jenkins,jpederzolli/jenkins-1,guoxu0514/jenkins,Krasnyanskiy/jenkins,rlugojr/jenkins,FTG-003/jenkins,ajshastri/jenkins,gitaccountforprashant/gittest,liupugong/jenkins,lilyJi/jenkins,scoheb/jenkins,noikiy/jenkins,noikiy/jenkins,ns163/jenkins,pjanouse/jenkins,batmat/jenkins,mdonohue/jenkins,singh88/jenkins,rsandell/jenkins,SebastienGllmt/jenkins,damianszczepanik/jenkins,patbos/jenkins,khmarbaise/jenkins,CodeShane/jenkins,viqueen/jenkins,akshayabd/jenkins,sathiya-mit/jenkins,azweb76/jenkins,seanlin816/jenkins,FarmGeek4Life/jenkins,mattclark/jenkins,csimons/jenkins,svanoort/jenkins,Vlatombe/jenkins,rlugojr/jenkins,arunsingh/jenkins,lordofthejars/jenkins,christ66/jenkins,stephenc/jenkins,ChrisA89/jenkins,my7seven/jenkins,singh88/jenkins,hplatou/jenkins,aquarellian/jenkins,wangyikai/jenkins,csimons/jenkins,khmarbaise/jenkins,svanoort/jenkins,oleg-nenashev/jenkins,duzifang/my-jenkins,gitaccountforprashant/gittest,amruthsoft9/Jenkis,mrooney/jenkins,Ykus/jenkins,ajshastri/jenkins,christ66/jenkins,luoqii/jenkins,rlugojr/jenkins,kzantow/jenkins,jenkinsci/jenkins,soenter/jenkins,bpzhang/jenkins,ChrisA89/jenkins,daniel-beck/jenkins,paulmillar/jenkins,bkmeneguello/jenkins,SenolOzer/jenkins,Ykus/jenkins,soenter/jenkins,AustinKwang/jenkins,pjanouse/jenkins,jenkinsci/jenkins,tastatur/jenkins,scoheb/jenkins,v1v/jenkins,Ykus/jenkins,wuwen5/jenkins,arunsingh/jenkins,Vlatombe/jenkins,mattclark/jenkins,FTG-003/jenkins,rashmikanta-1984/jenkins,arunsingh/jenkins,lordofthejars/jenkins,paulmillar/jenkins,duzifang/my-jenkins,tfennelly/jenkins,mdonohue/jenkins,my7seven/jenkins,patbos/jenkins,daniel-beck/jenkins,jenkinsci/jenkins,huybrechts/hudson,aduprat/jenkins,AustinKwang/jenkins,SenolOzer/jenkins,Jochen-A-Fuerbacher/jenkins,samatdav/jenkins,yonglehou/jenkins,FarmGeek4Life/jenkins,dbroady1/jenkins,jk47/jenkins,mcanthony/jenkins,intelchen/jenkins,kzantow/jenkins,ndeloof/jenkins,seanlin816/jenkins,dennisjlee/jenkins,wangyikai/jenkins,lindzh/jenkins,evernat/jenkins,jk47/jenkins,verbitan/jenkins,mcanthony/jenkins,Jimilian/jenkins,bkmeneguello/jenkins,amruthsoft9/Jenkis,jglick/jenkins,FTG-003/jenkins,batmat/jenkins,batmat/jenkins,petermarcoen/jenkins,AustinKwang/jenkins,my7seven/jenkins,Krasnyanskiy/jenkins,rashmikanta-1984/jenkins,jhoblitt/jenkins,daniel-beck/jenkins,hashar/jenkins,noikiy/jenkins,wuwen5/jenkins,hemantojhaa/jenkins,aduprat/jenkins,FarmGeek4Life/jenkins,recena/jenkins,gitaccountforprashant/gittest,6WIND/jenkins,tangkun75/jenkins,protazy/jenkins,my7seven/jenkins,bkmeneguello/jenkins,CodeShane/jenkins,damianszczepanik/jenkins,rsandell/jenkins,pjanouse/jenkins,kzantow/jenkins,6WIND/jenkins,vvv444/jenkins,jhoblitt/jenkins,gusreiber/jenkins,dariver/jenkins,petermarcoen/jenkins,AustinKwang/jenkins,paulwellnerbou/jenkins,tangkun75/jenkins,mcanthony/jenkins,godfath3r/jenkins,amruthsoft9/Jenkis,MarkEWaite/jenkins,v1v/jenkins,dbroady1/jenkins,arcivanov/jenkins,patbos/jenkins,samatdav/jenkins,verbitan/jenkins,andresrc/jenkins,my7seven/jenkins,gusreiber/jenkins,huybrechts/hudson,bkmeneguello/jenkins,petermarcoen/jenkins,pjanouse/jenkins,paulwellnerbou/jenkins,hemantojhaa/jenkins,soenter/jenkins,MarkEWaite/jenkins,intelchen/jenkins,ndeloof/jenkins,mrooney/jenkins,tfennelly/jenkins,jpederzolli/jenkins-1,godfath3r/jenkins,olivergondza/jenkins,Vlatombe/jenkins,alvarolobato/jenkins,escoem/jenkins,ajshastri/jenkins,aduprat/jenkins,paulmillar/jenkins,soenter/jenkins,christ66/jenkins,jpbriend/jenkins,patbos/jenkins,jk47/jenkins,tastatur/jenkins,aquarellian/jenkins,rashmikanta-1984/jenkins,andresrc/jenkins,khmarbaise/jenkins,1and1/jenkins,pselle/jenkins,ndeloof/jenkins,rashmikanta-1984/jenkins,my7seven/jenkins,vjuranek/jenkins,Krasnyanskiy/jenkins,olivergondza/jenkins,ns163/jenkins,Vlatombe/jenkins,jpbriend/jenkins,kzantow/jenkins,vlajos/jenkins,elkingtonmcb/jenkins,tfennelly/jenkins,mrooney/jenkins,evernat/jenkins,lordofthejars/jenkins,jk47/jenkins,FarmGeek4Life/jenkins,1and1/jenkins,mattclark/jenkins,recena/jenkins,andresrc/jenkins,ns163/jenkins,6WIND/jenkins,jpederzolli/jenkins-1,amuniz/jenkins,vvv444/jenkins,Ykus/jenkins,Jochen-A-Fuerbacher/jenkins,vlajos/jenkins,batmat/jenkins,mdonohue/jenkins,stephenc/jenkins,DanielWeber/jenkins,ikedam/jenkins,dariver/jenkins,DanielWeber/jenkins,hemantojhaa/jenkins,scoheb/jenkins,ydubreuil/jenkins,ikedam/jenkins,gusreiber/jenkins,amruthsoft9/Jenkis,hplatou/jenkins,wangyikai/jenkins,huybrechts/hudson,petermarcoen/jenkins,wangyikai/jenkins,kohsuke/hudson,damianszczepanik/jenkins,SebastienGllmt/jenkins,morficus/jenkins,morficus/jenkins,pselle/jenkins,kohsuke/hudson,lilyJi/jenkins,viqueen/jenkins,samatdav/jenkins,pjanouse/jenkins,ikedam/jenkins,wuwen5/jenkins,CodeShane/jenkins,stephenc/jenkins,csimons/jenkins,ndeloof/jenkins,gusreiber/jenkins,yonglehou/jenkins,jk47/jenkins,wuwen5/jenkins,hplatou/jenkins,SenolOzer/jenkins,bpzhang/jenkins,Jochen-A-Fuerbacher/jenkins,yonglehou/jenkins,evernat/jenkins,soenter/jenkins,lilyJi/jenkins,evernat/jenkins,Jochen-A-Fuerbacher/jenkins,mattclark/jenkins,evernat/jenkins,ChrisA89/jenkins,NehemiahMi/jenkins,msrb/jenkins,liupugong/jenkins,arcivanov/jenkins,paulmillar/jenkins,ErikVerheul/jenkins,vvv444/jenkins,vlajos/jenkins,vlajos/jenkins,azweb76/jenkins,292388900/jenkins,tastatur/jenkins,gusreiber/jenkins,christ66/jenkins,varmenise/jenkins,varmenise/jenkins,bpzhang/jenkins,vijayto/jenkins,lindzh/jenkins,gitaccountforprashant/gittest,olivergondza/jenkins,recena/jenkins,jpbriend/jenkins,msrb/jenkins,NehemiahMi/jenkins,singh88/jenkins,duzifang/my-jenkins,vijayto/jenkins,jpederzolli/jenkins-1,dariver/jenkins,viqueen/jenkins,vijayto/jenkins,lilyJi/jenkins,6WIND/jenkins,everyonce/jenkins,jglick/jenkins,tangkun75/jenkins,jenkinsci/jenkins,daniel-beck/jenkins,FarmGeek4Life/jenkins,lindzh/jenkins,damianszczepanik/jenkins,292388900/jenkins,stephenc/jenkins,dariver/jenkins,godfath3r/jenkins,singh88/jenkins,sathiya-mit/jenkins,mattclark/jenkins,aldaris/jenkins,paulmillar/jenkins,6WIND/jenkins,dariver/jenkins,jglick/jenkins,mattclark/jenkins,bpzhang/jenkins,sathiya-mit/jenkins,varmenise/jenkins,mrooney/jenkins,petermarcoen/jenkins,msrb/jenkins,guoxu0514/jenkins,olivergondza/jenkins,everyonce/jenkins,stephenc/jenkins,vjuranek/jenkins,dennisjlee/jenkins,tangkun75/jenkins,aquarellian/jenkins,ajshastri/jenkins,vijayto/jenkins,azweb76/jenkins,ns163/jenkins,ydubreuil/jenkins,Jimilian/jenkins,vjuranek/jenkins,paulwellnerbou/jenkins,ns163/jenkins,rlugojr/jenkins,ajshastri/jenkins,MarkEWaite/jenkins,oleg-nenashev/jenkins,guoxu0514/jenkins,lilyJi/jenkins,alvarolobato/jenkins,tfennelly/jenkins,AustinKwang/jenkins,escoem/jenkins,alvarolobato/jenkins,khmarbaise/jenkins,dbroady1/jenkins,AustinKwang/jenkins,NehemiahMi/jenkins,hashar/jenkins,DanielWeber/jenkins,gitaccountforprashant/gittest,morficus/jenkins,tastatur/jenkins,pselle/jenkins,sathiya-mit/jenkins,mdonohue/jenkins,ikedam/jenkins,amuniz/jenkins,dbroady1/jenkins,olivergondza/jenkins,292388900/jenkins,FTG-003/jenkins,amruthsoft9/Jenkis,1and1/jenkins,liupugong/jenkins,SebastienGllmt/jenkins,FTG-003/jenkins,evernat/jenkins,msrb/jenkins,yonglehou/jenkins,vijayto/jenkins,singh88/jenkins,scoheb/jenkins,csimons/jenkins,jglick/jenkins,samatdav/jenkins,intelchen/jenkins,kzantow/jenkins,jenkinsci/jenkins,samatdav/jenkins,fbelzunc/jenkins,6WIND/jenkins,noikiy/jenkins,luoqii/jenkins,samatdav/jenkins,jenkinsci/jenkins,elkingtonmcb/jenkins,elkingtonmcb/jenkins,Jimilian/jenkins,csimons/jenkins,damianszczepanik/jenkins,pselle/jenkins,seanlin816/jenkins,guoxu0514/jenkins,scoheb/jenkins,pselle/jenkins,huybrechts/hudson,v1v/jenkins,MarkEWaite/jenkins,recena/jenkins,vlajos/jenkins,verbitan/jenkins,dennisjlee/jenkins,dariver/jenkins,hashar/jenkins,verbitan/jenkins,rashmikanta-1984/jenkins,ErikVerheul/jenkins,stephenc/jenkins,lordofthejars/jenkins,damianszczepanik/jenkins,everyonce/jenkins,yonglehou/jenkins,akshayabd/jenkins,protazy/jenkins,intelchen/jenkins,recena/jenkins,daniel-beck/jenkins,fbelzunc/jenkins,aquarellian/jenkins,rlugojr/jenkins,v1v/jenkins,MarkEWaite/jenkins,MarkEWaite/jenkins,ChrisA89/jenkins,292388900/jenkins,msrb/jenkins,MarkEWaite/jenkins,ChrisA89/jenkins,singh88/jenkins,vjuranek/jenkins,ydubreuil/jenkins,tangkun75/jenkins,mcanthony/jenkins,ChrisA89/jenkins,jhoblitt/jenkins,Ykus/jenkins,verbitan/jenkins,viqueen/jenkins,gusreiber/jenkins,varmenise/jenkins,stephenc/jenkins,rsandell/jenkins,MichaelPranovich/jenkins_sc,Jochen-A-Fuerbacher/jenkins,seanlin816/jenkins,wangyikai/jenkins,christ66/jenkins,SenolOzer/jenkins,bkmeneguello/jenkins,kohsuke/hudson,Krasnyanskiy/jenkins,everyonce/jenkins,protazy/jenkins | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util;
import hudson.ExtensionPoint;
import hudson.security.SecurityRealm;
import jenkins.model.Jenkins;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Servlet {@link Filter} that chains multiple {@link Filter}s, provided by plugins
*
* <p>
* While this class by itself is not an extension point, I'm marking this class
* as an extension point so that this class will be more discoverable.
*
* <p>
* {@link SecurityRealm} that wants to contribute {@link Filter}s should first
* check if {@link SecurityRealm#createFilter(FilterConfig)} is more appropriate.
*
* @see SecurityRealm
*/
public class PluginServletFilter implements Filter, ExtensionPoint {
private final List<Filter> list = new CopyOnWriteArrayList<Filter>();
private /*almost final*/ FilterConfig config;
/**
* For backward compatibility with plugins that might register filters before Jenkins.getInstance()
* starts functioning, when we are not sure which Jenkins instance a filter belongs to, put it here,
* and let the first Jenkins instance take over.
*/
private static final List<Filter> LEGACY = new Vector<Filter>();
private static final String KEY = PluginServletFilter.class.getName();
/**
* Lookup the instance from servlet context.
*/
private static PluginServletFilter getInstance(ServletContext c) {
return (PluginServletFilter)c.getAttribute(KEY);
}
public void init(FilterConfig config) throws ServletException {
this.config = config;
synchronized (LEGACY) {
list.addAll(LEGACY);
LEGACY.clear();
}
for (Filter f : list) {
f.init(config);
}
config.getServletContext().setAttribute(KEY,this);
}
public static void addFilter(Filter filter) throws ServletException {
Jenkins j = Jenkins.getInstance();
// https://marvelution.atlassian.net/browse/JJI-188
if (j==null || getInstance(j.servletContext) == null) {
// report who is doing legacy registration
LOGGER.log(Level.WARNING, "Filter instance is registered too early: "+filter, new Exception());
LEGACY.add(filter);
} else {
PluginServletFilter container = getInstance(j.servletContext);
filter.init(container.config);
container.list.add(filter);
}
}
public static void removeFilter(Filter filter) throws ServletException {
Jenkins j = Jenkins.getInstance();
if (j==null || getInstance(j.servletContext) == null) {
LEGACY.remove(filter);
} else {
getInstance(j.servletContext).list.remove(filter);
}
}
public void doFilter(ServletRequest request, ServletResponse response, final FilterChain chain) throws IOException, ServletException {
new FilterChain() {
private final Iterator<Filter> itr = list.iterator();
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
if(itr.hasNext()) {
// call next
itr.next().doFilter(request, response, this);
} else {
// reached to the end
chain.doFilter(request,response);
}
}
}.doFilter(request,response);
}
public void destroy() {
for (Filter f : list) {
f.destroy();
}
list.clear();
}
private static final Logger LOGGER = Logger.getLogger(PluginServletFilter.class.getName());
}
| core/src/main/java/hudson/util/PluginServletFilter.java | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util;
import hudson.ExtensionPoint;
import hudson.security.SecurityRealm;
import jenkins.model.Jenkins;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Servlet {@link Filter} that chains multiple {@link Filter}s, provided by plugins
*
* <p>
* While this class by itself is not an extension point, I'm marking this class
* as an extension point so that this class will be more discoverable.
*
* <p>
* {@link SecurityRealm} that wants to contribute {@link Filter}s should first
* check if {@link SecurityRealm#createFilter(FilterConfig)} is more appropriate.
*
* @see SecurityRealm
*/
public class PluginServletFilter implements Filter, ExtensionPoint {
private final List<Filter> list = new CopyOnWriteArrayList<Filter>();
private /*almost final*/ FilterConfig config;
/**
* For backward compatibility with plugins that might register filters before Jenkins.getInstance()
* starts functioning, when we are not sure which Jenkins instance a filter belongs to, put it here,
* and let the first Jenkins instance take over.
*/
private static final List<Filter> LEGACY = new Vector<Filter>();
private static final String KEY = PluginServletFilter.class.getName();
/**
* Lookup the instance from servlet context.
*/
private static PluginServletFilter getInstance(ServletContext c) {
return (PluginServletFilter)c.getAttribute(KEY);
}
public void init(FilterConfig config) throws ServletException {
this.config = config;
synchronized (LEGACY) {
list.addAll(LEGACY);
LEGACY.clear();
}
for (Filter f : list) {
f.init(config);
}
config.getServletContext().setAttribute(KEY,this);
}
public static void addFilter(Filter filter) throws ServletException {
Jenkins j = Jenkins.getInstance();
if (j==null) {
// report who is doing legacy registration
LOGGER.log(Level.WARNING, "Filter instance is registered too early: "+filter, new Exception());
LEGACY.add(filter);
} else {
PluginServletFilter container = getInstance(j.servletContext);
filter.init(container.config);
container.list.add(filter);
}
}
public static void removeFilter(Filter filter) throws ServletException {
Jenkins j = Jenkins.getInstance();
if (j==null) {
LEGACY.remove(filter);
} else {
getInstance(j.servletContext).list.remove(filter);
}
}
public void doFilter(ServletRequest request, ServletResponse response, final FilterChain chain) throws IOException, ServletException {
new FilterChain() {
private final Iterator<Filter> itr = list.iterator();
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
if(itr.hasNext()) {
// call next
itr.next().doFilter(request, response, this);
} else {
// reached to the end
chain.doFilter(request,response);
}
}
}.doFilter(request,response);
}
public void destroy() {
for (Filter f : list) {
f.destroy();
}
list.clear();
}
private static final Logger LOGGER = Logger.getLogger(PluginServletFilter.class.getName());
}
| * Add a more stable workaround for adding PluginServletFilter when they
are not available yet e.g.
https://marvelution.atlassian.net/browse/JJI-188 | core/src/main/java/hudson/util/PluginServletFilter.java | * Add a more stable workaround for adding PluginServletFilter when they are not available yet e.g. https://marvelution.atlassian.net/browse/JJI-188 | <ide><path>ore/src/main/java/hudson/util/PluginServletFilter.java
<ide>
<ide> public static void addFilter(Filter filter) throws ServletException {
<ide> Jenkins j = Jenkins.getInstance();
<del> if (j==null) {
<add> // https://marvelution.atlassian.net/browse/JJI-188
<add> if (j==null || getInstance(j.servletContext) == null) {
<ide> // report who is doing legacy registration
<ide> LOGGER.log(Level.WARNING, "Filter instance is registered too early: "+filter, new Exception());
<ide> LEGACY.add(filter);
<ide>
<ide> public static void removeFilter(Filter filter) throws ServletException {
<ide> Jenkins j = Jenkins.getInstance();
<del> if (j==null) {
<add> if (j==null || getInstance(j.servletContext) == null) {
<ide> LEGACY.remove(filter);
<ide> } else {
<ide> getInstance(j.servletContext).list.remove(filter); |
|
Java | apache-2.0 | e15291ee376e30a05bf294a7a2205f5d2255df8e | 0 | orekyuu/intellij-community,samthor/intellij-community,clumsy/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,FHannes/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,ahb0327/intellij-community,holmes/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,holmes/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ibinti/intellij-community,izonder/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,adedayo/intellij-community,samthor/intellij-community,caot/intellij-community,slisson/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,ahb0327/intellij-community,slisson/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,retomerz/intellij-community,ryano144/intellij-community,ryano144/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,kool79/intellij-community,consulo/consulo,TangHao1987/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,fnouama/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,consulo/consulo,holmes/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,amith01994/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,slisson/intellij-community,semonte/intellij-community,signed/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,semonte/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,caot/intellij-community,izonder/intellij-community,robovm/robovm-studio,allotria/intellij-community,supersven/intellij-community,supersven/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,holmes/intellij-community,ibinti/intellij-community,vladmm/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,FHannes/intellij-community,slisson/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,Distrotech/intellij-community,da1z/intellij-community,hurricup/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,ernestp/consulo,petteyg/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,samthor/intellij-community,ernestp/consulo,ftomassetti/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,izonder/intellij-community,allotria/intellij-community,semonte/intellij-community,dslomov/intellij-community,hurricup/intellij-community,ernestp/consulo,petteyg/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,holmes/intellij-community,fitermay/intellij-community,asedunov/intellij-community,xfournet/intellij-community,samthor/intellij-community,da1z/intellij-community,retomerz/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,jagguli/intellij-community,supersven/intellij-community,vladmm/intellij-community,samthor/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,signed/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,slisson/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,allotria/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,supersven/intellij-community,allotria/intellij-community,slisson/intellij-community,FHannes/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,holmes/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,izonder/intellij-community,adedayo/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,kdwink/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,caot/intellij-community,allotria/intellij-community,semonte/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,xfournet/intellij-community,diorcety/intellij-community,consulo/consulo,asedunov/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,caot/intellij-community,robovm/robovm-studio,jagguli/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,asedunov/intellij-community,jagguli/intellij-community,izonder/intellij-community,dslomov/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,caot/intellij-community,fitermay/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,signed/intellij-community,signed/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,caot/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,slisson/intellij-community,wreckJ/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,hurricup/intellij-community,supersven/intellij-community,da1z/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,signed/intellij-community,samthor/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,Lekanich/intellij-community,kool79/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,kdwink/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,signed/intellij-community,kdwink/intellij-community,samthor/intellij-community,blademainer/intellij-community,petteyg/intellij-community,kdwink/intellij-community,adedayo/intellij-community,kool79/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,apixandru/intellij-community,semonte/intellij-community,signed/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,fitermay/intellij-community,apixandru/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,allotria/intellij-community,holmes/intellij-community,retomerz/intellij-community,holmes/intellij-community,kool79/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,signed/intellij-community,dslomov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,petteyg/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,caot/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,supersven/intellij-community,ibinti/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,blademainer/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,caot/intellij-community,asedunov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,fitermay/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,diorcety/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,signed/intellij-community,ibinti/intellij-community,izonder/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,slisson/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,semonte/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,signed/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,supersven/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,xfournet/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,izonder/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,clumsy/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,samthor/intellij-community,supersven/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,consulo/consulo,vvv1559/intellij-community,blademainer/intellij-community,ibinti/intellij-community,caot/intellij-community,caot/intellij-community,consulo/consulo,tmpgit/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,hurricup/intellij-community,fnouama/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,adedayo/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,samthor/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,izonder/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,clumsy/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,caot/intellij-community,diorcety/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,slisson/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,allotria/intellij-community,clumsy/intellij-community,da1z/intellij-community,da1z/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,ryano144/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,clumsy/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,kool79/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,apixandru/intellij-community,vladmm/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,ernestp/consulo,clumsy/intellij-community,dslomov/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,supersven/intellij-community,supersven/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,dslomov/intellij-community | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ImageObserver;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.RenderableImage;
import java.text.AttributedCharacterIterator;
import java.util.Map;
/**
* Wrap a graphics2d objects to debug internals paintings
*
* @author Konstantin Bulenkov
*/
@SuppressWarnings("UnusedDeclaration")
public class Graphics2DLog extends Graphics2D {
protected final Graphics2D myPeer;
public Graphics2DLog(Graphics g) {
myPeer = (Graphics2D)g;
}
@SuppressWarnings({"MethodMayBeStatic", "UseOfSystemOutOrSystemErr"})
protected void log(String msg) {
System.out.println(msg);
}
@Override
public void draw3DRect(int x, int y, int width, int height, boolean raised) {
log(String.format("draw3DRect(%d, %d, %d, %d, %b)", x, y, width, height, raised));
myPeer.draw3DRect(x, y, width, height, raised);
}
@Override
public void fill3DRect(int x, int y, int width, int height, boolean raised) {
log(String.format("draw3DRect(%d, %d, %d, %d, %b)", x, y, width, height, raised));
myPeer.fill3DRect(x, y, width, height, raised);
}
@Override
public void draw(Shape s) {
log("draw(" + s + ")");
myPeer.draw(s);
}
@Override
public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) {
log("drawImage(Image, AffineTransform, ImageObserver)");
return myPeer.drawImage(img, xform, obs);
}
@Override
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
log(String.format("drawImage(BufferedImage, BufferedImageOp, %d, %d)", x, y));
myPeer.drawImage(img, op, x, y);
}
@Override
public void drawRenderedImage(RenderedImage img, AffineTransform xform) {
log("drawRenderedImage(RenderedImage, AffineTransform)");
myPeer.drawRenderedImage(img, xform);
}
@Override
public void drawRenderableImage(RenderableImage img, AffineTransform xform) {
log("drawRenderableImage(RenderableImage, AffineTransform)");
myPeer.drawRenderableImage(img, xform);
}
@Override
public void drawString(String str, int x, int y) {
log(String.format("drawString(%s, %d, %d)", str, x, y));
myPeer.drawString(str, x, y);
}
@Override
public void drawString(String str, float x, float y) {
log(String.format("drawString(%s, %f, %f)", str, x, y));
myPeer.drawString(str, x, y);
}
@Override
public void drawString(AttributedCharacterIterator iterator, int x, int y) {
log(String.format("drawString(%s, %d, %d)", iterator, x, y));
myPeer.drawString(iterator, x, y);
}
@Override
public void drawString(AttributedCharacterIterator iterator, float x, float y) {
log(String.format("drawString(%s, %f, %f)", iterator, x, y));
myPeer.drawString(iterator, x, y);
}
@Override
public void drawGlyphVector(GlyphVector g, float x, float y) {
log(String.format("drawGlyphVector(%s, %f, %f)", g, x, y));
myPeer.drawGlyphVector(g, x, y);
}
@Override
public void fill(Shape s) {
log(String.format("fill(%s)", s));
myPeer.fill(s);
}
@Override
public boolean hit(Rectangle rect, Shape s, boolean onStroke) {
log(String.format("hit(%s, %s, %s)", rect, s, onStroke));
return myPeer.hit(rect, s, onStroke);
}
@Override
public GraphicsConfiguration getDeviceConfiguration() {
return myPeer.getDeviceConfiguration();
}
@Override
public void setComposite(Composite comp) {
log(String.format("setComposite(%s)", comp));
myPeer.setComposite(comp);
}
@Override
public void setPaint(Paint paint) {
log(String.format("setPaint(%s)", paint));
myPeer.setPaint(paint);
}
@Override
public void setStroke(Stroke s) {
log(String.format("setStroke(%s)", s));
myPeer.setStroke(s);
}
@Override
public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue) {
log(String.format("setRenderingHint(%s, %s)", hintKey, hintValue));
myPeer.setRenderingHint(hintKey, hintValue);
}
@Override
public Object getRenderingHint(RenderingHints.Key hintKey) {
log(String.format("getRenderingHints(%s)", hintKey));
return myPeer.getRenderingHint(hintKey);
}
@Override
public void setRenderingHints(Map<?, ?> hints) {
log(String.format("setRenderingHints(%s)", hints));
myPeer.setRenderingHints(hints);
}
@Override
public void addRenderingHints(Map<?, ?> hints) {
log(String.format("addRenderingHints(%s)", hints));
myPeer.addRenderingHints(hints);
}
@Override
public RenderingHints getRenderingHints() {
log(String.format("getRenderingHints()"));
return myPeer.getRenderingHints();
}
@Override
public void translate(int x, int y) {
log(String.format("translate(%d, %d)", x, y));
myPeer.translate(x, y);
}
@Override
public void translate(double tx, double ty) {
log(String.format("translate(%f, %f)", tx, ty));
myPeer.translate(tx, ty);
}
@Override
public void rotate(double theta) {
log(String.format("rotate(%f)", theta));
myPeer.rotate(theta);
}
@Override
public void rotate(double theta, double x, double y) {
log(String.format("rotate(%f, %f, %f)", theta, x, y));
myPeer.rotate(theta, x, y);
}
@Override
public void scale(double sx, double sy) {
log(String.format("scale(%f, %f)", sx, sy));
myPeer.scale(sx, sy);
}
@Override
public void shear(double shx, double shy) {
log(String.format("shear(%f, %f)", shx, shy));
myPeer.shear(shx, shy);
}
@Override
public void transform(AffineTransform Tx) {
log(String.format("transform(%s)", Tx));
myPeer.transform(Tx);
}
@Override
public void setTransform(AffineTransform Tx) {
log(String.format("setTransform(%s)", Tx));
myPeer.setTransform(Tx);
}
@Override
public AffineTransform getTransform() {
return myPeer.getTransform();
}
@Override
public Paint getPaint() {
return myPeer.getPaint();
}
@Override
public Composite getComposite() {
return myPeer.getComposite();
}
@Override
public void setBackground(Color color) {
log(String.format("setBackground(%s)", toHex(color)));
myPeer.setBackground(color);
}
@Override
public Color getBackground() {
return myPeer.getBackground();
}
@Override
public Stroke getStroke() {
return myPeer.getStroke();
}
@Override
public void clip(Shape s) {
log(String.format("clip(%s)", s));
myPeer.clip(s);
}
@Override
public FontRenderContext getFontRenderContext() {
return myPeer.getFontRenderContext();
}
@Override
public Graphics create() {
return new Graphics2DLog(myPeer.create());
}
@Override
public Graphics create(int x, int y, int width, int height) {
log(String.format("create(%d, %d %d, %d)", x, y, width, height));
return new Graphics2DLog(myPeer.create(x, y, width, height));
}
@Override
public Color getColor() {
return myPeer.getColor();
}
@Override
public void setColor(Color c) {
log(String.format("setColor(%s) alpha=%d", toHex(c), c == null ? 0 : c.getAlpha()));
myPeer.setColor(c);
}
@Override
public void setPaintMode() {
log(String.format("setPaintMode()"));
myPeer.setPaintMode();
}
@Override
public void setXORMode(Color c1) {
log(String.format("setXORMode(%s)", toHex(c1)));
myPeer.setXORMode(c1);
}
@Override
public Font getFont() {
return myPeer.getFont();
}
@Override
public void setFont(Font font) {
log(String.format("setFont(%s)", font));
myPeer.setFont(font);
}
@Override
public FontMetrics getFontMetrics() {
return myPeer.getFontMetrics();
}
@Override
public FontMetrics getFontMetrics(Font f) {
return myPeer.getFontMetrics(f);
}
@Override
public Rectangle getClipBounds() {
return myPeer.getClipBounds();
}
@Override
public void clipRect(int x, int y, int width, int height) {
log(String.format("clipRect(%d, %d, %d, %d)", x, y, width, height));
myPeer.clipRect(x, y, width, height);
}
@Override
public void setClip(int x, int y, int width, int height) {
log(String.format("setClip(%d, %d, %d, %d)", x, y, width, height));
myPeer.setClip(x, y, width, height);
}
@Override
public Shape getClip() {
log("getClip()");
return myPeer.getClip();
}
@Override
public void setClip(Shape clip) {
log(String.format("setClip(%s)", clip));
myPeer.setClip(clip);
}
@Override
public void copyArea(int x, int y, int width, int height, int dx, int dy) {
log(String.format("copyArea(%d, %d, %d, %d, %d, %d)", x, y, width, height, dx, dy));
myPeer.copyArea(x, y, width, height, dx, dy);
}
@Override
public void drawLine(int x1, int y1, int x2, int y2) {
log(String.format("drawLine(%d, %d, %d, %d)", x1, y1, x2, y2));
myPeer.drawLine(x1, y1, x2, y2);
}
@Override
public void fillRect(int x, int y, int width, int height) {
log(String.format("fillRect(%d, %d, %d, %d)", x, y, width, height));
myPeer.fillRect(x, y, width, height);
}
@Override
public void drawRect(int x, int y, int width, int height) {
log(String.format("drawRect(%d, %d, %d, %d)", x, y, width, height));
myPeer.drawRect(x, y, width, height);
}
@Override
public void clearRect(int x, int y, int width, int height) {
log(String.format("clearRect(%d, %d, %d, %d)", x, y, width, height));
myPeer.clearRect(x, y, width, height);
}
@Override
public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) {
log(String.format("drawRoundRect(%d, %d, %d, %d, %d, %d)", x, y, width, height, arcWidth, arcHeight));
myPeer.drawRoundRect(x, y, width, height, arcWidth, arcHeight);
}
@Override
public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) {
log(String.format("fillRoundRect(%d, %d, %d, %d, %d, %d)", x, y, width, height, arcWidth, arcHeight));
myPeer.fillRoundRect(x, y, width, height, arcWidth, arcHeight);
}
@Override
public void drawOval(int x, int y, int width, int height) {
log(String.format("drawOval(%d, %d, %d, %d)", x, y, width, height));
myPeer.drawOval(x, y, width, height);
}
@Override
public void fillOval(int x, int y, int width, int height) {
log(String.format("fillOval(%d, %d, %d, %d)", x, y, width, height));
myPeer.fillOval(x, y, width, height);
}
@Override
public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
myPeer.drawArc(x, y, width, height, startAngle, arcAngle);
}
@Override
public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
myPeer.fillArc(x, y, width, height, startAngle, arcAngle);
}
@Override
public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) {
log("drawPolyline(int[], int[], int)");
myPeer.drawPolyline(xPoints, yPoints, nPoints);
}
@Override
public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) {
log("drawPolygon(int[], int[], int)");
myPeer.drawPolygon(xPoints, yPoints, nPoints);
}
@Override
public void drawPolygon(Polygon p) {
log("drawPolygon()");
myPeer.drawPolygon(p);
}
@Override
public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) {
log("fillPolygon(int[], int[], int)");
myPeer.fillPolygon(xPoints, yPoints, nPoints);
}
@Override
public void fillPolygon(Polygon p) {
log("fillPolygon(" + p + ")");
myPeer.fillPolygon(p);
}
@Override
public void drawChars(char[] data, int offset, int length, int x, int y) {
log("drawChars()");
myPeer.drawChars(data, offset, length, x, y);
}
@Override
public void drawBytes(byte[] data, int offset, int length, int x, int y) {
log("drawBytes");
myPeer.drawBytes(data, offset, length, x, y);
}
@Override
public boolean drawImage(Image img, int x, int y, ImageObserver observer) {
log(String.format("drawImage(Image, %d, %d, ImageObserver)", x, y));
return myPeer.drawImage(img, x, y, observer);
}
@Override
public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) {
log("drawImage(Image,int,int,int,int,ImageObserver)");
return myPeer.drawImage(img, x, y, width, height, observer);
}
@Override
public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) {
log("drawImage(Image,int,int,Color,ImageObserver)");
return myPeer.drawImage(img, x, y, bgcolor, observer);
}
@Override
public boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) {
log("drawImage(Image,int,int,int,int,Color,ImageObserver)");
return myPeer.drawImage(img, x, y, width, height, bgcolor, observer);
}
@Override
public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) {
log("drawImage(Image,int,int,int,int,int,int,int,int,ImageObserver)");
return myPeer.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, observer);
}
@Override
public boolean drawImage(Image img,
int dx1,
int dy1,
int dx2,
int dy2,
int sx1,
int sy1,
int sx2,
int sy2,
Color bgcolor,
ImageObserver observer) {
log("drawImage(Image,int,int,int,int,int,int,int,int,Color,ImageObserver)");
return myPeer.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgcolor, observer);
}
@Override
public void dispose() {
log(String.format("dispose()"));
myPeer.dispose();
}
@Override
public void finalize() {
myPeer.finalize();
}
@Override
public String toString() {
return myPeer.toString();
}
@Override
@Deprecated
public Rectangle getClipRect() {
return myPeer.getClipRect();
}
@Override
public boolean hitClip(int x, int y, int width, int height) {
log(String.format("hitClip(%d, %d, %d, %d)", x, y, width, height));
return myPeer.hitClip(x, y, width, height);
}
@Override
public Rectangle getClipBounds(Rectangle r) {
return myPeer.getClipBounds(r);
}
@Nullable
private static String toHex(Color c) {
return c == null ? null : ColorUtil.toHex(c);
}
}
| platform/util/src/com/intellij/ui/Graphics2DLog.java | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ImageObserver;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.RenderableImage;
import java.text.AttributedCharacterIterator;
import java.util.Map;
/**
* Wrap a graphics2d objects to debug internals paintings
*
* @author Konstantin Bulenkov
*/
@SuppressWarnings("UnusedDeclaration")
public class Graphics2DLog extends Graphics2D {
protected final Graphics2D myPeer;
public Graphics2DLog(Graphics g) {
myPeer = (Graphics2D)g;
}
@SuppressWarnings({"MethodMayBeStatic", "UseOfSystemOutOrSystemErr"})
protected void log(String msg) {
System.out.println(msg);
}
@Override
public void draw3DRect(int x, int y, int width, int height, boolean raised) {
log(String.format("draw3DRect(%d, %d, %d, %d, %b)", x, y, width, height, raised));
myPeer.draw3DRect(x, y, width, height, raised);
}
@Override
public void fill3DRect(int x, int y, int width, int height, boolean raised) {
log(String.format("draw3DRect(%d, %d, %d, %d, %b)", x, y, width, height, raised));
myPeer.fill3DRect(x, y, width, height, raised);
}
@Override
public void draw(Shape s) {
log("draw(" + s + ")");
myPeer.draw(s);
}
@Override
public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) {
log("drawImage(Image, AffineTransform, ImageObserver)");
return myPeer.drawImage(img, xform, obs);
}
@Override
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
log(String.format("drawImage(BufferedImage, BufferedImageOp, %d, %d)", x, y));
myPeer.drawImage(img, op, x, y);
}
@Override
public void drawRenderedImage(RenderedImage img, AffineTransform xform) {
log("drawRenderedImage(RenderedImage, AffineTransform)");
myPeer.drawRenderedImage(img, xform);
}
@Override
public void drawRenderableImage(RenderableImage img, AffineTransform xform) {
log("drawRenderableImage(RenderableImage, AffineTransform)");
myPeer.drawRenderableImage(img, xform);
}
@Override
public void drawString(String str, int x, int y) {
log(String.format("drawString(%s, %d, %d)", str, x, y));
myPeer.drawString(str, x, y);
}
@Override
public void drawString(String str, float x, float y) {
log(String.format("drawString(%s, %f, %f)", str, x, y));
myPeer.drawString(str, x, y);
}
@Override
public void drawString(AttributedCharacterIterator iterator, int x, int y) {
log(String.format("drawString(%s, %d, %d)", iterator, x, y));
myPeer.drawString(iterator, x, y);
}
@Override
public void drawString(AttributedCharacterIterator iterator, float x, float y) {
log(String.format("drawString(%s, %f, %f)", iterator, x, y));
myPeer.drawString(iterator, x, y);
}
@Override
public void drawGlyphVector(GlyphVector g, float x, float y) {
log(String.format("drawGlyphVector(%s, %f, %f)", g, x, y));
myPeer.drawGlyphVector(g, x, y);
}
@Override
public void fill(Shape s) {
log(String.format("fill(%s)", s));
myPeer.fill(s);
}
@Override
public boolean hit(Rectangle rect, Shape s, boolean onStroke) {
log(String.format("hit(%s, %s, %s)", rect, s, onStroke));
return myPeer.hit(rect, s, onStroke);
}
@Override
public GraphicsConfiguration getDeviceConfiguration() {
return myPeer.getDeviceConfiguration();
}
@Override
public void setComposite(Composite comp) {
log(String.format("setComposite(%s)", comp));
myPeer.setComposite(comp);
}
@Override
public void setPaint(Paint paint) {
log(String.format("setPaint(%s)", paint));
myPeer.setPaint(paint);
}
@Override
public void setStroke(Stroke s) {
log(String.format("setStroke(%s)", s));
myPeer.setStroke(s);
}
@Override
public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue) {
log(String.format("setRenderingHint(%s, %s)", hintKey, hintValue));
myPeer.setRenderingHint(hintKey, hintValue);
}
@Override
public Object getRenderingHint(RenderingHints.Key hintKey) {
log(String.format("getRenderingHints(%s)", hintKey));
return myPeer.getRenderingHint(hintKey);
}
@Override
public void setRenderingHints(Map<?, ?> hints) {
log(String.format("setRenderingHints(%s)", hints));
myPeer.setRenderingHints(hints);
}
@Override
public void addRenderingHints(Map<?, ?> hints) {
log(String.format("addRenderingHints(%s)", hints));
myPeer.addRenderingHints(hints);
}
@Override
public RenderingHints getRenderingHints() {
log(String.format("getRenderingHints()"));
return myPeer.getRenderingHints();
}
@Override
public void translate(int x, int y) {
log(String.format("translate(%d, %d)", x, y));
myPeer.translate(x, y);
}
@Override
public void translate(double tx, double ty) {
log(String.format("translate(%f, %f)", tx, ty));
myPeer.translate(tx, ty);
}
@Override
public void rotate(double theta) {
log(String.format("rotate(%f)", theta));
myPeer.rotate(theta);
}
@Override
public void rotate(double theta, double x, double y) {
log(String.format("rotate(%f, %f, %f)", theta, x, y));
myPeer.rotate(theta, x, y);
}
@Override
public void scale(double sx, double sy) {
log(String.format("scale(%f, %f)", sx, sy));
myPeer.scale(sx, sy);
}
@Override
public void shear(double shx, double shy) {
log(String.format("shear(%f, %f)", shx, shy));
myPeer.shear(shx, shy);
}
@Override
public void transform(AffineTransform Tx) {
log(String.format("transform(%s)", Tx));
myPeer.transform(Tx);
}
@Override
public void setTransform(AffineTransform Tx) {
log(String.format("setTransform(%s)", Tx));
myPeer.setTransform(Tx);
}
@Override
public AffineTransform getTransform() {
return myPeer.getTransform();
}
@Override
public Paint getPaint() {
return myPeer.getPaint();
}
@Override
public Composite getComposite() {
return myPeer.getComposite();
}
@Override
public void setBackground(Color color) {
log(String.format("setBackground(%s)", toHex(color)));
myPeer.setBackground(color);
}
@Override
public Color getBackground() {
return myPeer.getBackground();
}
@Override
public Stroke getStroke() {
return myPeer.getStroke();
}
@Override
public void clip(Shape s) {
log(String.format("clip(%s)", s));
myPeer.clip(s);
}
@Override
public FontRenderContext getFontRenderContext() {
return myPeer.getFontRenderContext();
}
@Override
public Graphics create() {
return new Graphics2DLog(myPeer.create());
}
@Override
public Graphics create(int x, int y, int width, int height) {
log(String.format("create(%d, %d %d, %d)", x, y, width, height));
return new Graphics2DLog(myPeer.create(x, y, width, height));
}
@Override
public Color getColor() {
return myPeer.getColor();
}
@Override
public void setColor(Color c) {
log(String.format("setColor(%s) alpha=%d", toHex(c), c.getAlpha()));
myPeer.setColor(c);
}
@Override
public void setPaintMode() {
log(String.format("setPaintMode()"));
myPeer.setPaintMode();
}
@Override
public void setXORMode(Color c1) {
log(String.format("setXORMode(%s)", toHex(c1)));
myPeer.setXORMode(c1);
}
@Override
public Font getFont() {
return myPeer.getFont();
}
@Override
public void setFont(Font font) {
log(String.format("setFont(%s)", font));
myPeer.setFont(font);
}
@Override
public FontMetrics getFontMetrics() {
return myPeer.getFontMetrics();
}
@Override
public FontMetrics getFontMetrics(Font f) {
return myPeer.getFontMetrics(f);
}
@Override
public Rectangle getClipBounds() {
return myPeer.getClipBounds();
}
@Override
public void clipRect(int x, int y, int width, int height) {
log(String.format("clipRect(%d, %d, %d, %d)", x, y, width, height));
myPeer.clipRect(x, y, width, height);
}
@Override
public void setClip(int x, int y, int width, int height) {
log(String.format("setClip(%d, %d, %d, %d)", x, y, width, height));
myPeer.setClip(x, y, width, height);
}
@Override
public Shape getClip() {
log("getClip()");
return myPeer.getClip();
}
@Override
public void setClip(Shape clip) {
log(String.format("setClip(%s)", clip));
myPeer.setClip(clip);
}
@Override
public void copyArea(int x, int y, int width, int height, int dx, int dy) {
log(String.format("copyArea(%d, %d, %d, %d, %d, %d)", x, y, width, height, dx, dy));
myPeer.copyArea(x, y, width, height, dx, dy);
}
@Override
public void drawLine(int x1, int y1, int x2, int y2) {
log(String.format("drawLine(%d, %d, %d, %d)", x1, y1, x2, y2));
myPeer.drawLine(x1, y1, x2, y2);
}
@Override
public void fillRect(int x, int y, int width, int height) {
log(String.format("fillRect(%d, %d, %d, %d)", x, y, width, height));
myPeer.fillRect(x, y, width, height);
}
@Override
public void drawRect(int x, int y, int width, int height) {
log(String.format("drawRect(%d, %d, %d, %d)", x, y, width, height));
myPeer.drawRect(x, y, width, height);
}
@Override
public void clearRect(int x, int y, int width, int height) {
log(String.format("clearRect(%d, %d, %d, %d)", x, y, width, height));
myPeer.clearRect(x, y, width, height);
}
@Override
public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) {
log(String.format("drawRoundRect(%d, %d, %d, %d, %d, %d)", x, y, width, height, arcWidth, arcHeight));
myPeer.drawRoundRect(x, y, width, height, arcWidth, arcHeight);
}
@Override
public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) {
log(String.format("fillRoundRect(%d, %d, %d, %d, %d, %d)", x, y, width, height, arcWidth, arcHeight));
myPeer.fillRoundRect(x, y, width, height, arcWidth, arcHeight);
}
@Override
public void drawOval(int x, int y, int width, int height) {
log(String.format("drawOval(%d, %d, %d, %d)", x, y, width, height));
myPeer.drawOval(x, y, width, height);
}
@Override
public void fillOval(int x, int y, int width, int height) {
log(String.format("fillOval(%d, %d, %d, %d)", x, y, width, height));
myPeer.fillOval(x, y, width, height);
}
@Override
public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
myPeer.drawArc(x, y, width, height, startAngle, arcAngle);
}
@Override
public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
myPeer.fillArc(x, y, width, height, startAngle, arcAngle);
}
@Override
public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) {
log("drawPolyline(int[], int[], int)");
myPeer.drawPolyline(xPoints, yPoints, nPoints);
}
@Override
public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) {
log("drawPolygon(int[], int[], int)");
myPeer.drawPolygon(xPoints, yPoints, nPoints);
}
@Override
public void drawPolygon(Polygon p) {
log("drawPolygon()");
myPeer.drawPolygon(p);
}
@Override
public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) {
log("fillPolygon(int[], int[], int)");
myPeer.fillPolygon(xPoints, yPoints, nPoints);
}
@Override
public void fillPolygon(Polygon p) {
log("fillPolygon(" + p + ")");
myPeer.fillPolygon(p);
}
@Override
public void drawChars(char[] data, int offset, int length, int x, int y) {
log("drawChars()");
myPeer.drawChars(data, offset, length, x, y);
}
@Override
public void drawBytes(byte[] data, int offset, int length, int x, int y) {
log("drawBytes");
myPeer.drawBytes(data, offset, length, x, y);
}
@Override
public boolean drawImage(Image img, int x, int y, ImageObserver observer) {
log(String.format("drawImage(Image, %d, %d, ImageObserver)", x, y));
return myPeer.drawImage(img, x, y, observer);
}
@Override
public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) {
log("drawImage(Image,int,int,int,int,ImageObserver)");
return myPeer.drawImage(img, x, y, width, height, observer);
}
@Override
public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) {
log("drawImage(Image,int,int,Color,ImageObserver)");
return myPeer.drawImage(img, x, y, bgcolor, observer);
}
@Override
public boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) {
log("drawImage(Image,int,int,int,int,Color,ImageObserver)");
return myPeer.drawImage(img, x, y, width, height, bgcolor, observer);
}
@Override
public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) {
log("drawImage(Image,int,int,int,int,int,int,int,int,ImageObserver)");
return myPeer.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, observer);
}
@Override
public boolean drawImage(Image img,
int dx1,
int dy1,
int dx2,
int dy2,
int sx1,
int sy1,
int sx2,
int sy2,
Color bgcolor,
ImageObserver observer) {
log("drawImage(Image,int,int,int,int,int,int,int,int,Color,ImageObserver)");
return myPeer.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgcolor, observer);
}
@Override
public void dispose() {
log(String.format("dispose()"));
myPeer.dispose();
}
@Override
public void finalize() {
myPeer.finalize();
}
@Override
public String toString() {
return myPeer.toString();
}
@Override
@Deprecated
public Rectangle getClipRect() {
return myPeer.getClipRect();
}
@Override
public boolean hitClip(int x, int y, int width, int height) {
log(String.format("hitClip(%d, %d, %d, %d)", x, y, width, height));
return myPeer.hitClip(x, y, width, height);
}
@Override
public Rectangle getClipBounds(Rectangle r) {
return myPeer.getClipBounds(r);
}
@Nullable
private static String toHex(Color c) {
return c == null ? null : ColorUtil.toHex(c);
}
}
| NPE fix
(cherry picked from commit 97cf4bc8c8e842804fc68260ef68214227c2c6bc)
| platform/util/src/com/intellij/ui/Graphics2DLog.java | NPE fix (cherry picked from commit 97cf4bc8c8e842804fc68260ef68214227c2c6bc) | <ide><path>latform/util/src/com/intellij/ui/Graphics2DLog.java
<ide>
<ide> @Override
<ide> public void setColor(Color c) {
<del> log(String.format("setColor(%s) alpha=%d", toHex(c), c.getAlpha()));
<add> log(String.format("setColor(%s) alpha=%d", toHex(c), c == null ? 0 : c.getAlpha()));
<ide> myPeer.setColor(c);
<ide> }
<ide> |
|
Java | apache-2.0 | aa3ce8e32ca393f9f76c68c0c6b0407969371748 | 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-2018 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.roots.impl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.fileTypes.impl.FileTypeAssocTable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.UnloadedModuleDescription;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.libraries.LibraryEx;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Conditions;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
import com.intellij.util.CollectionQuery;
import com.intellij.util.Function;
import com.intellij.util.Query;
import com.intellij.util.SmartList;
import com.intellij.util.containers.Stack;
import com.intellij.util.containers.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.fileTypes.FileNameMatcherFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.*;
class RootIndex {
static final Comparator<OrderEntry> BY_OWNER_MODULE = (o1, o2) -> {
String name1 = o1.getOwnerModule().getName();
String name2 = o2.getOwnerModule().getName();
return name1.compareTo(name2);
};
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.roots.impl.RootIndex");
private static final FileTypeRegistry ourFileTypes = FileTypeRegistry.getInstance();
private final Map<VirtualFile, String> myPackagePrefixByRoot = ContainerUtil.newHashMap();
private final Map<VirtualFile, DirectoryInfo> myRootInfos = ContainerUtil.newHashMap();
private final ConcurrentBitSet myNonInterestingIds = new ConcurrentBitSet();
@NotNull private final Project myProject;
final PackageDirectoryCache myPackageDirectoryCache;
private OrderEntryGraph myOrderEntryGraph;
RootIndex(@NotNull Project project) {
myProject = project;
ApplicationManager.getApplication().assertReadAccessAllowed();
final RootInfo info = buildRootInfo(project);
MultiMap<String, VirtualFile> rootsByPackagePrefix = MultiMap.create();
Set<VirtualFile> allRoots = info.getAllRoots();
for (VirtualFile root : allRoots) {
List<VirtualFile> hierarchy = getHierarchy(root, allRoots, info);
Pair<DirectoryInfo, String> pair = hierarchy != null
? calcDirectoryInfoAndPackagePrefix(root, hierarchy, info)
: new Pair<>(NonProjectDirectoryInfo.IGNORED, null);
myRootInfos.put(root, pair.first);
rootsByPackagePrefix.putValue(pair.second, root);
myPackagePrefixByRoot.put(root, pair.second);
}
myPackageDirectoryCache = new PackageDirectoryCache(rootsByPackagePrefix) {
@Override
protected boolean isPackageDirectory(@NotNull VirtualFile dir, @NotNull String packageName) {
return getInfoForFile(dir).isInProject(dir) && packageName.equals(getPackageName(dir));
}
};
}
void onLowMemory() {
myPackageDirectoryCache.onLowMemory();
}
@NotNull
private RootInfo buildRootInfo(@NotNull Project project) {
final RootInfo info = new RootInfo();
ModuleManager moduleManager = ModuleManager.getInstance(project);
for (final Module module : moduleManager.getModules()) {
final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
for (final VirtualFile contentRoot : moduleRootManager.getContentRoots()) {
if (!info.contentRootOf.containsKey(contentRoot) && ensureValid(contentRoot, module)) {
info.contentRootOf.put(contentRoot, module);
}
}
for (ContentEntry contentEntry : moduleRootManager.getContentEntries()) {
if (!(contentEntry instanceof ContentEntryImpl) || !((ContentEntryImpl)contentEntry).isDisposed()) {
for (VirtualFile excludeRoot : contentEntry.getExcludeFolderFiles()) {
if (!ensureValid(excludeRoot, contentEntry)) continue;
info.excludedFromModule.put(excludeRoot, module);
}
List<String> patterns = contentEntry.getExcludePatterns();
if (!patterns.isEmpty()) {
FileTypeAssocTable<Boolean> table = new FileTypeAssocTable<>();
for (String pattern : patterns) {
table.addAssociation(FileNameMatcherFactory.getInstance().createMatcher(pattern), Boolean.TRUE);
}
info.excludeFromContentRootTables.put(contentEntry.getFile(), table);
}
}
// Init module sources
for (final SourceFolder sourceFolder : contentEntry.getSourceFolders()) {
final VirtualFile sourceFolderRoot = sourceFolder.getFile();
if (sourceFolderRoot != null && ensureValid(sourceFolderRoot, sourceFolder)) {
info.sourceFolders.put(sourceFolderRoot, sourceFolder);
info.classAndSourceRoots.add(sourceFolderRoot);
info.sourceRootOf.putValue(sourceFolderRoot, module);
info.packagePrefix.put(sourceFolderRoot, sourceFolder.getPackagePrefix());
}
}
}
for (OrderEntry orderEntry : moduleRootManager.getOrderEntries()) {
if (orderEntry instanceof LibraryOrSdkOrderEntry) {
final LibraryOrSdkOrderEntry entry = (LibraryOrSdkOrderEntry)orderEntry;
final VirtualFile[] sourceRoots = entry.getRootFiles(OrderRootType.SOURCES);
final VirtualFile[] classRoots = entry.getRootFiles(OrderRootType.CLASSES);
// Init library sources
for (final VirtualFile sourceRoot : sourceRoots) {
if (!ensureValid(sourceRoot, entry)) continue;
info.classAndSourceRoots.add(sourceRoot);
info.libraryOrSdkSources.add(sourceRoot);
info.packagePrefix.put(sourceRoot, "");
}
// init library classes
for (final VirtualFile classRoot : classRoots) {
if (!ensureValid(classRoot, entry)) continue;
info.classAndSourceRoots.add(classRoot);
info.libraryOrSdkClasses.add(classRoot);
info.packagePrefix.put(classRoot, "");
}
if (orderEntry instanceof LibraryOrderEntry) {
Library library = ((LibraryOrderEntry)orderEntry).getLibrary();
if (library != null) {
for (VirtualFile root : ((LibraryEx)library).getExcludedRoots()) {
if (!ensureValid(root, library)) continue;
info.excludedFromLibraries.putValue(root, library);
}
for (VirtualFile root : sourceRoots) {
if (!ensureValid(root, library)) continue;
info.sourceOfLibraries.putValue(root, library);
}
for (VirtualFile root : classRoots) {
if (!ensureValid(root, library)) continue;
info.classOfLibraries.putValue(root, library);
}
}
}
}
}
}
for (AdditionalLibraryRootsProvider provider : AdditionalLibraryRootsProvider.EP_NAME.getExtensionList()) {
Collection<SyntheticLibrary> libraries = provider.getAdditionalProjectLibraries(project);
for (SyntheticLibrary descriptor : libraries) {
for (VirtualFile sourceRoot : descriptor.getSourceRoots()) {
if (!ensureValid(sourceRoot, descriptor)) continue;
info.libraryOrSdkSources.add(sourceRoot);
info.classAndSourceRoots.add(sourceRoot);
if (descriptor instanceof JavaSyntheticLibrary) {
info.packagePrefix.put(sourceRoot, "");
}
info.sourceOfLibraries.putValue(sourceRoot, descriptor);
}
for (VirtualFile classRoot : descriptor.getBinaryRoots()) {
if (!ensureValid(classRoot, project)) continue;
info.libraryOrSdkClasses.add(classRoot);
info.classAndSourceRoots.add(classRoot);
if (descriptor instanceof JavaSyntheticLibrary) {
info.packagePrefix.put(classRoot, "");
}
info.classOfLibraries.putValue(classRoot, descriptor);
}
for (VirtualFile file : descriptor.getExcludedRoots()) {
if (!ensureValid(file, project)) continue;
info.excludedFromLibraries.putValue(file, descriptor);
}
}
}
for (DirectoryIndexExcludePolicy policy : DirectoryIndexExcludePolicy.EP_NAME.getExtensions(project)) {
List<VirtualFile> files = ContainerUtil.mapNotNull(policy.getExcludeUrlsForProject(), url -> VirtualFileManager.getInstance().findFileByUrl(url));
info.excludedFromProject.addAll(ContainerUtil.filter(files, file -> ensureValid(file, policy)));
Function<Sdk, List<VirtualFile>> fun = policy.getExcludeSdkRootsStrategy();
if (fun != null) {
Set<Sdk> sdks = new HashSet<>();
for (Module m : ModuleManager.getInstance(myProject).getModules()) {
Sdk sdk = ModuleRootManager.getInstance(m).getSdk();
if (sdk != null) {
sdks.add(sdk);
}
}
Set<VirtualFile> roots = new HashSet<>();
for (Sdk sdk: sdks) {
roots.addAll(Arrays.asList(sdk.getRootProvider().getFiles(OrderRootType.CLASSES)));
}
for (Sdk sdk: sdks) {
info.excludedFromSdkRoots
.addAll(ContainerUtil.filter(fun.fun(sdk), file -> ensureValid(file, policy) && !roots.contains(file)));
}
}
}
for (UnloadedModuleDescription description : moduleManager.getUnloadedModuleDescriptions()) {
for (VirtualFilePointer pointer : description.getContentRoots()) {
VirtualFile contentRoot = pointer.getFile();
if (contentRoot != null && ensureValid(contentRoot, description)) {
info.contentRootOfUnloaded.put(contentRoot, description.getName());
}
}
}
return info;
}
private static boolean ensureValid(@NotNull VirtualFile file, @NotNull Object container) {
if (!(file instanceof VirtualFileWithId)) {
//skip roots from unsupported file systems (e.g. http)
return false;
}
if (!file.isValid()) {
LOG.error("Invalid root " + file + " in " + container);
return false;
}
return true;
}
@NotNull
private synchronized OrderEntryGraph getOrderEntryGraph() {
if (myOrderEntryGraph == null) {
RootInfo rootInfo = buildRootInfo(myProject);
myOrderEntryGraph = new OrderEntryGraph(myProject, rootInfo);
}
return myOrderEntryGraph;
}
/**
* A reverse dependency graph of (library, jdk, module, module source) -> (module).
* <p>
* <p>Each edge carries with it the associated OrderEntry that caused the dependency.
*/
private static class OrderEntryGraph {
private static class Edge {
private final Module myKey;
private final ModuleOrderEntry myOrderEntry; // Order entry from myKey -> the node containing the edge
private final boolean myRecursive; // Whether this edge should be descended into during graph walk
Edge(@NotNull Module key, @NotNull ModuleOrderEntry orderEntry, boolean recursive) {
myKey = key;
myOrderEntry = orderEntry;
myRecursive = recursive;
}
@Override
public String toString() {
return myOrderEntry.toString();
}
}
private static class Node {
private final Module myKey;
private final List<Edge> myEdges = new ArrayList<>();
private Set<String> myUnloadedDependentModules;
private Node(@NotNull Module key) {
myKey = key;
}
@Override
public String toString() {
return myKey.toString();
}
}
private static class Graph {
private final Map<Module, Node> myNodes = new HashMap<>();
}
private final Project myProject;
private final RootInfo myRootInfo;
private final Set<VirtualFile> myAllRoots;
private final Graph myGraph;
private final MultiMap<VirtualFile, Node> myRoots; // Map of roots to their root nodes, eg. library jar -> library node
private final SynchronizedSLRUCache<VirtualFile, List<OrderEntry>> myCache;
private final SynchronizedSLRUCache<Module, Set<String>> myDependentUnloadedModulesCache;
private final MultiMap<VirtualFile, OrderEntry> myLibClassRootEntries;
private final MultiMap<VirtualFile, OrderEntry> myLibSourceRootEntries;
OrderEntryGraph(@NotNull Project project, @NotNull RootInfo rootInfo) {
myProject = project;
myRootInfo = rootInfo;
myAllRoots = myRootInfo.getAllRoots();
int cacheSize = Math.max(25, myAllRoots.size() / 100 * 2);
myCache = new SynchronizedSLRUCache<VirtualFile, List<OrderEntry>>(cacheSize, cacheSize) {
@NotNull
@Override
public List<OrderEntry> createValue(@NotNull VirtualFile key) {
return collectOrderEntries(key);
}
};
int dependentUnloadedModulesCacheSize = ModuleManager.getInstance(project).getModules().length / 2;
myDependentUnloadedModulesCache =
new SynchronizedSLRUCache<Module, Set<String>>(dependentUnloadedModulesCacheSize, dependentUnloadedModulesCacheSize) {
@NotNull
@Override
public Set<String> createValue(@NotNull Module key) {
return collectDependentUnloadedModules(key);
}
};
Pair<Graph, MultiMap<VirtualFile, Node>> pair = initGraphRoots();
myGraph = pair.getFirst();
myRoots = pair.getSecond();
Pair<MultiMap<VirtualFile, OrderEntry>, MultiMap<VirtualFile, OrderEntry>> lpair = initLibraryClassSourceRoots();
myLibClassRootEntries = lpair.getFirst();
myLibSourceRootEntries = lpair.getSecond();
}
@NotNull
private Pair<Graph, MultiMap<VirtualFile, Node>> initGraphRoots() {
Graph graph = new Graph();
MultiMap<VirtualFile, Node> roots = MultiMap.createSmart();
ModuleManager moduleManager = ModuleManager.getInstance(myProject);
for (final Module module : moduleManager.getModules()) {
final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
List<OrderEnumerationHandler> handlers = OrderEnumeratorBase.getCustomHandlers(module);
for (OrderEntry orderEntry : moduleRootManager.getOrderEntries()) {
if (orderEntry instanceof ModuleOrderEntry) {
ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)orderEntry;
final Module depModule = moduleOrderEntry.getModule();
if (depModule != null) {
Node node = graph.myNodes.get(depModule);
OrderEnumerator en = OrderEnumerator.orderEntries(depModule).exportedOnly();
if (node == null) {
node = new Node(depModule);
graph.myNodes.put(depModule, node);
VirtualFile[] importedClassRoots = en.classes().usingCache().getRoots();
for (VirtualFile importedClassRoot : importedClassRoots) {
roots.putValue(importedClassRoot, node);
}
VirtualFile[] importedSourceRoots = en.sources().usingCache().getRoots();
for (VirtualFile sourceRoot : importedSourceRoots) {
roots.putValue(sourceRoot, node);
}
}
boolean shouldRecurse = en.recursively().shouldRecurse(moduleOrderEntry, handlers);
node.myEdges.add(new Edge(module, moduleOrderEntry, shouldRecurse));
}
}
}
}
for (UnloadedModuleDescription description : moduleManager.getUnloadedModuleDescriptions()) {
for (String depName : description.getDependencyModuleNames()) {
Module depModule = moduleManager.findModuleByName(depName);
if (depModule != null) {
Node node = graph.myNodes.get(depModule);
if (node == null) {
node = new Node(depModule);
graph.myNodes.put(depModule, node);
}
if (node.myUnloadedDependentModules == null) {
node.myUnloadedDependentModules = new LinkedHashSet<>();
}
node.myUnloadedDependentModules.add(description.getName());
}
}
}
return Pair.create(graph, roots);
}
@NotNull
private Pair<MultiMap<VirtualFile, OrderEntry>, MultiMap<VirtualFile, OrderEntry>> initLibraryClassSourceRoots() {
MultiMap<VirtualFile, OrderEntry> libClassRootEntries = MultiMap.createSmart();
MultiMap<VirtualFile, OrderEntry> libSourceRootEntries = MultiMap.createSmart();
for (final Module module : ModuleManager.getInstance(myProject).getModules()) {
final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
for (OrderEntry orderEntry : moduleRootManager.getOrderEntries()) {
if (orderEntry instanceof LibraryOrSdkOrderEntry) {
final LibraryOrSdkOrderEntry entry = (LibraryOrSdkOrderEntry)orderEntry;
for (final VirtualFile sourceRoot : entry.getRootFiles(OrderRootType.SOURCES)) {
libSourceRootEntries.putValue(sourceRoot, orderEntry);
}
for (final VirtualFile classRoot : entry.getRootFiles(OrderRootType.CLASSES)) {
libClassRootEntries.putValue(classRoot, orderEntry);
}
}
}
}
return Pair.create(libClassRootEntries, libSourceRootEntries);
}
@NotNull
private List<OrderEntry> getOrderEntries(@NotNull VirtualFile file) {
return myCache.get(file);
}
/**
* Traverses the graph from the given file, collecting all encountered order entries.
*/
@NotNull
private List<OrderEntry> collectOrderEntries(@NotNull VirtualFile file) {
List<VirtualFile> roots = getHierarchy(file, myAllRoots, myRootInfo);
if (roots == null) {
return Collections.emptyList();
}
Stack<Node> stack = new Stack<>();
for (VirtualFile root : roots) {
Collection<Node> nodes = myRoots.get(root);
for (Node node : nodes) {
stack.push(node);
}
}
Set<Node> seen = new HashSet<>();
List<OrderEntry> result = new ArrayList<>();
while (!stack.isEmpty()) {
Node node = stack.pop();
if (seen.contains(node)) {
continue;
}
seen.add(node);
for (Edge edge : node.myEdges) {
result.add(edge.myOrderEntry);
if (edge.myRecursive) {
Node targetNode = myGraph.myNodes.get(edge.myKey);
if (targetNode != null) {
stack.push(targetNode);
}
}
}
}
@Nullable Pair<VirtualFile, List<Condition<? super VirtualFile>>> libraryClassRootInfo = myRootInfo.findLibraryRootInfo(roots, false);
@Nullable Pair<VirtualFile, List<Condition<? super VirtualFile>>> librarySourceRootInfo = myRootInfo.findLibraryRootInfo(roots, true);
result.addAll(myRootInfo.getLibraryOrderEntries(roots,
Pair.getFirst(libraryClassRootInfo),
Pair.getFirst(librarySourceRootInfo),
myLibClassRootEntries, myLibSourceRootEntries));
VirtualFile moduleContentRoot = myRootInfo.findNearestContentRoot(roots);
if (moduleContentRoot != null) {
ContainerUtil.addIfNotNull(result, myRootInfo.getModuleSourceEntry(roots, moduleContentRoot, myLibClassRootEntries));
}
Collections.sort(result, BY_OWNER_MODULE);
return ContainerUtil.immutableList(result);
}
@NotNull
Set<String> getDependentUnloadedModules(@NotNull Module module) {
return myDependentUnloadedModulesCache.get(module);
}
/**
* @return names of unloaded modules which directly or transitively via exported dependencies depend on the specified module
*/
@NotNull
private Set<String> collectDependentUnloadedModules(@NotNull Module module) {
Node start = myGraph.myNodes.get(module);
if (start == null) return Collections.emptySet();
Deque<Node> stack = new ArrayDeque<>();
stack.push(start);
Set<Node> seen = new HashSet<>();
Set<String> result = null;
while (!stack.isEmpty()) {
Node node = stack.pop();
if (!seen.add(node)) {
continue;
}
if (node.myUnloadedDependentModules != null) {
if (result == null) {
result = new LinkedHashSet<>(node.myUnloadedDependentModules);
}
else {
result.addAll(node.myUnloadedDependentModules);
}
}
for (Edge edge : node.myEdges) {
if (edge.myRecursive) {
Node targetNode = myGraph.myNodes.get(edge.myKey);
if (targetNode != null) {
stack.push(targetNode);
}
}
}
}
return result != null ? result : Collections.emptySet();
}
}
@NotNull
DirectoryInfo getInfoForFile(@NotNull VirtualFile file) {
if (!file.isValid() || !(file instanceof VirtualFileWithId)) {
return NonProjectDirectoryInfo.INVALID;
}
for (VirtualFile each = file; each != null; each = each.getParent()) {
int id = ((VirtualFileWithId)each).getId();
if (!myNonInterestingIds.get(id)) {
DirectoryInfo info = myRootInfos.get(each);
if (info != null) {
return info;
}
if (ourFileTypes.isFileIgnored(each)) {
return NonProjectDirectoryInfo.IGNORED;
}
myNonInterestingIds.set(id);
}
}
return NonProjectDirectoryInfo.NOT_UNDER_PROJECT_ROOTS;
}
@NotNull
Query<VirtualFile> getDirectoriesByPackageName(@NotNull final String packageName, final boolean includeLibrarySources) {
// Note that this method is used in upsource as well, hence, don't reduce this method's visibility.
List<VirtualFile> result = myPackageDirectoryCache.getDirectoriesByPackageName(packageName);
if (!includeLibrarySources) {
result = ContainerUtil.filter(result, file -> {
DirectoryInfo info = getInfoForFile(file);
return info.isInProject(file) && (!info.isInLibrarySource(file) || info.isInModuleSource(file) || info.hasLibraryClassRoot());
});
}
return new CollectionQuery<>(result);
}
@Nullable
String getPackageName(@NotNull final VirtualFile dir) {
if (dir.isDirectory()) {
if (ourFileTypes.isFileIgnored(dir)) {
return null;
}
if (myPackagePrefixByRoot.containsKey(dir)) {
return myPackagePrefixByRoot.get(dir);
}
final VirtualFile parent = dir.getParent();
if (parent != null) {
return getPackageNameForSubdir(getPackageName(parent), dir.getName());
}
}
return null;
}
private static String getPackageNameForSubdir(@Nullable String parentPackageName, @NotNull String subdirName) {
if (parentPackageName == null) return null;
return parentPackageName.isEmpty() ? subdirName : parentPackageName + "." + subdirName;
}
@Nullable("returns null only if dir is under ignored folder")
private static List<VirtualFile> getHierarchy(@NotNull VirtualFile deepDir, @NotNull Set<? extends VirtualFile> allRoots, @NotNull RootInfo info) {
List<VirtualFile> hierarchy = ContainerUtil.newArrayList();
boolean hasContentRoots = false;
for (VirtualFile dir = deepDir; dir != null; dir = dir.getParent()) {
hasContentRoots |= info.contentRootOf.get(dir) != null;
if (!hasContentRoots && ourFileTypes.isFileIgnored(dir)) {
return null;
}
if (allRoots.contains(dir)) {
hierarchy.add(dir);
}
}
return hierarchy;
}
private static class RootInfo {
// getDirectoriesByPackageName used to be in this order, some clients might rely on that
@NotNull private final Set<VirtualFile> classAndSourceRoots = new LinkedHashSet<>();
@NotNull private final Set<VirtualFile> libraryOrSdkSources = new HashSet<>();
@NotNull private final Set<VirtualFile> libraryOrSdkClasses = new HashSet<>();
@NotNull private final Map<VirtualFile, Module> contentRootOf = new HashMap<>();
@NotNull private final Map<VirtualFile, String> contentRootOfUnloaded = new HashMap<>();
@NotNull private final MultiMap<VirtualFile, Module> sourceRootOf = MultiMap.createSet();
@NotNull private final Map<VirtualFile, SourceFolder> sourceFolders = new HashMap<>();
@NotNull private final MultiMap<VirtualFile, /*Library|SyntheticLibrary*/ Object> excludedFromLibraries = MultiMap.createSmart();
@NotNull private final MultiMap<VirtualFile, /*Library|SyntheticLibrary*/ Object> classOfLibraries = MultiMap.createSmart();
@NotNull private final MultiMap<VirtualFile, /*Library|SyntheticLibrary*/ Object> sourceOfLibraries = MultiMap.createSmart();
@NotNull private final Set<VirtualFile> excludedFromProject = new HashSet<>();
@NotNull private final Set<VirtualFile> excludedFromSdkRoots = new HashSet<>();
@NotNull private final Map<VirtualFile, Module> excludedFromModule = new HashMap<>();
@NotNull private final Map<VirtualFile, FileTypeAssocTable<Boolean>> excludeFromContentRootTables = new HashMap<>();
@NotNull private final Map<VirtualFile, String> packagePrefix = new HashMap<>();
@NotNull
Set<VirtualFile> getAllRoots() {
Set<VirtualFile> result = new LinkedHashSet<>();
result.addAll(classAndSourceRoots);
result.addAll(contentRootOf.keySet());
result.addAll(contentRootOfUnloaded.keySet());
result.addAll(excludedFromLibraries.keySet());
result.addAll(excludedFromModule.keySet());
result.addAll(excludedFromProject);
result.addAll(excludedFromSdkRoots);
return result;
}
/**
* Returns nearest content root for a file by its parent directories hierarchy. If the file is excluded (i.e. located under an excluded
* root and there are no source roots on the path to the excluded root) returns {@code null}.
*/
@Nullable
private VirtualFile findNearestContentRoot(@NotNull List<? extends VirtualFile> hierarchy) {
Collection<Module> sourceRootOwners = null;
boolean underExcludedSourceRoot = false;
for (VirtualFile root : hierarchy) {
Module module = contentRootOf.get(root);
Module excludedFrom = excludedFromModule.get(root);
if (module != null) {
FileTypeAssocTable<Boolean> table = excludeFromContentRootTables.get(root);
if (table != null && isExcludedByPattern(root, hierarchy, table)) {
excludedFrom = module;
}
}
if (module != null && (excludedFrom != module || underExcludedSourceRoot && sourceRootOwners.contains(module))) {
return root;
}
if (excludedFrom != null || excludedFromProject.contains(root) || contentRootOfUnloaded.containsKey(root)) {
if (sourceRootOwners == null) {
return null;
}
underExcludedSourceRoot = true;
}
if (!underExcludedSourceRoot && sourceRootOf.containsKey(root)) {
Collection<Module> modulesForSourceRoot = sourceRootOf.get(root);
if (!modulesForSourceRoot.isEmpty()) {
sourceRootOwners = sourceRootOwners == null ? modulesForSourceRoot : ContainerUtil.union(sourceRootOwners, modulesForSourceRoot);
}
}
}
return null;
}
private static boolean isExcludedByPattern(@NotNull VirtualFile contentRoot,
List<? extends VirtualFile> hierarchy,
@NotNull FileTypeAssocTable<Boolean> table) {
for (VirtualFile file : hierarchy) {
if (table.findAssociatedFileType(file.getNameSequence()) != null) {
return true;
}
if (file.equals(contentRoot)) {
break;
}
}
return false;
}
@Nullable
private VirtualFile findNearestContentRootForExcluded(@NotNull List<? extends VirtualFile> hierarchy) {
for (VirtualFile root : hierarchy) {
if (contentRootOf.containsKey(root) || contentRootOfUnloaded.containsKey(root)) {
return root;
}
}
return null;
}
/**
* @return root and set of libraries that provided it
*/
@Nullable
private Pair<VirtualFile, List<Condition<? super VirtualFile>>> findLibraryRootInfo(@NotNull List<? extends VirtualFile> hierarchy,
boolean source) {
Set</*Library|SyntheticLibrary*/ Object> librariesToIgnore = ContainerUtil.newHashSet();
for (VirtualFile root : hierarchy) {
librariesToIgnore.addAll(excludedFromLibraries.get(root));
if (source && libraryOrSdkSources.contains(root)) {
List<Condition<? super VirtualFile>> found = findInLibraryProducers(root, sourceOfLibraries, librariesToIgnore);
if (found != null) return Pair.create(root, found);
}
else if (!source && libraryOrSdkClasses.contains(root)) {
List<Condition<? super VirtualFile>> found = findInLibraryProducers(root, classOfLibraries, librariesToIgnore);
if (found != null) return Pair.create(root, found);
}
}
return null;
}
private static List<Condition<? super VirtualFile>> findInLibraryProducers(@NotNull VirtualFile root,
@NotNull MultiMap<VirtualFile, Object> libraryRoots,
@NotNull Set<Object> librariesToIgnore) {
if (!libraryRoots.containsKey(root)) {
return Collections.emptyList();
}
Collection<Object> producers = libraryRoots.get(root);
Set</*Library|SyntheticLibrary*/ Object> libraries = ContainerUtil.newHashSet();
List<Condition<? super VirtualFile>> exclusions = new SmartList<>();
for (Object library : producers) {
if (librariesToIgnore.contains(library)) continue;
if (library instanceof SyntheticLibrary) {
Condition<VirtualFile> exclusion = ((SyntheticLibrary)library).getExcludeFileCondition();
if (exclusion != null) {
exclusions.add(exclusion);
if (exclusion.value(root)) {
continue;
}
}
}
libraries.add(library);
}
if (!libraries.isEmpty()) {
return exclusions;
}
return null;
}
private String calcPackagePrefix(@NotNull VirtualFile root,
@NotNull List<? extends VirtualFile> hierarchy,
VirtualFile moduleContentRoot,
VirtualFile libraryClassRoot,
VirtualFile librarySourceRoot) {
VirtualFile packageRoot = findPackageRootInfo(hierarchy, moduleContentRoot, libraryClassRoot, librarySourceRoot);
String prefix = packagePrefix.get(packageRoot);
if (prefix != null && !root.equals(packageRoot)) {
assert packageRoot != null;
String relative = VfsUtilCore.getRelativePath(root, packageRoot, '.');
prefix = StringUtil.isEmpty(prefix) ? relative : prefix + '.' + relative;
}
return prefix;
}
@Nullable
private VirtualFile findPackageRootInfo(@NotNull List<? extends VirtualFile> hierarchy,
VirtualFile moduleContentRoot,
VirtualFile libraryClassRoot,
VirtualFile librarySourceRoot) {
for (VirtualFile root : hierarchy) {
if (moduleContentRoot != null &&
sourceRootOf.get(root).contains(contentRootOf.get(moduleContentRoot)) &&
librarySourceRoot == null) {
return root;
}
if (root.equals(libraryClassRoot) || root.equals(librarySourceRoot)) {
return root;
}
if (root.equals(moduleContentRoot) && !sourceRootOf.containsKey(root) && librarySourceRoot == null && libraryClassRoot == null) {
return null;
}
}
return null;
}
@NotNull
private LinkedHashSet<OrderEntry> getLibraryOrderEntries(@NotNull List<? extends VirtualFile> hierarchy,
@Nullable VirtualFile libraryClassRoot,
@Nullable VirtualFile librarySourceRoot,
@NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries,
@NotNull MultiMap<VirtualFile, OrderEntry> libSourceRootEntries) {
LinkedHashSet<OrderEntry> orderEntries = ContainerUtil.newLinkedHashSet();
for (VirtualFile root : hierarchy) {
if (root.equals(libraryClassRoot) && !sourceRootOf.containsKey(root)) {
orderEntries.addAll(libClassRootEntries.get(root));
}
if (root.equals(librarySourceRoot) && libraryClassRoot == null) {
orderEntries.addAll(libSourceRootEntries.get(root));
}
if (libClassRootEntries.containsKey(root) || sourceRootOf.containsKey(root) && librarySourceRoot == null) {
break;
}
}
return orderEntries;
}
@Nullable
private ModuleSourceOrderEntry getModuleSourceEntry(@NotNull List<? extends VirtualFile> hierarchy,
@NotNull VirtualFile moduleContentRoot,
@NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries) {
Module module = contentRootOf.get(moduleContentRoot);
for (VirtualFile root : hierarchy) {
if (sourceRootOf.get(root).contains(module)) {
return ContainerUtil.findInstance(ModuleRootManager.getInstance(module).getOrderEntries(), ModuleSourceOrderEntry.class);
}
if (libClassRootEntries.containsKey(root)) {
return null;
}
}
return null;
}
}
@NotNull
private static Pair<DirectoryInfo, String> calcDirectoryInfoAndPackagePrefix(@NotNull final VirtualFile root,
@NotNull final List<? extends VirtualFile> hierarchy,
@NotNull RootInfo info) {
VirtualFile moduleContentRoot = info.findNearestContentRoot(hierarchy);
Pair<VirtualFile, List<Condition<? super VirtualFile>>> librarySourceRootInfo = info.findLibraryRootInfo(hierarchy, true);
VirtualFile librarySourceRoot = Pair.getFirst(librarySourceRootInfo);
Pair<VirtualFile, List<Condition<? super VirtualFile>>> libraryClassRootInfo = info.findLibraryRootInfo(hierarchy, false);
VirtualFile libraryClassRoot = Pair.getFirst(libraryClassRootInfo);
boolean inProject = moduleContentRoot != null ||
(libraryClassRoot != null || librarySourceRoot != null) && !info.excludedFromSdkRoots.contains(root);
VirtualFile nearestContentRoot;
if (inProject) {
nearestContentRoot = moduleContentRoot;
}
else {
nearestContentRoot = info.findNearestContentRootForExcluded(hierarchy);
if (nearestContentRoot == null) {
return new Pair<>(NonProjectDirectoryInfo.EXCLUDED, null);
}
}
VirtualFile sourceRoot = info.findPackageRootInfo(hierarchy, moduleContentRoot, null, librarySourceRoot);
VirtualFile moduleSourceRoot = info.findPackageRootInfo(hierarchy, moduleContentRoot, null, null);
boolean inModuleSources = moduleSourceRoot != null;
boolean inLibrarySource = librarySourceRoot != null;
SourceFolder sourceFolder = moduleSourceRoot != null ? info.sourceFolders.get(moduleSourceRoot) : null;
Module module = info.contentRootOf.get(nearestContentRoot);
String unloadedModuleName = info.contentRootOfUnloaded.get(nearestContentRoot);
FileTypeAssocTable<Boolean> contentExcludePatterns =
moduleContentRoot != null ? info.excludeFromContentRootTables.get(moduleContentRoot) : null;
Condition<? super VirtualFile> libraryExclusionPredicate = getLibraryExclusionPredicate(Pair.getSecond(librarySourceRootInfo));
DirectoryInfo directoryInfo = contentExcludePatterns != null || libraryExclusionPredicate != null
? new DirectoryInfoWithExcludePatterns(root, module, nearestContentRoot, sourceRoot, sourceFolder,
libraryClassRoot, inModuleSources, inLibrarySource, !inProject,
contentExcludePatterns, libraryExclusionPredicate, unloadedModuleName)
: new DirectoryInfoImpl(root, module, nearestContentRoot, sourceRoot, sourceFolder,
libraryClassRoot, inModuleSources, inLibrarySource,
!inProject, unloadedModuleName);
String packagePrefix = info.calcPackagePrefix(root, hierarchy, moduleContentRoot, libraryClassRoot, librarySourceRoot);
return Pair.create(directoryInfo, packagePrefix);
}
@Nullable
private static Condition<? super VirtualFile> getLibraryExclusionPredicate(@Nullable List<? extends Condition<? super VirtualFile>> exclusions) {
if (exclusions != null) {
Condition<VirtualFile> result = Conditions.alwaysFalse();
for (Condition<? super VirtualFile> exclusion : exclusions) {
result = Conditions.or(result, exclusion);
}
return result == Conditions.<VirtualFile>alwaysFalse() ? null : result;
}
return null;
}
@NotNull
List<OrderEntry> getOrderEntries(@NotNull DirectoryInfo info) {
if (!(info instanceof DirectoryInfoImpl)) return Collections.emptyList();
return getOrderEntryGraph().getOrderEntries(((DirectoryInfoImpl)info).getRoot());
}
@NotNull
Set<String> getDependentUnloadedModules(@NotNull Module module) {
return getOrderEntryGraph().getDependentUnloadedModules(module);
}
/**
* An LRU cache with synchronization around the primary cache operations (get() and insertion
* of a newly created value). Other map operations are not synchronized.
*/
abstract static class SynchronizedSLRUCache<K, V> extends SLRUMap<K, V> {
private final Object myLock = new Object();
SynchronizedSLRUCache(final int protectedQueueSize, final int probationalQueueSize) {
super(protectedQueueSize, probationalQueueSize);
}
@NotNull
public abstract V createValue(@NotNull K key);
@Override
@NotNull
public V get(K key) {
V value;
synchronized (myLock) {
value = super.get(key);
if (value != null) {
return value;
}
}
value = createValue(key);
synchronized (myLock) {
put(key, value);
}
return value;
}
}
}
| platform/projectModel-impl/src/com/intellij/openapi/roots/impl/RootIndex.java | // Copyright 2000-2018 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.roots.impl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.fileTypes.impl.FileTypeAssocTable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.UnloadedModuleDescription;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.libraries.LibraryEx;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Conditions;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
import com.intellij.util.CollectionQuery;
import com.intellij.util.Function;
import com.intellij.util.Query;
import com.intellij.util.containers.Stack;
import com.intellij.util.containers.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.fileTypes.FileNameMatcherFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.*;
class RootIndex {
static final Comparator<OrderEntry> BY_OWNER_MODULE = (o1, o2) -> {
String name1 = o1.getOwnerModule().getName();
String name2 = o2.getOwnerModule().getName();
return name1.compareTo(name2);
};
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.roots.impl.RootIndex");
private static final FileTypeRegistry ourFileTypes = FileTypeRegistry.getInstance();
private final Map<VirtualFile, String> myPackagePrefixByRoot = ContainerUtil.newHashMap();
private final Map<VirtualFile, DirectoryInfo> myRootInfos = ContainerUtil.newHashMap();
private final ConcurrentBitSet myNonInterestingIds = new ConcurrentBitSet();
@NotNull private final Project myProject;
final PackageDirectoryCache myPackageDirectoryCache;
private OrderEntryGraph myOrderEntryGraph;
RootIndex(@NotNull Project project) {
myProject = project;
ApplicationManager.getApplication().assertReadAccessAllowed();
final RootInfo info = buildRootInfo(project);
MultiMap<String, VirtualFile> rootsByPackagePrefix = MultiMap.create();
Set<VirtualFile> allRoots = info.getAllRoots();
for (VirtualFile root : allRoots) {
List<VirtualFile> hierarchy = getHierarchy(root, allRoots, info);
Pair<DirectoryInfo, String> pair = hierarchy != null
? calcDirectoryInfo(root, hierarchy, info)
: new Pair<>(NonProjectDirectoryInfo.IGNORED, null);
myRootInfos.put(root, pair.first);
rootsByPackagePrefix.putValue(pair.second, root);
myPackagePrefixByRoot.put(root, pair.second);
}
myPackageDirectoryCache = new PackageDirectoryCache(rootsByPackagePrefix) {
@Override
protected boolean isPackageDirectory(@NotNull VirtualFile dir, @NotNull String packageName) {
return getInfoForFile(dir).isInProject(dir) && packageName.equals(getPackageName(dir));
}
};
}
void onLowMemory() {
myPackageDirectoryCache.onLowMemory();
}
@NotNull
private RootInfo buildRootInfo(@NotNull Project project) {
final RootInfo info = new RootInfo();
ModuleManager moduleManager = ModuleManager.getInstance(project);
for (final Module module : moduleManager.getModules()) {
final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
for (final VirtualFile contentRoot : moduleRootManager.getContentRoots()) {
if (!info.contentRootOf.containsKey(contentRoot) && ensureValid(contentRoot, module)) {
info.contentRootOf.put(contentRoot, module);
}
}
for (ContentEntry contentEntry : moduleRootManager.getContentEntries()) {
if (!(contentEntry instanceof ContentEntryImpl) || !((ContentEntryImpl)contentEntry).isDisposed()) {
for (VirtualFile excludeRoot : contentEntry.getExcludeFolderFiles()) {
if (!ensureValid(excludeRoot, contentEntry)) continue;
info.excludedFromModule.put(excludeRoot, module);
}
List<String> patterns = contentEntry.getExcludePatterns();
if (!patterns.isEmpty()) {
FileTypeAssocTable<Boolean> table = new FileTypeAssocTable<>();
for (String pattern : patterns) {
table.addAssociation(FileNameMatcherFactory.getInstance().createMatcher(pattern), Boolean.TRUE);
}
info.excludeFromContentRootTables.put(contentEntry.getFile(), table);
}
}
// Init module sources
for (final SourceFolder sourceFolder : contentEntry.getSourceFolders()) {
final VirtualFile sourceFolderRoot = sourceFolder.getFile();
if (sourceFolderRoot != null && ensureValid(sourceFolderRoot, sourceFolder)) {
info.sourceFolders.put(sourceFolderRoot, sourceFolder);
info.classAndSourceRoots.add(sourceFolderRoot);
info.sourceRootOf.putValue(sourceFolderRoot, module);
info.packagePrefix.put(sourceFolderRoot, sourceFolder.getPackagePrefix());
}
}
}
for (OrderEntry orderEntry : moduleRootManager.getOrderEntries()) {
if (orderEntry instanceof LibraryOrSdkOrderEntry) {
final LibraryOrSdkOrderEntry entry = (LibraryOrSdkOrderEntry)orderEntry;
final VirtualFile[] sourceRoots = entry.getRootFiles(OrderRootType.SOURCES);
final VirtualFile[] classRoots = entry.getRootFiles(OrderRootType.CLASSES);
// Init library sources
for (final VirtualFile sourceRoot : sourceRoots) {
if (!ensureValid(sourceRoot, entry)) continue;
info.classAndSourceRoots.add(sourceRoot);
info.libraryOrSdkSources.add(sourceRoot);
info.packagePrefix.put(sourceRoot, "");
}
// init library classes
for (final VirtualFile classRoot : classRoots) {
if (!ensureValid(classRoot, entry)) continue;
info.classAndSourceRoots.add(classRoot);
info.libraryOrSdkClasses.add(classRoot);
info.packagePrefix.put(classRoot, "");
}
if (orderEntry instanceof LibraryOrderEntry) {
Library library = ((LibraryOrderEntry)orderEntry).getLibrary();
if (library != null) {
for (VirtualFile root : ((LibraryEx)library).getExcludedRoots()) {
if (!ensureValid(root, library)) continue;
info.excludedFromLibraries.putValue(root, library);
}
for (VirtualFile root : sourceRoots) {
if (!ensureValid(root, library)) continue;
info.sourceOfLibraries.putValue(root, library);
}
for (VirtualFile root : classRoots) {
if (!ensureValid(root, library)) continue;
info.classOfLibraries.putValue(root, library);
}
}
}
}
}
}
for (AdditionalLibraryRootsProvider provider : AdditionalLibraryRootsProvider.EP_NAME.getExtensionList()) {
Collection<SyntheticLibrary> libraries = provider.getAdditionalProjectLibraries(project);
for (SyntheticLibrary descriptor : libraries) {
for (VirtualFile sourceRoot : descriptor.getSourceRoots()) {
if (!ensureValid(sourceRoot, descriptor)) continue;
info.libraryOrSdkSources.add(sourceRoot);
info.classAndSourceRoots.add(sourceRoot);
if (descriptor instanceof JavaSyntheticLibrary) {
info.packagePrefix.put(sourceRoot, "");
}
info.sourceOfLibraries.putValue(sourceRoot, descriptor);
}
for (VirtualFile classRoot : descriptor.getBinaryRoots()) {
if (!ensureValid(classRoot, project)) continue;
info.libraryOrSdkClasses.add(classRoot);
info.classAndSourceRoots.add(classRoot);
if (descriptor instanceof JavaSyntheticLibrary) {
info.packagePrefix.put(classRoot, "");
}
info.classOfLibraries.putValue(classRoot, descriptor);
}
for (VirtualFile file : descriptor.getExcludedRoots()) {
if (!ensureValid(file, project)) continue;
info.excludedFromLibraries.putValue(file, descriptor);
}
}
}
for (DirectoryIndexExcludePolicy policy : DirectoryIndexExcludePolicy.EP_NAME.getExtensions(project)) {
List<VirtualFile> files = ContainerUtil.mapNotNull(policy.getExcludeUrlsForProject(), url -> VirtualFileManager.getInstance().findFileByUrl(url));
info.excludedFromProject.addAll(ContainerUtil.filter(files, file -> ensureValid(file, policy)));
Function<Sdk, List<VirtualFile>> fun = policy.getExcludeSdkRootsStrategy();
if (fun != null) {
Set<Sdk> sdks = new HashSet<>();
for (Module m : ModuleManager.getInstance(myProject).getModules()) {
Sdk sdk = ModuleRootManager.getInstance(m).getSdk();
if (sdk != null) {
sdks.add(sdk);
}
}
Set<VirtualFile> roots = new HashSet<>();
for (Sdk sdk: sdks) {
roots.addAll(Arrays.asList(sdk.getRootProvider().getFiles(OrderRootType.CLASSES)));
}
for (Sdk sdk: sdks) {
info.excludedFromSdkRoots
.addAll(ContainerUtil.filter(fun.fun(sdk), file -> ensureValid(file, policy) && !roots.contains(file)));
}
}
}
for (UnloadedModuleDescription description : moduleManager.getUnloadedModuleDescriptions()) {
for (VirtualFilePointer pointer : description.getContentRoots()) {
VirtualFile contentRoot = pointer.getFile();
if (contentRoot != null && ensureValid(contentRoot, description)) {
info.contentRootOfUnloaded.put(contentRoot, description.getName());
}
}
}
return info;
}
private static boolean ensureValid(@NotNull VirtualFile file, @NotNull Object container) {
if (!(file instanceof VirtualFileWithId)) {
//skip roots from unsupported file systems (e.g. http)
return false;
}
if (!file.isValid()) {
LOG.error("Invalid root " + file + " in " + container);
return false;
}
return true;
}
@NotNull
private synchronized OrderEntryGraph getOrderEntryGraph() {
if (myOrderEntryGraph == null) {
RootInfo rootInfo = buildRootInfo(myProject);
myOrderEntryGraph = new OrderEntryGraph(myProject, rootInfo);
}
return myOrderEntryGraph;
}
/**
* A reverse dependency graph of (library, jdk, module, module source) -> (module).
* <p>
* <p>Each edge carries with it the associated OrderEntry that caused the dependency.
*/
private static class OrderEntryGraph {
private static class Edge {
private final Module myKey;
private final ModuleOrderEntry myOrderEntry; // Order entry from myKey -> the node containing the edge
private final boolean myRecursive; // Whether this edge should be descended into during graph walk
Edge(@NotNull Module key, @NotNull ModuleOrderEntry orderEntry, boolean recursive) {
myKey = key;
myOrderEntry = orderEntry;
myRecursive = recursive;
}
@Override
public String toString() {
return myOrderEntry.toString();
}
}
private static class Node {
private final Module myKey;
private final List<Edge> myEdges = new ArrayList<>();
private Set<String> myUnloadedDependentModules;
private Node(@NotNull Module key) {
myKey = key;
}
@Override
public String toString() {
return myKey.toString();
}
}
private static class Graph {
private final Map<Module, Node> myNodes = new HashMap<>();
}
private final Project myProject;
private final RootInfo myRootInfo;
private final Set<VirtualFile> myAllRoots;
private final Graph myGraph;
private final MultiMap<VirtualFile, Node> myRoots; // Map of roots to their root nodes, eg. library jar -> library node
private final SynchronizedSLRUCache<VirtualFile, List<OrderEntry>> myCache;
private final SynchronizedSLRUCache<Module, Set<String>> myDependentUnloadedModulesCache;
private final MultiMap<VirtualFile, OrderEntry> myLibClassRootEntries;
private final MultiMap<VirtualFile, OrderEntry> myLibSourceRootEntries;
OrderEntryGraph(@NotNull Project project, @NotNull RootInfo rootInfo) {
myProject = project;
myRootInfo = rootInfo;
myAllRoots = myRootInfo.getAllRoots();
int cacheSize = Math.max(25, myAllRoots.size() / 100 * 2);
myCache = new SynchronizedSLRUCache<VirtualFile, List<OrderEntry>>(cacheSize, cacheSize) {
@NotNull
@Override
public List<OrderEntry> createValue(@NotNull VirtualFile key) {
return collectOrderEntries(key);
}
};
int dependentUnloadedModulesCacheSize = ModuleManager.getInstance(project).getModules().length / 2;
myDependentUnloadedModulesCache =
new SynchronizedSLRUCache<Module, Set<String>>(dependentUnloadedModulesCacheSize, dependentUnloadedModulesCacheSize) {
@NotNull
@Override
public Set<String> createValue(@NotNull Module key) {
return collectDependentUnloadedModules(key);
}
};
Pair<Graph, MultiMap<VirtualFile, Node>> pair = initGraphRoots();
myGraph = pair.getFirst();
myRoots = pair.getSecond();
Pair<MultiMap<VirtualFile, OrderEntry>, MultiMap<VirtualFile, OrderEntry>> lpair = initLibraryClassSourceRoots();
myLibClassRootEntries = lpair.getFirst();
myLibSourceRootEntries = lpair.getSecond();
}
@NotNull
private Pair<Graph, MultiMap<VirtualFile, Node>> initGraphRoots() {
Graph graph = new Graph();
MultiMap<VirtualFile, Node> roots = MultiMap.createSmart();
ModuleManager moduleManager = ModuleManager.getInstance(myProject);
for (final Module module : moduleManager.getModules()) {
final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
List<OrderEnumerationHandler> handlers = OrderEnumeratorBase.getCustomHandlers(module);
for (OrderEntry orderEntry : moduleRootManager.getOrderEntries()) {
if (orderEntry instanceof ModuleOrderEntry) {
ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)orderEntry;
final Module depModule = moduleOrderEntry.getModule();
if (depModule != null) {
Node node = graph.myNodes.get(depModule);
OrderEnumerator en = OrderEnumerator.orderEntries(depModule).exportedOnly();
if (node == null) {
node = new Node(depModule);
graph.myNodes.put(depModule, node);
VirtualFile[] importedClassRoots = en.classes().usingCache().getRoots();
for (VirtualFile importedClassRoot : importedClassRoots) {
roots.putValue(importedClassRoot, node);
}
VirtualFile[] importedSourceRoots = en.sources().usingCache().getRoots();
for (VirtualFile sourceRoot : importedSourceRoots) {
roots.putValue(sourceRoot, node);
}
}
boolean shouldRecurse = en.recursively().shouldRecurse(moduleOrderEntry, handlers);
node.myEdges.add(new Edge(module, moduleOrderEntry, shouldRecurse));
}
}
}
}
for (UnloadedModuleDescription description : moduleManager.getUnloadedModuleDescriptions()) {
for (String depName : description.getDependencyModuleNames()) {
Module depModule = moduleManager.findModuleByName(depName);
if (depModule != null) {
Node node = graph.myNodes.get(depModule);
if (node == null) {
node = new Node(depModule);
graph.myNodes.put(depModule, node);
}
if (node.myUnloadedDependentModules == null) {
node.myUnloadedDependentModules = new LinkedHashSet<>();
}
node.myUnloadedDependentModules.add(description.getName());
}
}
}
return Pair.create(graph, roots);
}
@NotNull
private Pair<MultiMap<VirtualFile, OrderEntry>, MultiMap<VirtualFile, OrderEntry>> initLibraryClassSourceRoots() {
MultiMap<VirtualFile, OrderEntry> libClassRootEntries = MultiMap.createSmart();
MultiMap<VirtualFile, OrderEntry> libSourceRootEntries = MultiMap.createSmart();
for (final Module module : ModuleManager.getInstance(myProject).getModules()) {
final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
for (OrderEntry orderEntry : moduleRootManager.getOrderEntries()) {
if (orderEntry instanceof LibraryOrSdkOrderEntry) {
final LibraryOrSdkOrderEntry entry = (LibraryOrSdkOrderEntry)orderEntry;
for (final VirtualFile sourceRoot : entry.getRootFiles(OrderRootType.SOURCES)) {
libSourceRootEntries.putValue(sourceRoot, orderEntry);
}
for (final VirtualFile classRoot : entry.getRootFiles(OrderRootType.CLASSES)) {
libClassRootEntries.putValue(classRoot, orderEntry);
}
}
}
}
return Pair.create(libClassRootEntries, libSourceRootEntries);
}
@NotNull
private List<OrderEntry> getOrderEntries(@NotNull VirtualFile file) {
return myCache.get(file);
}
/**
* Traverses the graph from the given file, collecting all encountered order entries.
*/
@NotNull
private List<OrderEntry> collectOrderEntries(@NotNull VirtualFile file) {
List<VirtualFile> roots = getHierarchy(file, myAllRoots, myRootInfo);
if (roots == null) {
return Collections.emptyList();
}
Stack<Node> stack = new Stack<>();
for (VirtualFile root : roots) {
Collection<Node> nodes = myRoots.get(root);
for (Node node : nodes) {
stack.push(node);
}
}
Set<Node> seen = new HashSet<>();
List<OrderEntry> result = new ArrayList<>();
while (!stack.isEmpty()) {
Node node = stack.pop();
if (seen.contains(node)) {
continue;
}
seen.add(node);
for (Edge edge : node.myEdges) {
result.add(edge.myOrderEntry);
if (edge.myRecursive) {
Node targetNode = myGraph.myNodes.get(edge.myKey);
if (targetNode != null) {
stack.push(targetNode);
}
}
}
}
@Nullable Pair<VirtualFile, Collection<?>> libraryClassRootInfo = myRootInfo.findLibraryRootInfo(roots, false);
@Nullable Pair<VirtualFile, Collection<?>> librarySourceRootInfo = myRootInfo.findLibraryRootInfo(roots, true);
result.addAll(myRootInfo.getLibraryOrderEntries(roots,
Pair.getFirst(libraryClassRootInfo),
Pair.getFirst(librarySourceRootInfo),
myLibClassRootEntries, myLibSourceRootEntries));
VirtualFile moduleContentRoot = myRootInfo.findNearestContentRoot(roots);
if (moduleContentRoot != null) {
ContainerUtil.addIfNotNull(result, myRootInfo.getModuleSourceEntry(roots, moduleContentRoot, myLibClassRootEntries));
}
Collections.sort(result, BY_OWNER_MODULE);
return ContainerUtil.immutableList(result);
}
@NotNull
Set<String> getDependentUnloadedModules(@NotNull Module module) {
return myDependentUnloadedModulesCache.get(module);
}
/**
* @return names of unloaded modules which directly or transitively via exported dependencies depend on the specified module
*/
@NotNull
private Set<String> collectDependentUnloadedModules(@NotNull Module module) {
Node start = myGraph.myNodes.get(module);
if (start == null) return Collections.emptySet();
Deque<Node> stack = new ArrayDeque<>();
stack.push(start);
Set<Node> seen = new HashSet<>();
Set<String> result = null;
while (!stack.isEmpty()) {
Node node = stack.pop();
if (!seen.add(node)) {
continue;
}
if (node.myUnloadedDependentModules != null) {
if (result == null) {
result = new LinkedHashSet<>(node.myUnloadedDependentModules);
}
else {
result.addAll(node.myUnloadedDependentModules);
}
}
for (Edge edge : node.myEdges) {
if (edge.myRecursive) {
Node targetNode = myGraph.myNodes.get(edge.myKey);
if (targetNode != null) {
stack.push(targetNode);
}
}
}
}
return result != null ? result : Collections.emptySet();
}
}
@NotNull
DirectoryInfo getInfoForFile(@NotNull VirtualFile file) {
if (!file.isValid() || !(file instanceof VirtualFileWithId)) {
return NonProjectDirectoryInfo.INVALID;
}
for (VirtualFile each = file; each != null; each = each.getParent()) {
int id = ((VirtualFileWithId)each).getId();
if (!myNonInterestingIds.get(id)) {
DirectoryInfo info = myRootInfos.get(each);
if (info != null) {
return info;
}
if (ourFileTypes.isFileIgnored(each)) {
return NonProjectDirectoryInfo.IGNORED;
}
myNonInterestingIds.set(id);
}
}
return NonProjectDirectoryInfo.NOT_UNDER_PROJECT_ROOTS;
}
@NotNull
Query<VirtualFile> getDirectoriesByPackageName(@NotNull final String packageName, final boolean includeLibrarySources) {
// Note that this method is used in upsource as well, hence, don't reduce this method's visibility.
List<VirtualFile> result = myPackageDirectoryCache.getDirectoriesByPackageName(packageName);
if (!includeLibrarySources) {
result = ContainerUtil.filter(result, file -> {
DirectoryInfo info = getInfoForFile(file);
return info.isInProject(file) && (!info.isInLibrarySource(file) || info.isInModuleSource(file) || info.hasLibraryClassRoot());
});
}
return new CollectionQuery<>(result);
}
@Nullable
String getPackageName(@NotNull final VirtualFile dir) {
if (dir.isDirectory()) {
if (ourFileTypes.isFileIgnored(dir)) {
return null;
}
if (myPackagePrefixByRoot.containsKey(dir)) {
return myPackagePrefixByRoot.get(dir);
}
final VirtualFile parent = dir.getParent();
if (parent != null) {
return getPackageNameForSubdir(getPackageName(parent), dir.getName());
}
}
return null;
}
private static String getPackageNameForSubdir(@Nullable String parentPackageName, @NotNull String subdirName) {
if (parentPackageName == null) return null;
return parentPackageName.isEmpty() ? subdirName : parentPackageName + "." + subdirName;
}
@Nullable("returns null only if dir is under ignored folder")
private static List<VirtualFile> getHierarchy(@NotNull VirtualFile deepDir, @NotNull Set<? extends VirtualFile> allRoots, @NotNull RootInfo info) {
List<VirtualFile> hierarchy = ContainerUtil.newArrayList();
boolean hasContentRoots = false;
for (VirtualFile dir = deepDir; dir != null; dir = dir.getParent()) {
hasContentRoots |= info.contentRootOf.get(dir) != null;
if (!hasContentRoots && ourFileTypes.isFileIgnored(dir)) {
return null;
}
if (allRoots.contains(dir)) {
hierarchy.add(dir);
}
}
return hierarchy;
}
private static class RootInfo {
// getDirectoriesByPackageName used to be in this order, some clients might rely on that
@NotNull private final Set<VirtualFile> classAndSourceRoots = new LinkedHashSet<>();
@NotNull private final Set<VirtualFile> libraryOrSdkSources = new HashSet<>();
@NotNull private final Set<VirtualFile> libraryOrSdkClasses = new HashSet<>();
@NotNull private final Map<VirtualFile, Module> contentRootOf = new HashMap<>();
@NotNull private final Map<VirtualFile, String> contentRootOfUnloaded = new HashMap<>();
@NotNull private final MultiMap<VirtualFile, Module> sourceRootOf = MultiMap.createSet();
@NotNull private final Map<VirtualFile, SourceFolder> sourceFolders = new HashMap<>();
@NotNull private final MultiMap<VirtualFile, /*Library|SyntheticLibrary*/ Object> excludedFromLibraries = MultiMap.createSmart();
@NotNull private final MultiMap<VirtualFile, /*Library|SyntheticLibrary*/ Object> classOfLibraries = MultiMap.createSmart();
@NotNull private final MultiMap<VirtualFile, /*Library|SyntheticLibrary*/ Object> sourceOfLibraries = MultiMap.createSmart();
@NotNull private final Set<VirtualFile> excludedFromProject = new HashSet<>();
@NotNull private final Set<VirtualFile> excludedFromSdkRoots = new HashSet<>();
@NotNull private final Map<VirtualFile, Module> excludedFromModule = new HashMap<>();
@NotNull private final Map<VirtualFile, FileTypeAssocTable<Boolean>> excludeFromContentRootTables = new HashMap<>();
@NotNull private final Map<VirtualFile, String> packagePrefix = new HashMap<>();
@NotNull
Set<VirtualFile> getAllRoots() {
Set<VirtualFile> result = new LinkedHashSet<>();
result.addAll(classAndSourceRoots);
result.addAll(contentRootOf.keySet());
result.addAll(contentRootOfUnloaded.keySet());
result.addAll(excludedFromLibraries.keySet());
result.addAll(excludedFromModule.keySet());
result.addAll(excludedFromProject);
result.addAll(excludedFromSdkRoots);
return result;
}
/**
* Returns nearest content root for a file by its parent directories hierarchy. If the file is excluded (i.e. located under an excluded
* root and there are no source roots on the path to the excluded root) returns {@code null}.
*/
@Nullable
private VirtualFile findNearestContentRoot(@NotNull List<? extends VirtualFile> hierarchy) {
Collection<Module> sourceRootOwners = null;
boolean underExcludedSourceRoot = false;
for (VirtualFile root : hierarchy) {
Module module = contentRootOf.get(root);
Module excludedFrom = excludedFromModule.get(root);
if (module != null) {
FileTypeAssocTable<Boolean> table = excludeFromContentRootTables.get(root);
if (table != null && isExcludedByPattern(root, hierarchy, table)) {
excludedFrom = module;
}
}
if (module != null && (excludedFrom != module || underExcludedSourceRoot && sourceRootOwners.contains(module))) {
return root;
}
if (excludedFrom != null || excludedFromProject.contains(root) || contentRootOfUnloaded.containsKey(root)) {
if (sourceRootOwners == null) {
return null;
}
underExcludedSourceRoot = true;
}
if (!underExcludedSourceRoot && sourceRootOf.containsKey(root)) {
Collection<Module> modulesForSourceRoot = sourceRootOf.get(root);
if (!modulesForSourceRoot.isEmpty()) {
sourceRootOwners = sourceRootOwners == null ? modulesForSourceRoot : ContainerUtil.union(sourceRootOwners, modulesForSourceRoot);
}
}
}
return null;
}
private static boolean isExcludedByPattern(@NotNull VirtualFile contentRoot, List<? extends VirtualFile> hierarchy, @NotNull FileTypeAssocTable<Boolean> table) {
for (VirtualFile file : hierarchy) {
if (table.findAssociatedFileType(file.getNameSequence()) != null) {
return true;
}
if (file.equals(contentRoot)) {
break;
}
}
return false;
}
@Nullable
private VirtualFile findNearestContentRootForExcluded(@NotNull List<? extends VirtualFile> hierarchy) {
for (VirtualFile root : hierarchy) {
if (contentRootOf.containsKey(root) || contentRootOfUnloaded.containsKey(root)) {
return root;
}
}
return null;
}
/**
* @return root and set of libraries that provided it
*/
@Nullable
private Pair<VirtualFile, Collection<?>> findLibraryRootInfo(@NotNull List<? extends VirtualFile> hierarchy, boolean source) {
Set<Object> librariesToIgnore = ContainerUtil.newHashSet();
for (VirtualFile root : hierarchy) {
librariesToIgnore.addAll(excludedFromLibraries.get(root));
if (source && libraryOrSdkSources.contains(root)) {
if (!sourceOfLibraries.containsKey(root)) {
return Pair.create(root, Collections.emptySet());
}
Collection<Object> rootProducers = findLibraryRootProducers(sourceOfLibraries.get(root), root, librariesToIgnore);
if (!rootProducers.isEmpty()) {
return Pair.create(root, rootProducers);
}
}
else if (!source && libraryOrSdkClasses.contains(root)) {
if (!classOfLibraries.containsKey(root)) {
return Pair.create(root, Collections.emptySet());
}
Collection<Object> rootProducers = findLibraryRootProducers(classOfLibraries.get(root), root, librariesToIgnore);
if (!rootProducers.isEmpty()) {
return Pair.create(root, rootProducers);
}
}
}
return null;
}
@NotNull
private static Collection<Object> findLibraryRootProducers(@NotNull Collection<?> producers,
@NotNull VirtualFile root,
@NotNull Set<?> librariesToIgnore) {
Set<Object> libraries = ContainerUtil.newHashSet();
for (Object library : producers) {
if (librariesToIgnore.contains(library)) continue;
if (library instanceof SyntheticLibrary) {
Condition<VirtualFile> exclusion = ((SyntheticLibrary)library).getExcludeFileCondition();
if (exclusion != null && exclusion.value(root)) {
continue;
}
}
libraries.add(library);
}
return libraries;
}
private String calcPackagePrefix(@NotNull VirtualFile root,
@NotNull List<? extends VirtualFile> hierarchy,
VirtualFile moduleContentRoot,
VirtualFile libraryClassRoot,
VirtualFile librarySourceRoot) {
VirtualFile packageRoot = findPackageRootInfo(hierarchy, moduleContentRoot, libraryClassRoot, librarySourceRoot);
String prefix = packagePrefix.get(packageRoot);
if (prefix != null && !root.equals(packageRoot)) {
assert packageRoot != null;
String relative = VfsUtilCore.getRelativePath(root, packageRoot, '.');
prefix = StringUtil.isEmpty(prefix) ? relative : prefix + '.' + relative;
}
return prefix;
}
@Nullable
private VirtualFile findPackageRootInfo(@NotNull List<? extends VirtualFile> hierarchy,
VirtualFile moduleContentRoot,
VirtualFile libraryClassRoot,
VirtualFile librarySourceRoot) {
for (VirtualFile root : hierarchy) {
if (moduleContentRoot != null &&
sourceRootOf.get(root).contains(contentRootOf.get(moduleContentRoot)) &&
librarySourceRoot == null) {
return root;
}
if (root.equals(libraryClassRoot) || root.equals(librarySourceRoot)) {
return root;
}
if (root.equals(moduleContentRoot) && !sourceRootOf.containsKey(root) && librarySourceRoot == null && libraryClassRoot == null) {
return null;
}
}
return null;
}
@NotNull
private LinkedHashSet<OrderEntry> getLibraryOrderEntries(@NotNull List<? extends VirtualFile> hierarchy,
@Nullable VirtualFile libraryClassRoot,
@Nullable VirtualFile librarySourceRoot,
@NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries,
@NotNull MultiMap<VirtualFile, OrderEntry> libSourceRootEntries) {
LinkedHashSet<OrderEntry> orderEntries = ContainerUtil.newLinkedHashSet();
for (VirtualFile root : hierarchy) {
if (root.equals(libraryClassRoot) && !sourceRootOf.containsKey(root)) {
orderEntries.addAll(libClassRootEntries.get(root));
}
if (root.equals(librarySourceRoot) && libraryClassRoot == null) {
orderEntries.addAll(libSourceRootEntries.get(root));
}
if (libClassRootEntries.containsKey(root) || sourceRootOf.containsKey(root) && librarySourceRoot == null) {
break;
}
}
return orderEntries;
}
@Nullable
private ModuleSourceOrderEntry getModuleSourceEntry(@NotNull List<? extends VirtualFile> hierarchy,
@NotNull VirtualFile moduleContentRoot,
@NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries) {
Module module = contentRootOf.get(moduleContentRoot);
for (VirtualFile root : hierarchy) {
if (sourceRootOf.get(root).contains(module)) {
return ContainerUtil.findInstance(ModuleRootManager.getInstance(module).getOrderEntries(), ModuleSourceOrderEntry.class);
}
if (libClassRootEntries.containsKey(root)) {
return null;
}
}
return null;
}
}
@NotNull
private static Pair<DirectoryInfo, String> calcDirectoryInfo(@NotNull final VirtualFile root,
@NotNull final List<? extends VirtualFile> hierarchy,
@NotNull RootInfo info) {
VirtualFile moduleContentRoot = info.findNearestContentRoot(hierarchy);
Pair<VirtualFile, Collection<?>> librarySourceRootInfo = info.findLibraryRootInfo(hierarchy, true);
VirtualFile librarySourceRoot = Pair.getFirst(librarySourceRootInfo);
Pair<VirtualFile, Collection<?>> libraryClassRootInfo = info.findLibraryRootInfo(hierarchy, false);
VirtualFile libraryClassRoot = Pair.getFirst(libraryClassRootInfo);
boolean inProject = moduleContentRoot != null ||
(libraryClassRoot != null || librarySourceRoot != null) && !info.excludedFromSdkRoots.contains(root);
VirtualFile nearestContentRoot;
if (inProject) {
nearestContentRoot = moduleContentRoot;
}
else {
nearestContentRoot = info.findNearestContentRootForExcluded(hierarchy);
if (nearestContentRoot == null) {
return new Pair<>(NonProjectDirectoryInfo.EXCLUDED, null);
}
}
VirtualFile sourceRoot = info.findPackageRootInfo(hierarchy, moduleContentRoot, null, librarySourceRoot);
VirtualFile moduleSourceRoot = info.findPackageRootInfo(hierarchy, moduleContentRoot, null, null);
boolean inModuleSources = moduleSourceRoot != null;
boolean inLibrarySource = librarySourceRoot != null;
SourceFolder sourceFolder = moduleSourceRoot != null ? info.sourceFolders.get(moduleSourceRoot) : null;
Module module = info.contentRootOf.get(nearestContentRoot);
String unloadedModuleName = info.contentRootOfUnloaded.get(nearestContentRoot);
FileTypeAssocTable<Boolean> contentExcludePatterns =
moduleContentRoot != null ? info.excludeFromContentRootTables.get(moduleContentRoot) : null;
Condition<VirtualFile> libraryExclusionPredicate = getLibraryExclusionPredicate(librarySourceRootInfo);
DirectoryInfo directoryInfo = contentExcludePatterns != null || libraryExclusionPredicate != null
? new DirectoryInfoWithExcludePatterns(root, module, nearestContentRoot, sourceRoot, sourceFolder,
libraryClassRoot, inModuleSources, inLibrarySource, !inProject,
contentExcludePatterns, libraryExclusionPredicate, unloadedModuleName)
: new DirectoryInfoImpl(root, module, nearestContentRoot, sourceRoot, sourceFolder,
libraryClassRoot, inModuleSources, inLibrarySource,
!inProject, unloadedModuleName);
String packagePrefix = info.calcPackagePrefix(root, hierarchy, moduleContentRoot, libraryClassRoot, librarySourceRoot);
return Pair.create(directoryInfo, packagePrefix);
}
@Nullable
private static Condition<VirtualFile> getLibraryExclusionPredicate(@Nullable Pair<VirtualFile, Collection<?>> libraryRootInfo) {
Condition<VirtualFile> result = Conditions.alwaysFalse();
if (libraryRootInfo != null) {
for (Object library : libraryRootInfo.second) {
Condition<VirtualFile> exclusionPredicate =
library instanceof SyntheticLibrary ? ((SyntheticLibrary)library).getExcludeFileCondition() : null;
if (exclusionPredicate == null) continue;
result = Conditions.or(result, exclusionPredicate);
}
}
return result != Conditions.<VirtualFile>alwaysFalse() ? result : null;
}
@NotNull
List<OrderEntry> getOrderEntries(@NotNull DirectoryInfo info) {
if (!(info instanceof DirectoryInfoImpl)) return Collections.emptyList();
return getOrderEntryGraph().getOrderEntries(((DirectoryInfoImpl)info).getRoot());
}
@NotNull
Set<String> getDependentUnloadedModules(@NotNull Module module) {
return getOrderEntryGraph().getDependentUnloadedModules(module);
}
/**
* An LRU cache with synchronization around the primary cache operations (get() and insertion
* of a newly created value). Other map operations are not synchronized.
*/
abstract static class SynchronizedSLRUCache<K, V> extends SLRUMap<K, V> {
private final Object myLock = new Object();
SynchronizedSLRUCache(final int protectedQueueSize, final int probationalQueueSize) {
super(protectedQueueSize, probationalQueueSize);
}
@NotNull
public abstract V createValue(@NotNull K key);
@Override
@NotNull
public V get(K key) {
V value;
synchronized (myLock) {
value = super.get(key);
if (value != null) {
return value;
}
}
value = createValue(key);
synchronized (myLock) {
put(key, value);
}
return value;
}
}
}
| cleanup: fewer type-less Object collections
| platform/projectModel-impl/src/com/intellij/openapi/roots/impl/RootIndex.java | cleanup: fewer type-less Object collections | <ide><path>latform/projectModel-impl/src/com/intellij/openapi/roots/impl/RootIndex.java
<ide> import com.intellij.util.CollectionQuery;
<ide> import com.intellij.util.Function;
<ide> import com.intellij.util.Query;
<add>import com.intellij.util.SmartList;
<ide> import com.intellij.util.containers.Stack;
<ide> import com.intellij.util.containers.*;
<ide> import org.jetbrains.annotations.NotNull;
<ide> for (VirtualFile root : allRoots) {
<ide> List<VirtualFile> hierarchy = getHierarchy(root, allRoots, info);
<ide> Pair<DirectoryInfo, String> pair = hierarchy != null
<del> ? calcDirectoryInfo(root, hierarchy, info)
<add> ? calcDirectoryInfoAndPackagePrefix(root, hierarchy, info)
<ide> : new Pair<>(NonProjectDirectoryInfo.IGNORED, null);
<ide> myRootInfos.put(root, pair.first);
<ide> rootsByPackagePrefix.putValue(pair.second, root);
<ide> }
<ide> }
<ide>
<del> @Nullable Pair<VirtualFile, Collection<?>> libraryClassRootInfo = myRootInfo.findLibraryRootInfo(roots, false);
<del> @Nullable Pair<VirtualFile, Collection<?>> librarySourceRootInfo = myRootInfo.findLibraryRootInfo(roots, true);
<add> @Nullable Pair<VirtualFile, List<Condition<? super VirtualFile>>> libraryClassRootInfo = myRootInfo.findLibraryRootInfo(roots, false);
<add> @Nullable Pair<VirtualFile, List<Condition<? super VirtualFile>>> librarySourceRootInfo = myRootInfo.findLibraryRootInfo(roots, true);
<ide> result.addAll(myRootInfo.getLibraryOrderEntries(roots,
<ide> Pair.getFirst(libraryClassRootInfo),
<ide> Pair.getFirst(librarySourceRootInfo),
<ide> return null;
<ide> }
<ide>
<del> private static boolean isExcludedByPattern(@NotNull VirtualFile contentRoot, List<? extends VirtualFile> hierarchy, @NotNull FileTypeAssocTable<Boolean> table) {
<add> private static boolean isExcludedByPattern(@NotNull VirtualFile contentRoot,
<add> List<? extends VirtualFile> hierarchy,
<add> @NotNull FileTypeAssocTable<Boolean> table) {
<ide> for (VirtualFile file : hierarchy) {
<ide> if (table.findAssociatedFileType(file.getNameSequence()) != null) {
<ide> return true;
<ide> * @return root and set of libraries that provided it
<ide> */
<ide> @Nullable
<del> private Pair<VirtualFile, Collection<?>> findLibraryRootInfo(@NotNull List<? extends VirtualFile> hierarchy, boolean source) {
<del> Set<Object> librariesToIgnore = ContainerUtil.newHashSet();
<add> private Pair<VirtualFile, List<Condition<? super VirtualFile>>> findLibraryRootInfo(@NotNull List<? extends VirtualFile> hierarchy,
<add> boolean source) {
<add> Set</*Library|SyntheticLibrary*/ Object> librariesToIgnore = ContainerUtil.newHashSet();
<ide> for (VirtualFile root : hierarchy) {
<ide> librariesToIgnore.addAll(excludedFromLibraries.get(root));
<ide> if (source && libraryOrSdkSources.contains(root)) {
<del> if (!sourceOfLibraries.containsKey(root)) {
<del> return Pair.create(root, Collections.emptySet());
<del> }
<del> Collection<Object> rootProducers = findLibraryRootProducers(sourceOfLibraries.get(root), root, librariesToIgnore);
<del> if (!rootProducers.isEmpty()) {
<del> return Pair.create(root, rootProducers);
<del> }
<add> List<Condition<? super VirtualFile>> found = findInLibraryProducers(root, sourceOfLibraries, librariesToIgnore);
<add> if (found != null) return Pair.create(root, found);
<ide> }
<ide> else if (!source && libraryOrSdkClasses.contains(root)) {
<del> if (!classOfLibraries.containsKey(root)) {
<del> return Pair.create(root, Collections.emptySet());
<del> }
<del> Collection<Object> rootProducers = findLibraryRootProducers(classOfLibraries.get(root), root, librariesToIgnore);
<del> if (!rootProducers.isEmpty()) {
<del> return Pair.create(root, rootProducers);
<del> }
<add> List<Condition<? super VirtualFile>> found = findInLibraryProducers(root, classOfLibraries, librariesToIgnore);
<add> if (found != null) return Pair.create(root, found);
<ide> }
<ide> }
<ide> return null;
<ide> }
<ide>
<del> @NotNull
<del> private static Collection<Object> findLibraryRootProducers(@NotNull Collection<?> producers,
<del> @NotNull VirtualFile root,
<del> @NotNull Set<?> librariesToIgnore) {
<del> Set<Object> libraries = ContainerUtil.newHashSet();
<add> private static List<Condition<? super VirtualFile>> findInLibraryProducers(@NotNull VirtualFile root,
<add> @NotNull MultiMap<VirtualFile, Object> libraryRoots,
<add> @NotNull Set<Object> librariesToIgnore) {
<add> if (!libraryRoots.containsKey(root)) {
<add> return Collections.emptyList();
<add> }
<add> Collection<Object> producers = libraryRoots.get(root);
<add> Set</*Library|SyntheticLibrary*/ Object> libraries = ContainerUtil.newHashSet();
<add> List<Condition<? super VirtualFile>> exclusions = new SmartList<>();
<ide> for (Object library : producers) {
<ide> if (librariesToIgnore.contains(library)) continue;
<ide> if (library instanceof SyntheticLibrary) {
<ide> Condition<VirtualFile> exclusion = ((SyntheticLibrary)library).getExcludeFileCondition();
<del> if (exclusion != null && exclusion.value(root)) {
<del> continue;
<add> if (exclusion != null) {
<add> exclusions.add(exclusion);
<add> if (exclusion.value(root)) {
<add> continue;
<add> }
<ide> }
<ide> }
<ide> libraries.add(library);
<ide> }
<del> return libraries;
<add> if (!libraries.isEmpty()) {
<add> return exclusions;
<add> }
<add> return null;
<ide> }
<ide>
<ide> private String calcPackagePrefix(@NotNull VirtualFile root,
<ide> }
<ide>
<ide> @NotNull
<del> private static Pair<DirectoryInfo, String> calcDirectoryInfo(@NotNull final VirtualFile root,
<del> @NotNull final List<? extends VirtualFile> hierarchy,
<del> @NotNull RootInfo info) {
<add> private static Pair<DirectoryInfo, String> calcDirectoryInfoAndPackagePrefix(@NotNull final VirtualFile root,
<add> @NotNull final List<? extends VirtualFile> hierarchy,
<add> @NotNull RootInfo info) {
<ide> VirtualFile moduleContentRoot = info.findNearestContentRoot(hierarchy);
<del> Pair<VirtualFile, Collection<?>> librarySourceRootInfo = info.findLibraryRootInfo(hierarchy, true);
<add> Pair<VirtualFile, List<Condition<? super VirtualFile>>> librarySourceRootInfo = info.findLibraryRootInfo(hierarchy, true);
<ide> VirtualFile librarySourceRoot = Pair.getFirst(librarySourceRootInfo);
<ide>
<del> Pair<VirtualFile, Collection<?>> libraryClassRootInfo = info.findLibraryRootInfo(hierarchy, false);
<add> Pair<VirtualFile, List<Condition<? super VirtualFile>>> libraryClassRootInfo = info.findLibraryRootInfo(hierarchy, false);
<ide> VirtualFile libraryClassRoot = Pair.getFirst(libraryClassRootInfo);
<ide>
<ide> boolean inProject = moduleContentRoot != null ||
<ide> String unloadedModuleName = info.contentRootOfUnloaded.get(nearestContentRoot);
<ide> FileTypeAssocTable<Boolean> contentExcludePatterns =
<ide> moduleContentRoot != null ? info.excludeFromContentRootTables.get(moduleContentRoot) : null;
<del> Condition<VirtualFile> libraryExclusionPredicate = getLibraryExclusionPredicate(librarySourceRootInfo);
<add> Condition<? super VirtualFile> libraryExclusionPredicate = getLibraryExclusionPredicate(Pair.getSecond(librarySourceRootInfo));
<ide>
<ide> DirectoryInfo directoryInfo = contentExcludePatterns != null || libraryExclusionPredicate != null
<ide> ? new DirectoryInfoWithExcludePatterns(root, module, nearestContentRoot, sourceRoot, sourceFolder,
<ide> }
<ide>
<ide> @Nullable
<del> private static Condition<VirtualFile> getLibraryExclusionPredicate(@Nullable Pair<VirtualFile, Collection<?>> libraryRootInfo) {
<del> Condition<VirtualFile> result = Conditions.alwaysFalse();
<del> if (libraryRootInfo != null) {
<del> for (Object library : libraryRootInfo.second) {
<del> Condition<VirtualFile> exclusionPredicate =
<del> library instanceof SyntheticLibrary ? ((SyntheticLibrary)library).getExcludeFileCondition() : null;
<del> if (exclusionPredicate == null) continue;
<del> result = Conditions.or(result, exclusionPredicate);
<del> }
<del> }
<del> return result != Conditions.<VirtualFile>alwaysFalse() ? result : null;
<add> private static Condition<? super VirtualFile> getLibraryExclusionPredicate(@Nullable List<? extends Condition<? super VirtualFile>> exclusions) {
<add> if (exclusions != null) {
<add> Condition<VirtualFile> result = Conditions.alwaysFalse();
<add> for (Condition<? super VirtualFile> exclusion : exclusions) {
<add> result = Conditions.or(result, exclusion);
<add> }
<add> return result == Conditions.<VirtualFile>alwaysFalse() ? null : result;
<add> }
<add> return null;
<ide> }
<ide>
<ide> @NotNull |
|
Java | mit | 22556ceeb9f21bfd4a2e37f5ea2c93a4d3371951 | 0 | AldurD392/SubgraphExplorer,AldurD392/SubgraphExplorer,AldurD392/SubgraphExplorer | package com.github.aldurd392.bigdatacontest.utils;
import com.github.aldurd392.bigdatacontest.Main;
import com.github.aldurd392.bigdatacontest.datatypes.IntArrayWritable;
import com.github.aldurd392.bigdatacontest.datatypes.NeighbourhoodMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Writable;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
/**
* BigDataContest - com.github.aldurd392.bigdatacontest.utils
* Created by aldur on 10/05/15.
*/
public class Utils {
private static final String resultFileName = "_FOUND";
private static final String pathResultFile = "result";
private static final String successFileName = "_SUCCESS";
private static final double smoothing_factor = 5;
/**
* Given the neighbourhood map, calculate the density of the subgraph.
* @param neighbourhood our subgraph representation
* @return null if the supplied subgraph didn't meet density requirements,
* otherwise the densest subgraph found that still meets the requirements.
*/
public static IntArrayWritable density(NeighbourhoodMap neighbourhood) {
final int neighbourhood_size = neighbourhood.size();
final HashSet<IntWritable> neighbourhood_nodes = new HashSet<>(neighbourhood_size);
for (Writable writable_node: neighbourhood.keySet()) {
IntWritable node = (IntWritable) writable_node;
neighbourhood_nodes.add(node);
}
/*
* We have the number of nodes in the subgraph.
* Let's count the number of edges too.
*/
int edges_count = 0;
for (Writable writable_neighbours : neighbourhood.values()) {
IntArrayWritable neighbours = (IntArrayWritable) writable_neighbours;
for (Writable writable_neighbour : neighbours.get()) {
IntWritable neighbour = (IntWritable) writable_neighbour;
if (neighbourhood_nodes.contains(neighbour)) {
edges_count++;
}
}
}
// We counted each edge twice, so better divide by two here.
edges_count = edges_count / 2;
final double rho = Main.inputs.getRho();
if (edges_count / neighbourhood_size >= rho) {
/*
* Once we know that the subgraph we're dealing with meets our density requirements,
* we check if it's a clique (by comparing the number of edges and the number of nodes).
* In that case we can shrink its size until it's minimal (our goal).
*/
if (edges_count == ((neighbourhood_size - 1) * neighbourhood_size) / 2) {
double diff = ((double) edges_count / neighbourhood_size) - rho;
System.out.println("Filtro di fattore: " + diff);
Iterator<IntWritable> neighbourhood_nodes_iterator = neighbourhood_nodes.iterator();
for (; diff >= 0.5; diff -= 0.5) {
neighbourhood_nodes_iterator.next();
neighbourhood_nodes_iterator.remove();
}
}
IntWritable[] nodes_array = neighbourhood_nodes.toArray(new IntWritable[neighbourhood_nodes.size()]);
final IntArrayWritable densestSubgraph = new IntArrayWritable();
densestSubgraph.set(nodes_array);
return densestSubgraph;
}
/* If the subgraph didn't meet required density value, we return null. */
return null;
}
public static void writeResultOnFile(IntArrayWritable result) throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Path outFile = new Path(pathResultFile + "/" + resultFileName);
FSDataOutputStream out;
if (!fs.exists(outFile)) {
out = fs.create(outFile);
out.close();
}
out = fs.create(new Path(pathResultFile + "/" + result.hashCode()));
out.writeChars(result.toString());
out.close();
}
public static boolean resultFound() throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Path resultFile = new Path(pathResultFile + "/" + resultFileName);
return fs.exists(resultFile);
}
public static boolean previousResults(String currentOuputDirectory) throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Writable w = new IntArrayWritable();
FileStatus[] statuses;
try {
statuses = fs.listStatus(new Path(currentOuputDirectory));
} catch (java.io.FileNotFoundException e) {
// The first time we don't have previous result!
return true;
}
for (FileStatus status : statuses) {
if (status.getPath().getName().equals(successFileName)) {
continue;
}
SequenceFile.Reader reader = new SequenceFile.Reader(fs, status.getPath(), conf);
if (reader.next(w)) {
reader.close();
return true;
}
reader.close();
}
return false;
}
/**
* This function selects a proper euristicFactor given the desired rho
* @param rho the desired density.
* @return an euristic factor that is inversely proportional to rho.
*/
public static double euristicFactorFunction(double rho) {
return Math.pow(rho, -(Math.log10(rho) / smoothing_factor));
}
}
| BigDataContest/src/main/java/com/github/aldurd392/bigdatacontest/utils/Utils.java | package com.github.aldurd392.bigdatacontest.utils;
import com.github.aldurd392.bigdatacontest.Main;
import com.github.aldurd392.bigdatacontest.datatypes.IntArrayWritable;
import com.github.aldurd392.bigdatacontest.datatypes.NeighbourhoodMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Writable;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
/**
* BigDataContest - com.github.aldurd392.bigdatacontest.utils
* Created by aldur on 10/05/15.
*/
public class Utils {
private static final String resultFileName = "_FOUND";
private static final String pathResultFile = "result";
private static final String successFileName = "_SUCCESS";
private static final double smoothing_factor = 5;
public static IntArrayWritable density(NeighbourhoodMap neighbourhood) {
HashSet<IntWritable> nodes_set = new HashSet<>();
for (Writable w : neighbourhood.keySet()) {
IntWritable i = (IntWritable) w;
nodes_set.add(i);
}
int num_nodes = nodes_set.size();
int i = 0;
for (Writable w : neighbourhood.values()) {
IntArrayWritable array_writable = (IntArrayWritable) w;
for (Writable w_node : array_writable.get()) {
IntWritable node = (IntWritable) w_node;
if (nodes_set.contains(node)) {
i++;
}
}
}
// Final edges count.
i = i/2;
if(i/num_nodes >= Main.inputs.getRho()){
IntArrayWritable intArrayWritable = new IntArrayWritable();
// Check if the subgraph founded is a clique.
if (i == ((num_nodes - 1)*num_nodes)/2){
double diff = i/num_nodes - Main.inputs.getRho();
System.out.println("Filtro di fattore: " +diff);
Iterator<IntWritable> it = nodes_set.iterator();
for(; diff >= 0.5; diff-=0.5){
it.next();
it.remove();
}
}
IntWritable[] nodes_array = nodes_set.toArray(new IntWritable[nodes_set.size()]);
intArrayWritable.set(nodes_array);
return intArrayWritable;
}
return null;
}
public static void writeResultOnFile(IntArrayWritable result) throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Path outFile = new Path(pathResultFile + "/" + resultFileName);
FSDataOutputStream out;
if (!fs.exists(outFile)) {
out = fs.create(outFile);
out.close();
}
out = fs.create(new Path(pathResultFile + "/" + result.hashCode()));
out.writeChars(result.toString());
out.close();
}
public static boolean resultFound() throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Path resultFile = new Path(pathResultFile + "/" + resultFileName);
return fs.exists(resultFile);
}
public static boolean previousResults(String currentOuputDirectory) throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Writable w = new IntArrayWritable();
FileStatus[] statuses;
try {
statuses = fs.listStatus(new Path(currentOuputDirectory));
} catch (java.io.FileNotFoundException e) {
// The first time we don't have previous result!
return true;
}
for (FileStatus status : statuses) {
if (status.getPath().getName().equals(successFileName)) {
continue;
}
SequenceFile.Reader reader = new SequenceFile.Reader(fs, status.getPath(), conf);
if (reader.next(w)) {
reader.close();
return true;
}
reader.close();
}
return false;
}
public static double euristicFactorFunction(double rho) {
return Math.pow(rho, -(Math.log10(rho) / smoothing_factor));
}
}
| refactor Utils
| BigDataContest/src/main/java/com/github/aldurd392/bigdatacontest/utils/Utils.java | refactor Utils | <ide><path>igDataContest/src/main/java/com/github/aldurd392/bigdatacontest/utils/Utils.java
<ide>
<ide> private static final double smoothing_factor = 5;
<ide>
<add> /**
<add> * Given the neighbourhood map, calculate the density of the subgraph.
<add> * @param neighbourhood our subgraph representation
<add> * @return null if the supplied subgraph didn't meet density requirements,
<add> * otherwise the densest subgraph found that still meets the requirements.
<add> */
<ide> public static IntArrayWritable density(NeighbourhoodMap neighbourhood) {
<del> HashSet<IntWritable> nodes_set = new HashSet<>();
<del> for (Writable w : neighbourhood.keySet()) {
<del> IntWritable i = (IntWritable) w;
<del> nodes_set.add(i);
<add> final int neighbourhood_size = neighbourhood.size();
<add>
<add> final HashSet<IntWritable> neighbourhood_nodes = new HashSet<>(neighbourhood_size);
<add> for (Writable writable_node: neighbourhood.keySet()) {
<add> IntWritable node = (IntWritable) writable_node;
<add> neighbourhood_nodes.add(node);
<ide> }
<del>
<del> int num_nodes = nodes_set.size();
<ide>
<del> int i = 0;
<del> for (Writable w : neighbourhood.values()) {
<del> IntArrayWritable array_writable = (IntArrayWritable) w;
<del> for (Writable w_node : array_writable.get()) {
<del> IntWritable node = (IntWritable) w_node;
<del> if (nodes_set.contains(node)) {
<del> i++;
<add> /*
<add> * We have the number of nodes in the subgraph.
<add> * Let's count the number of edges too.
<add> */
<add> int edges_count = 0;
<add> for (Writable writable_neighbours : neighbourhood.values()) {
<add> IntArrayWritable neighbours = (IntArrayWritable) writable_neighbours;
<add>
<add> for (Writable writable_neighbour : neighbours.get()) {
<add> IntWritable neighbour = (IntWritable) writable_neighbour;
<add>
<add> if (neighbourhood_nodes.contains(neighbour)) {
<add> edges_count++;
<ide> }
<ide> }
<ide> }
<del>
<del> // Final edges count.
<del> i = i/2;
<del>
<del> if(i/num_nodes >= Main.inputs.getRho()){
<del>
<del> IntArrayWritable intArrayWritable = new IntArrayWritable();
<del>
<del> // Check if the subgraph founded is a clique.
<del> if (i == ((num_nodes - 1)*num_nodes)/2){
<del> double diff = i/num_nodes - Main.inputs.getRho();
<del> System.out.println("Filtro di fattore: " +diff);
<del>
<del> Iterator<IntWritable> it = nodes_set.iterator();
<del> for(; diff >= 0.5; diff-=0.5){
<del> it.next();
<del> it.remove();
<del> }
<add> // We counted each edge twice, so better divide by two here.
<add> edges_count = edges_count / 2;
<add>
<add> final double rho = Main.inputs.getRho();
<add> if (edges_count / neighbourhood_size >= rho) {
<add> /*
<add> * Once we know that the subgraph we're dealing with meets our density requirements,
<add> * we check if it's a clique (by comparing the number of edges and the number of nodes).
<add> * In that case we can shrink its size until it's minimal (our goal).
<add> */
<add> if (edges_count == ((neighbourhood_size - 1) * neighbourhood_size) / 2) {
<add> double diff = ((double) edges_count / neighbourhood_size) - rho;
<add> System.out.println("Filtro di fattore: " + diff);
<add>
<add> Iterator<IntWritable> neighbourhood_nodes_iterator = neighbourhood_nodes.iterator();
<add> for (; diff >= 0.5; diff -= 0.5) {
<add> neighbourhood_nodes_iterator.next();
<add> neighbourhood_nodes_iterator.remove();
<add> }
<ide> }
<del>
<del> IntWritable[] nodes_array = nodes_set.toArray(new IntWritable[nodes_set.size()]);
<del> intArrayWritable.set(nodes_array);
<del> return intArrayWritable;
<add>
<add> IntWritable[] nodes_array = neighbourhood_nodes.toArray(new IntWritable[neighbourhood_nodes.size()]);
<add> final IntArrayWritable densestSubgraph = new IntArrayWritable();
<add> densestSubgraph.set(nodes_array);
<add>
<add> return densestSubgraph;
<ide> }
<del>
<add>
<add> /* If the subgraph didn't meet required density value, we return null. */
<ide> return null;
<ide> }
<ide>
<ide> return false;
<ide> }
<ide>
<add> /**
<add> * This function selects a proper euristicFactor given the desired rho
<add> * @param rho the desired density.
<add> * @return an euristic factor that is inversely proportional to rho.
<add> */
<ide> public static double euristicFactorFunction(double rho) {
<ide> return Math.pow(rho, -(Math.log10(rho) / smoothing_factor));
<ide> } |
|
Java | apache-2.0 | a7f2d8e9d63eefc97d0edf27018aaa739fb94be6 | 0 | RedRoma/banana-service,RedRoma/banana-service,RedRoma/aroma-service,AromaTech/banana-service,RedRoma/aroma-service,AromaTech/banana-service | /*
* Copyright 2015 Aroma Tech.
*
* 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 tech.aroma.service.server;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provides;
import java.net.SocketException;
import javax.inject.Singleton;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.aroma.data.cassandra.ModuleCassandraDataRepositories;
import tech.aroma.data.cassandra.ModuleCassandraDevCluster;
import tech.aroma.service.ModuleAromaService;
import tech.aroma.service.operations.ModuleAromaServiceOperations;
import tech.aroma.service.operations.encryption.ModuleEncryptionMaterialsDev;
import tech.aroma.thrift.authentication.service.AuthenticationService;
import tech.aroma.thrift.service.AromaService;
import tech.aroma.thrift.service.AromaServiceConstants;
import tech.aroma.thrift.services.Clients;
import tech.sirwellington.alchemy.annotations.access.Internal;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* This Main Class runs the Aroma Service on a Server Socket.
*
* @author SirWellington
*/
@Internal
public final class TcpServer
{
private final static Logger LOG = LoggerFactory.getLogger(TcpServer.class);
private static final int PORT = AromaServiceConstants.SERVICE_PORT;
public static void main(String[] args) throws TTransportException, SocketException
{
Injector injector = Guice.createInjector(new ModuleAromaServiceOperations(),
new ModuleAromaService(),
new ModuleCassandraDataRepositories(),
new ModuleCassandraDevCluster(),
new ModuleEncryptionMaterialsDev(),
new RestOfDependencies());
AromaService.Iface aromaService = injector.getInstance(AromaService.Iface.class);
AromaService.Processor processor = new AromaService.Processor<>(aromaService);
TServerSocket socket = new TServerSocket(PORT);
socket.getServerSocket().setSoTimeout((int) SECONDS.toMillis(30));
TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(socket)
.protocolFactory(new TBinaryProtocol.Factory())
.processor(processor)
.requestTimeout(60)
.requestTimeoutUnit(SECONDS)
.minWorkerThreads(5)
.maxWorkerThreads(100);
LOG.info("Starting Aroma Service at port {}", PORT);
TThreadPoolServer server = new TThreadPoolServer(serverArgs);
server.serve();
server.stop();
}
private static class RestOfDependencies extends AbstractModule
{
@Override
protected void configure()
{
}
@Singleton
@Provides
AuthenticationService.Iface provideAuthenticationService()
{
try
{
return Clients.newPerRequestAuthenticationServiceClient();
}
catch (Exception ex)
{
LOG.error("Failed to create Authentication Service", ex);
throw new RuntimeException(ex);
}
}
}
}
| src/main/java/tech/aroma/service/server/TcpServer.java | /*
* Copyright 2015 Aroma Tech.
*
* 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 tech.aroma.service.server;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provides;
import java.net.SocketException;
import javax.inject.Singleton;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.aroma.data.cassandra.ModuleCassandraDataRepositories;
import tech.aroma.data.cassandra.ModuleCassandraDevCluster;
import tech.aroma.service.ModuleAromaService;
import tech.aroma.service.operations.ModuleAromaServiceOperations;
import tech.aroma.service.operations.encryption.ModuleEncryptionMaterialsDev;
import tech.aroma.thrift.authentication.service.AuthenticationService;
import tech.aroma.thrift.service.AromaService;
import tech.aroma.thrift.service.AromaServiceConstants;
import tech.aroma.thrift.services.Clients;
import tech.sirwellington.alchemy.annotations.access.Internal;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* This Main Class runs the Aroma Service on a Server Socket.
*
* @author SirWellington
*/
@Internal
public final class TcpServer
{
private final static Logger LOG = LoggerFactory.getLogger(TcpServer.class);
private static final int PORT = AromaServiceConstants.SERVICE_PORT;
public static void main(String[] args) throws TTransportException, SocketException
{
Injector injector = Guice.createInjector(new ModuleAromaServiceOperations(),
new ModuleAromaService(),
new ModuleCassandraDataRepositories(),
new ModuleCassandraDevCluster(),
new ModuleEncryptionMaterialsDev(),
new RestOfDependencies());
AromaService.Iface bananaService = injector.getInstance(AromaService.Iface.class);
AromaService.Processor processor = new AromaService.Processor<>(bananaService);
TServerSocket socket = new TServerSocket(PORT);
socket.getServerSocket().setSoTimeout((int) SECONDS.toMillis(30));
TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(socket)
.protocolFactory(new TBinaryProtocol.Factory())
.processor(processor)
.requestTimeout(60)
.requestTimeoutUnit(SECONDS)
.minWorkerThreads(5)
.maxWorkerThreads(100);
LOG.info("Starting Aroma Service at port {}", PORT);
TThreadPoolServer server = new TThreadPoolServer(serverArgs);
server.serve();
server.stop();
}
private static class RestOfDependencies extends AbstractModule
{
@Override
protected void configure()
{
}
@Singleton
@Provides
AuthenticationService.Iface provideAuthenticationService()
{
try
{
return Clients.newPerRequestAuthenticationServiceClient();
}
catch (Exception ex)
{
LOG.error("Failed to create Authentication Service", ex);
throw new RuntimeException(ex);
}
}
}
}
| TcpServer: Updating variable name | src/main/java/tech/aroma/service/server/TcpServer.java | TcpServer: Updating variable name | <ide><path>rc/main/java/tech/aroma/service/server/TcpServer.java
<ide> new ModuleEncryptionMaterialsDev(),
<ide> new RestOfDependencies());
<ide>
<del> AromaService.Iface bananaService = injector.getInstance(AromaService.Iface.class);
<del> AromaService.Processor processor = new AromaService.Processor<>(bananaService);
<add> AromaService.Iface aromaService = injector.getInstance(AromaService.Iface.class);
<add> AromaService.Processor processor = new AromaService.Processor<>(aromaService);
<ide>
<ide> TServerSocket socket = new TServerSocket(PORT);
<ide> socket.getServerSocket().setSoTimeout((int) SECONDS.toMillis(30)); |
|
JavaScript | mit | 9944e631d74cfe02afb372f981453195c4059376 | 0 | NikolaySuslov/LivelyKernel,pascience/LivelyKernel,NikolaySuslov/LivelyKernel,pascience/LivelyKernel,NikolaySuslov/LivelyKernel,pascience/LivelyKernel,LivelyKernel/LivelyKernel,LivelyKernel/LivelyKernel,LivelyKernel/LivelyKernel | module('lively.morphic.Widgets').requires('lively.morphic.Core', 'lively.morphic.Events', 'lively.morphic.TextCore', 'lively.morphic.Styles').toRun(function() {
lively.morphic.Morph.subclass('lively.morphic.Button',
'settings', {
isButton: true,
normalColor: Color.rgbHex('#DDDDDD'),
toggleColor: Color.rgb(171,215,248),
disabledColor: Color.rgbHex('#DDDDDD'),
normalTextColor: Color.black,
disabledTextColor: Color.rgbHex('#999999'),
style: {
enableGrabbing: false,
enableDropping: false,
borderColor: Color.neutral.lightGray,
borderWidth: 1,
borderRadius: 5,
padding: Rectangle.inset(0,3),
label: {
borderWidth: 0,
fill: null,
padding: Rectangle.inset(0,3),
fontSize: 10,
align: 'center',
fixedWidth: true,
fixedHeight: true,
textColor: Color.black,
clipMode: 'hidden',
emphasize: {textShadow: {offset: pt(0,1), color: Color.white}},
allowInput: false
}
}
},
'initializing', {
initialize: function($super, bounds, labelString) {
$super(this.defaultShape());
if (bounds) this.setBounds(bounds);
this.value = false;
this.toggle = false;
this.isActive = true;
this.changeAppearanceFor(false, false);
this.ensureLabel(labelString);
this.setAppearanceStylingMode(true);
this.setBorderStylingMode(true);
},
ensureLabel: function(labelString) {
if (!this.label) {
this.label = new lively.morphic.Text(this.getExtent().extentAsRectangle(), labelString);
} else {
this.label.setBounds(this.getExtent().extentAsRectangle());
this.label.textString = labelString;
}
if (this.label.owner !== this) {
this.addMorph(this.label);
}
this.label.beLabel(this.style.label);
this.label.setTextStylingMode(true);
this.label.disableEvents();
return this.label;
},
},
'accessing', {
setLabel: function(label) {
this.label.setTextString(label);
this.label.setExtent(this.getExtent());
this.label.applyStyle(this.style.label);
return this;
},
getLabel: function(label) { return this.label.textString },
setActive: function(bool) {
this.isActive = bool;
this.updateAppearance();
},
setValue: function(bool) {
this.value = bool;
// buttons should fire on mouse up
if (!bool || this.toggle) lively.bindings.signal(this, 'fire', bool);
},
setExtent: function($super, extent) {
// FIXME use layout! spaceFill!
$super(extent);
this.label && this.label.setExtent(extent)
},
setPadding: function(padding) { this.label && this.label.setPadding(padding); },
setToggle: function(optBool) {
this.toggle = (optBool === undefined)? true : optBool;
return this.toggle
}
},
'styling', {
updateAppearance: function(){
this.changeAppearanceFor(this.isPressed, this.value);
},
changeAppearanceFor: function(pressed, toggled) {
if (this.isActive) {
this.removeStyleClassName('disabled');
var isToggled = toggled || this.value;
if (isToggled) {
this.addStyleClassName('toggled');
} else {
this.removeStyleClassName('toggled');
}
if (pressed) {
this.addStyleClassName('pressed');
} else {
this.removeStyleClassName('pressed');
}
if (this.style && this.style.label && this.style.label.padding) {
var labelPadding = pressed ? this.style.label.padding.withY(this.style.label.padding.y+1):this.style.label.padding;
this.setPadding(labelPadding);
}
if (this.label)
this.label.setExtent(this.getExtent())
} else {
this.addStyleClassName('disabled');
this.removeStyleClassName('toggled');
this.removeStyleClassName('pressed');
}
},
applyStyle: function($super, spec) {
if (spec.label && this.label) {
this.label.applyStyle(spec.label);
}
return $super(spec);
},
generateFillWith: function(color, shade, upperCenter, lowerCenter, bottomShade){
return new lively.morphic.LinearGradient(
[{offset: 0, color: color.mixedWith(shade, 0.2)},
{offset: upperCenter || 0.3, color: color},
{offset: lowerCenter || 0.7, color: color},
{offset: 1, color: color.mixedWith(bottomShade|| shade, 0.2)}],
"NorthSouth");
}
},
'events', {
isValidEvent: function(evt) {
if (!this.isActive) return false;
if (evt.isLeftMouseButtonDown() && !evt.isCommandKey()) return true;
if (evt.isKeyboardEvent && evt.keyCode === Event.KEY_RETURN) return true;
return false;
},
onMouseOut: function (evt) {
this.isPressed && this.changeAppearanceFor(false);
},
onMouseOver: function (evt) {
if (evt.isLeftMouseButtonDown()) {
this.isPressed && this.changeAppearanceFor(true);
} else {
this.isPressed = false;
}
},
onMouseDown: function (evt) {
if (this.isValidEvent(evt) && this.isActive) {
this.activate();
}
return false;
},
onMouseUp: function(evt) {
if (this.isValidEvent(evt) && this.isPressed) {
this.deactivate();
}
return false;
},
onKeyDown: function(evt) {
if (this.isValidEvent(evt) && this.isActive) {
this.activate();
}
return false;
},
onKeyUp: function(evt) {
if (this.isValidEvent(evt) && this.isPressed) {
this.deactivate();
}
return false;
},
simulateButtonClick: function() {
var world = this.world() || lively.morphic.World.current(),
hand = world.firstHand();
function createEvent() {
return {
isLeftMouseButtonDown: Functions.True,
isRightMouseButtonDown: Functions.False,
isCommandKey: Functions.False,
isAltDown: Functions.False,
world: world,
hand: hand,
getPosition: function() { return hand.getPosition() }
}
}
this.onMouseDown(createEvent());
this.onMouseUp(createEvent());
},
activate: function() {
this.isPressed = true;
this.changeAppearanceFor(true);
},
deactivate: function() {
var newValue = this.toggle ? !this.value : false;
this.setValue(newValue);
this.changeAppearanceFor(false);
this.isPressed = false;
}
},
'menu', {
morphMenuItems: function($super) {
var self = this, items = $super();
items.push([
'Set label', function(evt) {
$world.prompt('Set label', function(input) {
if (input !== null)
self.setLabel(input || '');
}, self.getLabel());
}])
return items;
}
});
lively.morphic.Button.subclass('lively.morphic.ImageButton',
'initializing', {
initialize: function($super, bounds, url) {
//if (bounds) this.setBounds(bounds);
$super(bounds, '');
this.image = new lively.morphic.Image(this.getExtent().extentAsRectangle(), url, true);
this.addMorph(this.image);
this.image.ignoreEvents();
this.image.disableHalos();
},
},
'accessing', {
setImage: function(url) {
this.image.setImageURL(url);
return this;
},
getImage: function() { return this.image.getImageURL() },
setImageOffset: function(padding) { this.image && this.image.setPosition(padding) },
},
'menu', {
morphMenuItems: function($super) {
var self = this, items = $super();
items.push([
'Set image', function(evt) {
$world.prompt('Set image URL', function(input) {
if (input !== null)
self.setImage(input || '');
}, self.getImage());
}])
return items;
},
});
lively.morphic.ImageButton.subclass('lively.morphic.ImageOptionButton',
'buttonstuff', {
setValue: function(bool) {
this.value = bool;
this.changeAppearanceFor(bool);
},
onMouseDown: function (evt) {
if (this.isActive && evt.isLeftMouseButtonDown()
&& !this.value && !evt.isCommandKey()) {
this.changeAppearanceFor(true);
}
},
onMouseUp: function(evt) {
if (this.isActive && evt.isLeftMouseButtonDown()
&& !evt.isCommandKey() && !this.value && this.otherButtons) {
this.setValue(true);
this.otherButtons.each(function(btn){btn.setValue(false);});
return false;
}
return false;
},
setOtherButtons: function(morphs) {
var otherButtons = [];
if (morphs.first()) { // if the list is empty, apply the empty list
if (morphs.first().toUpperCase) { // if the list contains strings, get the morphs first
var t = this;
morphs.each(function(btn){
var a = t.get(btn);
a && a.setOtherButtons && otherButtons.push(a);
});
} else {
otherButtons = morphs;
}
}
this.otherButtons = otherButtons;
},
});
lively.morphic.Morph.subclass('lively.morphic.Image',
'initializing', {
initialize: function($super, bounds, url, useNativeExtent) {
var imageShape = this.defaultShape(bounds.extent().extentAsRectangle(), url);
$super(imageShape);
this.setPosition(bounds.topLeft());
this.setImageURL(url, useNativeExtent);
},
defaultShape: function(bounds, url) {
url = url || '';
return new lively.morphic.Shapes.Image(bounds, url);
}
},
'accessing', {
setImageURL: function(url, useNativeExtent) {
if (!url) return null;
if (useNativeExtent) {
connect(this.shape, 'isLoaded', this, 'setNativeExtent',
{removeAfterUpdate: true});
} else {
connect(this.shape, 'isLoaded', this, 'setExtent',
{removeAfterUpdate: true, converter: function() {
return this.targetObj.getExtent(); }});
}
return this.shape.setImageURL(url);
},
getImageURL: function() { return this.shape.getImageURL() },
getNativeExtent: function() { return this.shape.getNativeExtent() },
setNativeExtent: function() {
var ext = this.getNativeExtent();
// FIXME magic numbers
if (ext.x < 10) ext.x = 10;
if (ext.y < 10) ext.y = 10;
return this.setExtent(ext);
},
},
'halos', {
getHaloClasses: function($super) {
return $super().concat([lively.morphic.SetImageURLHalo]);
},
},
'menu', {
morphMenuItems: function($super) {
var items = $super();
items.push(['set to original extent', this.setNativeExtent.bind(this)]);
items.push(['inline image data', this.convertToBase64.bind(this)]);
return items;
},
},
'keyboard events', {
onKeyPress: function($super, evt) {
// The extent of iages should can be changed by using the + and - key
var key = evt.getKeyChar();
switch (key) {
case "-": {
this.setExtent(this.getExtent().scaleBy(0.8))
return true;
}
case "+": {
this.setExtent(this.getExtent().scaleBy(1.1))
return true;
}
}
return $super(evt)
}
},
'inline image', {
convertToBase64: function() {
var urlString = this.getImageURL(),
type = urlString.substring(urlString.lastIndexOf('.') + 1, urlString.length);
if (type == 'jpg') type = 'jpeg';
if (!['gif', 'jpeg', 'png', 'tiff'].include(type)) type = 'gif';
if (false && Global.btoa) {
// FIXME actually this should work but the encoding result is wrong...
// maybe the binary image content is not loaded correctly because of encoding?
urlString = URL.makeProxied(urlString);
var content = new WebResource(urlString).get(null, 'image/' + type).content,
fixedContent = content.replace(/./g, function(m) {
return String.fromCharCode(m.charCodeAt(0) & 0xff);
}),
encoded = btoa(fixedContent);
this.setImageURL('data:image/' + type + ';base64,' + encoded);
} else {
var image = this;
if (!urlString.startsWith('http')) {
urlString = URL.source.getDirectory().withFilename(urlString).toString();
}
require('lively.ide.CommandLineInterface').toRun(function() { // FIXME
var cmd = 'curl --silent "' + urlString + '" | openssl base64'
lively.ide.CommandLineInterface.exec(cmd, function(cmd) {
image.setImageURL('data:image/' + type + ';base64,' + cmd.getStdout());
});
});
}
}
});
Object.extend(lively.morphic.Image, {
fromURL: function(url, optBounds) {
var bounds = optBounds || new Rectangle(0,0, 100, 100);
return new lively.morphic.Image(bounds, url, optBounds == undefined)
},
});
lively.morphic.Morph.subclass('lively.morphic.CheckBox',
'properties', {
connections: {
setChecked: {}
}
},
'initializing', {
initialize: function($super, isChecked) {
$super(this.defaultShape());
this.setChecked(isChecked);
},
defaultShape: function() {
// FIXME: render context dependent
var node = XHTMLNS.create('input');
node.type = 'checkbox';
return new lively.morphic.Shapes.External(node);
}
},
'accessing', {
setChecked: function(bool) {
// FIXME: render context dependent
this.checked = bool;
this.renderContext().shapeNode.checked = bool;
return bool;
}
},
'testing', {
isChecked: function() {
return this.checked;
},
},
'event handling', {
onClick: function(evt) {
// for halos/menus
if (evt.isCommandKey() || !evt.isLeftMouseButtonDown()) {
evt.stop()
return true;
}
// we do it ourselves
this.setChecked(!this.isChecked());
return true;
},
},
'serialization', {
prepareForNewRenderContext: function ($super, renderCtx) {
$super(renderCtx);
// FIXME what about connections to this.isChecked?
// they would be updated here...
this.setChecked(this.isChecked());
}
});
lively.morphic.Morph.subclass('lively.morphic.PasswordInput',
'initializing', {
initialize: function($super, isChecked) {
$super(this.createShape());
},
createShape: function() {
var node = XHTMLNS.create('input');
node.type = 'password';
node.className = 'visibleSelection';
return new lively.morphic.Shapes.External(node);
},
},
'accessing', {
set value(string) {
// FIXME move to lively.morphic.HTML
var inputNode = this.renderContext().shapeNode;
if (inputNode) {
inputNode.value = string;
}
lively.bindings.signal(this, 'value', string);
return string;
},
get value() {
// FIXME move to lively.morphic.HTML
var inputNode = this.renderContext().shapeNode;
return inputNode ? inputNode.value : '';
}
});
lively.morphic.Box.subclass('lively.morphic.ProgressBar',
'settings', {
style: {
fill: Color.white, borderColor: Color.rgb(170,170,170), borderWidth: 1, borderRadius: 5,
adjustForNewBounds: true,
clipMode: 'hidden', // so that sharp borders of progress do not stick out
},
progressStyle: {
scaleHorizontal: true,
scaleVertical: true,
borderColor: Color.rgb(170,170,170),
borderWidth: 1,
borderRadius: "5px 0px 0px 5px",
fill: new lively.morphic.LinearGradient([
{offset: 0, color: Color.rgb(223,223,223)},
{offset: 1, color: Color.rgb(204,204,204)}]),
clipMode: 'hidden', // for label
},
labelStyle: {
fontSize: 11,
fixedWidth: true,
fixedHeight: false,
clipMode: 'hidden',
align: 'center',
},
},
'initializing', {
initialize: function($super, bounds) {
bounds = bounds || new Rectangle(0,0, 200,22);
$super(bounds);
this.createProgressMorph();
this.createLabel();
this.value = 0;
},
createProgressMorph: function() {
var bounds = this.innerBounds();
this.progressMorph = this.addMorph(lively.morphic.Morph.makeRectangle(bounds.withWidth(0)));
this.progressMorph.applyStyle(this.progressStyle);
this.progressMorph.ignoreEvents();
},
createLabel: function() {
this.labelBlack = lively.morphic.Text.makeLabel('', Object.extend({textColor: Color.black, centeredVertical: true, scaleHorizontal: true}, this.labelStyle));
this.labelWhite = lively.morphic.Text.makeLabel('', Object.extend({textColor: Color.white}, this.labelStyle));
this.addMorphBack(this.labelBlack);
this.progressMorph.addMorph(this.labelWhite);
this.labelBlack.ignoreEvents();
this.labelWhite.ignoreEvents();
connect(this.labelBlack, 'extent', this.labelWhite, 'setExtent')
connect(this.labelBlack, 'position', this.labelWhite, 'setPosition')
this.labelBlack.setBounds(this.innerBounds());
this.labelBlack.fit();
},
},
'accessing', {
getValue: function() { return this.value },
setValue: function(v) { this.updateBar(v); return this.value = v },
setLabel: function(string) {
this.labelBlack.textString = string;
this.labelWhite.textString = string;
},
},
'updating', {
updateBar: function(value) {
var maxExt = this.getExtent();
this.progressMorph.setExtent(pt(Math.floor(maxExt.x * value), maxExt.y));
}
});
lively.morphic.Text.subclass('lively.morphic.FrameRateMorph', {
initialize: function($super, shape) {
// Steps at maximum speed, and gathers stats on ticks per sec and max latency
$super(shape);
this.setTextString('FrameRateMorph')
this.reset(new Date());
},
reset: function(date) {
this.lastTick = date.getSeconds();
this.lastMS = date.getTime();
this.stepsSinceTick = 0;
this.maxLatency = 0;
},
nextStep: function() {
var date = new Date();
this.stepsSinceTick++;
var nowMS = date.getTime();
this.maxLatency = Math.max(this.maxLatency, nowMS - this.lastMS);
this.lastMS = nowMS;
var nowTick = date.getSeconds();
if (nowTick != this.lastTick) {
this.lastTick = nowTick;
var ms = (1000 / Math.max(this. stepsSinceTick,1)).roundTo(1);
this.setTextString(this.stepsSinceTick + " frames/sec (" + ms + "ms avg),\nmax latency " + this.maxLatency + " ms.");
this.reset(date);
}
},
startSteppingScripts: function() { this.startStepping(1, 'nextStep'); }
});
lively.morphic.Box.subclass('lively.morphic.Menu',
'settings', {
style: {
fill: Color.gray.lighter(3),
borderColor: Color.gray.lighter(),
borderWidth: 1,
borderStyle: 'outset',
borderRadius: 4,
opacity: 0.95
},
isEpiMorph: true,
isMenu: true,
removeOnMouseOut: false
},
'initializing', {
initialize: function($super, title, items) {
$super(new Rectangle(0,0, 120, 10));
this.items = [];
this.itemMorphs = [];
if (title) this.setupTitle(title);
if (items) this.addItems(items);
},
setupTitle: function(title) {
if (this.title) this.title.remove()
this.title = new lively.morphic.Text(
new Rectangle(0,0, this.getExtent().x, 25),
String(title).truncate(26)).beLabel({
borderRadius: this.getBorderRadius(),
borderColor: this.getBorderColor(),
borderWidth: 0,
fill: new lively.morphic.LinearGradient([{offset: 0, color: Color.white},
{offset: 1, color: Color.gray}]),
textColor: CrayonColors.lead,
clipMode: 'hidden',
fixedWidth: false,
fixedHeight: true,
borderColor: Color.gray.lighter(2),
borderWidth: 1,
borderStyle: 'outset',
borderRadius: 4,
padding: Rectangle.inset(5,5,5,5),
emphasize: {fontWeight: 'bold'}
});
this.title.align(this.title.bounds().bottomLeft(), pt(0,0));
this.addMorph(this.title);
this.fitToItems()
}
},
'mouse events', {
onMouseOut: function() {
if (this.removeOnMouseOut) {
this.remove()
};
return this.removeOnMouseOut;
}
},
'opening', {
openIn: function(parentMorph, pos, remainOnScreen, captionIfAny) {
this.setPosition(pos || pt(0,0));
if (captionIfAny) { this.setupTitle(captionIfAny) };
var owner = parentMorph || lively.morphic.World.current();
this.remainOnScreen = remainOnScreen;
if (!remainOnScreen) {
if (owner.currentMenu) { owner.currentMenu.remove() };
owner.currentMenu = this;
} else {
this.isEpiMorph = false;
}
owner.addMorph(this);
this.fitToItems.bind(this).delay(0);
this.offsetForWorld(pos);
// delayed because of fitToItems
// currently this is deactivated because the initial bounds are correct
// for our current usage
// this.offsetForWorld.curry(pos).bind(this).delay(0);
return this;
},
},
'removing', {
remove: function($super) {
var w = this.world();
if (w && w.currentMenu === this) w.currentMenu = null;
$super();
},
},
'item management', {
removeAllItems: function() {
this.items = [];
this.itemMorphs = [];
this.submorphs.without(this.title).invoke('remove');
},
createMenuItems: function(items) {
function createItem(string, value, idx, callback, callback2, isSubMenu) {
return {
isMenuItem: true,
isListItem: true,
isSubMenu: isSubMenu,
string: string,
value: value,
idx: idx,
onClickCallback: callback,
onMouseOverCallback: callback2
}
}
var result = [], self = this;
items.forEach(function(item, i) {
if (item.isMenuItem) { item.idx = i; result.push(item); return };
// item = [name, callback]
if (Object.isArray(item) && Object.isFunction(item[1])) {
result.push(createItem(String(item[0]), item[0], i, item[1]))
return;
}
// item = [name, target, methodName, args...]
if (Object.isArray(item) && Object.isString(item[2])) {
result.push(createItem(String(item[0]), item[0], i, function(evt) {
var receiver = item[1],
method = receiver[item[2]],
args = item.slice(3);
method.apply(receiver, args) }))
return;
}
// sub menu item = [name, [sub elements]]
if (Object.isArray(item) && Object.isArray(item[1])) {
var name = item[0], subItems = item[1];
result.push(createItem(name, name, i, null, function(evt) {
self.openSubMenu(evt, name, subItems) }, true));
return;
}
// [name, {getItems: function() { return submenu items }}]
if (Object.isArray(item) && Object.isObject(item[1])) {
var name = item[0], spec = item[1];
if (Object.isFunction(spec.condition)) {
if (!spec.condition()) return;
}
if (Object.isFunction(spec.getItems)) {
result.push(createItem(name, name, i, null, function(evt) {
self.openSubMenu(evt, name, spec.getItems()) }, true));
}
return;
}
// item = "some string"
result.push(createItem(String(item), item, i, function() { alert('clicked ' + self.idx) }));
});
return result;
},
addItems: function(items) {
this.removeAllItems();
this.items = this.createMenuItems(items);
var y = 0, x = 0;
this.items.forEach(function(item) {
var itemMorph = new lively.morphic.MenuItem(item);
this.itemMorphs.push(this.addMorph(itemMorph));
itemMorph.setPosition(pt(0, y));
y += itemMorph.getExtent().y;
x = Math.max(x, itemMorph.getExtent().x);
}, this);
if (this.title) y += this.title.bounds().height;
this.setExtent(pt(x, y));
}
},
'sub menu', {
openSubMenu: function(evt, name, items) {
var m = new lively.morphic.Menu(null, items);
this.addMorph(m);
m.fitToItems.bind(m).delay(0);
this.subMenu = m;
m.ownerMenu = this;
// delayed so we can use the real text extent
(function() {
if (!m.ownerMenu) return; // we might have removed that submenu already again
m.offsetForOwnerMenu();
m.setVisible(true);
}).delay(0);
return m;
},
removeSubMenu: function() {
if (!this.subMenu) return;
var m = this.subMenu;
m.ownerMenu = null;
this.subMenu = null;
m.remove();
},
removeOwnerMenu: function() {
if (!this.ownerMenu) return;
var m = this.ownerMenu;
this.ownerMenu = null;
m.remove();
},
},
'removal', {
remove: function($super) {
$super();
this.removeSubMenu();
this.removeOwnerMenu();
},
},
'bounds calculation', {
moveBoundsForVisibility: function(menuBounds, visibleBounds) {
var offsetX = 0,
offsetY = 0;
Global.lastMenuBounds = menuBounds;
if (menuBounds.right() > visibleBounds.right())
offsetX = -1 * (menuBounds.right() - visibleBounds.right());
var overlapLeft = menuBounds.left() + offsetX;
if (overlapLeft < 0)
offsetX += -overlapLeft;
if (menuBounds.bottom() > visibleBounds.bottom()) {
offsetY = -1 * (menuBounds.bottom() - visibleBounds.bottom());
// so that hand is not directly over menu, does not work when
// menu is in the bottom right corner
offsetX += 1;
}
var overlapTop = menuBounds.top() + offsetY;
if (overlapTop < 0)
offsetY += -overlapTop;
return menuBounds.translatedBy(pt(offsetX, offsetY));
},
moveSubMenuBoundsForVisibility: function(subMenuBnds, mainMenuItemBnds, visibleBounds, direction) {
// subMenuBnds is bounds to be transformed, mainMenuItemBnds is the bounds of the menu
// item that caused the submenu to appear, visbleBounds is the bounds that the submenu
// should fit into, when there are multiple submenus force one direction with forceDirection
if (!direction) {
direction = mainMenuItemBnds.right() + subMenuBnds.width > visibleBounds.right() ?
'left' : 'right';
}
var extent = subMenuBnds.extent();
if (direction === 'left') {
subMenuBnds = mainMenuItemBnds.topLeft().addXY(-extent.x, 0).extent(extent);
} else {
subMenuBnds = mainMenuItemBnds.topRight().extent(extent);
}
if (subMenuBnds.bottom() > visibleBounds.bottom()) {
var deltaY = -1 * (subMenuBnds.bottom() - visibleBounds.bottom());
subMenuBnds = subMenuBnds.translatedBy(pt(0, deltaY));
}
// if it overlaps at the top move the bounds so that it aligns woitht he top
if (subMenuBnds.top() < visibleBounds.top()) {
var deltaY = visibleBounds.top() - subMenuBnds.top();
subMenuBnds = subMenuBnds.translatedBy(pt(0, deltaY));
}
return subMenuBnds;
},
offsetForWorld: function(pos) {
var bounds = this.innerBounds().translatedBy(pos);
if (this.title) {
bounds = bounds.withTopLeft(bounds.topLeft().addXY(0, this.title.getExtent().y));
}
if (this.owner.visibleBounds) {
bounds = this.moveBoundsForVisibility(bounds, this.owner.visibleBounds());
}
this.setBounds(bounds);
},
offsetForOwnerMenu: function() {
var owner = this.ownerMenu,
visibleBounds = this.world().visibleBounds(),
localVisibleBounds = owner.getGlobalTransform().inverse().transformRectToRect(visibleBounds),
newBounds = this.moveSubMenuBoundsForVisibility(
this.innerBounds(),
owner.overItemMorph ? owner.overItemMorph.bounds() : new Rectangle(0,0,0,0),
localVisibleBounds);
this.setBounds(newBounds);
},
fitToItems: function() {
var offset = 10 + 20,
morphs = this.itemMorphs;
if (this.title) morphs = morphs.concat([this.title]);
var widths = morphs.invoke('getTextExtent').pluck('x'),
width = Math.max.apply(Global, widths) + offset,
newExtent = this.getExtent().withX(width);
this.setExtent(newExtent);
morphs.forEach(function(ea) {
ea.setExtent(ea.getExtent().withX(newExtent.x));
if (ea.submorphs.length > 0) {
var arrow = ea.submorphs.first();
arrow.setPosition(arrow.getPosition().withX(newExtent.x-17));
}
})
}
});
Object.extend(lively.morphic.Menu, {
openAtHand: function(title, items) {
return this.openAt(lively.morphic.World.current().firstHand().getPosition(), title, items);
},
openAt: function(pos, title, items) {
var menu = new lively.morphic.Menu(title, items);
return menu.openIn(lively.morphic.World.current(), pos, false);
},
});
lively.morphic.Text.subclass("lively.morphic.MenuItem",
'settings', {
style: {
clipMode: 'hidden',
fixedHeight: true,
fixedWidth: false,
borderWidth: 0,
fill: null,
handStyle: 'default',
enableGrabbing: false,
allowInput: false,
fontSize: 10.5,
padding: Rectangle.inset(3,2),
textColor: Config.get('textColor') || Color.black,
whiteSpaceHandling: 'nowrap'
},
defaultTextColor: Config.get('textColor') || Color.black
},
'initializing', {
initialize: function($super, item) {
$super(new Rectangle(0,0, 100, 23), item.string);
this.item = item;
if (item.isSubMenu) this.addArrowMorph();
},
addArrowMorph: function() {
var extent = this.getExtent(),
arrowMorph = new lively.morphic.Text(
new Rectangle(0, 0, 10, extent.y), "▶");
arrowMorph.setPosition(pt(extent.x, 0));
arrowMorph.applyStyle(this.getStyle());
this.arrow = this.addMorph(arrowMorph);
}
},
'mouse events', {
onMouseUp: function($super, evt) {
if (evt.world.clickedOnMorph !== this && (Date.now() - evt.world.clickedOnMorphTime < 500)) {
return false; // only a click
}
$super(evt);
this.item.onClickCallback && this.item.onClickCallback(evt);
if (!this.owner.remainOnScreen) this.owner.remove(); // remove the menu
evt.stop();
return true;
},
onMouseOver: function(evt) {
if (this.isSelected) return true;
this.select();
this.item.onMouseOverCallback && this.item.onMouseOverCallback(evt);
evt.stop();
return true;
},
onMouseWheel: function(evt) {
return false; // to allow scrolling
},
onSelectStart: function(evt) {
return false; // to allow scrolling
},
select: function(evt) {
this.isSelected = true;
this.owner.itemMorphs.without(this).invoke('deselect');
this.applyStyle({
fill: new lively.morphic.LinearGradient([
{offset: 0, color: Color.rgb(100,131,248)},
{offset: 1, color: Color.rgb(34,85,245)}]),
textColor: Color.white,
borderRadius: 4
});
// if the item is a submenu, set its textColor to white
var arrow = this.submorphs.first();
if (arrow) {
arrow.applyStyle({textColor: Color.white});
}
this.owner.overItemMorph = this;
this.owner.removeSubMenu();
return true;
},
deselect: function(evt) {
this.isSelected = false;
this.applyStyle({fill: null, textColor: this.defaultTextColor});
if (this.arrow) {
this.arrow.applyStyle({textColor: this.defaultTextColor});
}
}
});
lively.morphic.Morph.addMethods(
'menu', {
enableMorphMenu: function() {
this.showsMorphMenu = true;
},
disableMorphMenu: function() { this.showsMorphMenu = false },
openMorphMenuAt: function(pos, itemFilter) {
itemFilter = Object.isFunction(itemFilter) ? itemFilter : Functions.K;
return lively.morphic.Menu.openAt(pos, this.name || this.toString(),
itemFilter(this.morphMenuItems()));
},
createMorphMenu: function(itemFilter) {
itemFilter = Object.isFunction(itemFilter) ? itemFilter : Functions.K;
return new lively.morphic.Menu(this.name || this.toString(),
itemFilter(this.morphMenuItems()));
},
showMorphMenu: function(evt) {
var pos = evt ? evt.getPosition() : this.firstHand().getPosition();
evt && evt.stop();
this.openMorphMenuAt(pos);
return true;
},
morphMenuItems: function() {
var self = this,
world = this.world(),
items = [];
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// partsbin related
items.push(['Publish', function(evt) { self.copyToPartsBinWithUserRequest(); }]);
if (this.reset) {
[].pushAt
var idx=-1; items.detect(function(item, i) { idx = i; return item[0] === 'Publish'; });
idx > -1 && items.pushAt(['Reset', this.reset.bind(this)], idx+1);
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// morphic hierarchy / windows
items.push(['Open in...', [
['Window', function(evt) { self.openInWindow(evt.mousePoint); }],
['Flap...', ['top', 'right', 'bottom', 'left'].map(function(align) {
return [align, function(evt) {
require('lively.morphic.MorphAddons').toRun(function() {
self.openInFlap(align); }); }]; })]
]]);
// Drilling into scene to addMorph or get a halo
// whew... this is expensive...
function menuItemsForMorphsBeneathMe(itemCallback) {
var morphs = world.morphsContainingPoint(self.worldPoint(pt(0,0)));
morphs.pop(); // remove world
var selfInList = morphs.indexOf(self);
// remove self and other morphs over self (the menu)
morphs = morphs.slice(selfInList + 1);
return morphs.collect(function(ea) { return [String(ea), itemCallback.bind(this, ea)]; });
}
items.push(["Add morph to...", {
getItems: menuItemsForMorphsBeneathMe.bind(this, function(morph) { morph.addMorph(self) })
}]);
items.push(["Get halo on...", {
getItems: menuItemsForMorphsBeneathMe.bind(this, function(morph, evt) { morph.toggleHalos(evt); })
}]);
if (this.owner && this.owner.submorphs.length > 1) {
var arrange = [];
arrange.push(["Bring to front", function(){self.bringToFront()}]);
arrange.push(["Send to back", function(){self.sendToBack()}]);
items.push(["Arrange morph", arrange]);
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// stepping scripts
var steppingItems = [];
if (this.startSteppingScripts) {
steppingItems.push(["Start stepping", function(){self.startSteppingScripts()}])
}
if (this.scripts.length != 0) {
steppingItems.push(["Stop stepping", function(){self.stopStepping()}])
}
if (steppingItems.length != 0) {
items.push(["Stepping", steppingItems])
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// lively bindings
items.push(["Connections...", {
getConnections: function() {
if (!this.connections) {
this.connections = !self.attributeConnections ? [] :
self.attributeConnections
// rk: come on, this is a mess!
.reject(function(ea) { return ea.dependedBy }) // Meta connection
.reject(function(ea) { return ea.targetMethodName == 'alignToMagnet'}) // Meta connection
}
return this.connections;
},
condition: function() {
return this.getConnections().length > 0;
},
getItems: function() {
return this.getConnections()
.collect(function(ea) {
var s = ea.sourceAttrName + " -> " + ea.targetObj + "." + ea.targetMethodName
return [s, [
["Disconnect", function() { alertOK("disconnecting " + ea); ea.disconnect(); }],
["Edit converter", function() { var window = lively.bindings.editConnection(ea); }],
["Show", function() { lively.bindings.showConnection(ea); }],
["Hide", function() { if (ea.visualConnector) ea.visualConnector.remove(); }]]];
});
}
}]);
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// morphic properties
var morphicMenuItems = ['Morphic properties', []];
items.push(morphicMenuItems);
morphicMenuItems[1].push(['display serialization info', function() {
require('lively.persistence.Debugging').toRun(function() {
var json = self.copy(true),
printer = lively.persistence.Debugging.Helper.listObjects(json);
var text = world.addTextWindow({content: printer.toString(),
extent: pt(600, 200),
title: 'Objects in this world'});
text.setFontFamily('Monaco,monospace');
text.setFontSize(10);
})}]);
['grabbing', 'dragging', 'dropping', 'halos'].forEach(function(propName) {
if (self[propName + 'Enabled'] || self[propName + 'Enabled'] == undefined) {
morphicMenuItems[1].push(["Disable " + propName.capitalize(), self['disable' + propName.capitalize()].bind(self)]);
} else {
morphicMenuItems[1].push(["Enable " + propName.capitalize(), self['enable' + propName.capitalize()].bind(self)]);
}
});
if (this.submorphs.length > 0) {
if (this.isLocked()) {
morphicMenuItems[1].push(["Unlock parts", this.unlock.bind(this)])
} else {
morphicMenuItems[1].push(["Lock parts", this.lock.bind(this)])
}
}
if (this.isFixed) {
morphicMenuItems[1].push(["set unfixed", function() {
self.setFixed(false);
}]);
} else {
morphicMenuItems[1].push(["set fixed", function() {
self.setFixed(true);
}]);
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// left over...
if (false) { // rk 12-06-22: what is this for???
items.push(["Enable internal selections", function() {
Trait('SelectionMorphTrait').applyTo(self, {override: ['onDrag', 'onDragStart', 'onDragEnd']});
self.enableDragging();
}])
}
return items;
},
getWindow: function() {
if (this.isWorld) {
return null;
}
if (this.isWindow) {
return this;
}
if (this.owner) {
return this.owner.getWindow();
}
return null;
},
isInInactiveWindow: function() {
var win = this.getWindow();
return win ? !win.isActive() : false;
},
},
'modal dialog', {
beModal: function(optBackgroundColor) {
/*
* Makes a morph 'modal' by adding a backpane to the world
* which is not removed as long as the morph is still there.
*
* Usage:
*
* morph.beModal(Color.gray);
*
* Enjoy
*/
if (this.backPanel) {
this.removeBackPanel();
}
function createBackPanel(extent) {
var backPanel = new lively.morphic.Box(extent.extentAsRectangle()),
style = {enableGrabbing: false, enableDragging: false};
if (optBackgroundColor) style.fill = optBackgroundColor;
backPanel.applyStyle(style).ignoreEvents();
return backPanel;
}
this.addScript(function removeBackPanel() {
this.backPanel && this.backPanel.remove && this.backPanel.remove();
delete this.backPanel;
delete this.removeBackPanel;
delete this.remove;
});
this.addScript(function remove() {
if (this.backPanelCanBeRemoved) this.removeBackPanel();
return $super();
});
this.backPanel = createBackPanel(this.owner.getExtent());
this.owner.addMorph(this.backPanel);
this.backPanel.bringToFront();
this.backPanelCanBeRemoved = false;
this.bringToFront();
this.backPanelCanBeRemoved = true;
}
});
lively.morphic.Text.addMethods(
'menu', {
morphMenuItems: function($super) {
var self = this, items = $super(), textItems = ['Text...'];
textItems.push([[
(self.inputAllowed() ? '[X]' : '[ ]') + ' input allowed',
function() { self.setInputAllowed(!self.inputAllowed()); }
], [
(self.evalEnabled ? '[X]' : '[ ]') + ' eval',
function() { self.evalEnabled = !self.evalEnabled }
], [
(self.syntaxHighlightingWhileTyping ? '[X]' : '[ ]') + ' syntax highlighting',
function() { self.syntaxHighlightingWhileTyping ?
self.disableSyntaxHighlighting() : self.enableSyntaxHighlighting() }
], [
'convert to annotation',
function() {
var part = $world.openPartItem('AnnotationPin', 'PartsBin/Documentation');
part.setPosition(self.getPosition());
part.createAnnotationFromText(self);
self.remove();
}
], [
'debugging', [
[(self.isInChunkDebugMode() ? 'disable' : 'enable') + ' text chunk debugging',
function() { self.setChunkDebugMode(!self.isInChunkDebugMode()) }],
['open text inspector', function() {
var inspector = $world.openPartItem('TextInspector', 'PartsBin/Debugging');
inspector.targetMorph.findAndConnectMorph(self);
}]
]]
]);
items.push(textItems);
return items;
},
});
lively.morphic.World.addMethods(
'tools', {
loadPartItem: function(partName, optPartspaceName) {
var optPartspaceName = optPartspaceName || 'PartsBin/NewWorld',
part = lively.PartsBin.getPart(partName, optPartspaceName);
if (!part) return;
if (part.onCreateFromPartsBin) part.onCreateFromPartsBin();
return part;
},
openPartItem: function(partName, optPartspaceName) {
var part = this.loadPartItem(partName, optPartspaceName);
part.openInWorld(pt(0,0))
part.align(part.bounds().center(), this.visibleBounds().center());
return part;
},
openPartsBin: function(evt) {
module('lively.morphic.tools.PartsBin').load(true);
return lively.BuildSpec('lively.morphic.tools.PartsBin').createMorph().openInWorldCenter();
},
openInspectorFor: function(object, evt) {
module('lively.ide.tools.Inspector').load(true);
var inspector = lively.BuildSpec('lively.ide.tools.Inspector').createMorph().openInWorldCenter();
inspector.comeForward();
inspector.inspect(object);
return inspector;
},
openStyleEditorFor: function(morph, evt) {
module('lively.ide.tools.StyleEditor').load(true);
var styleEditorWindow = lively.BuildSpec('lively.ide.tools.StyleEditor').createMorph().openInWorld();
styleEditorWindow.setTarget(morph);
var alignPos = morph.getGlobalTransform().transformPoint(morph.innerBounds().bottomLeft()),
edBounds = styleEditorWindow.innerBounds(),
visibleBounds = this.visibleBounds();
if (visibleBounds.containsRect(edBounds.translatedBy(alignPos))) {
styleEditorWindow.setPosition(alignPos);
} else {
styleEditorWindow.setPositionCentered(visibleBounds.center());
}
return styleEditorWindow;
},
openObjectEditor: function() {
module('lively.ide.tools.ObjectEditor').load(true);
return lively.BuildSpec('lively.ide.tools.ObjectEditor').createMorph().openInWorldCenter();
},
openTerminal: function() {
require('lively.ide.tools.Terminal').toRun(function() {
lively.BuildSpec('lively.ide.tools.Terminal').createMorph().openInWorldCenter().comeForward();
});
},
openObjectEditorFor: function(morph) {
var part = this.openObjectEditor();
part.setTarget(morph);
return part;
},
openMethodFinder: function() {
return this.openPartItem('MethodFinder', 'PartsBin/Tools');
},
openMethodFinderFor: function(searchString) {
var toolPane = this.get('ToolTabPane');
if (!toolPane) {
toolPane = this.openPartItem('ToolTabPane', 'PartsBin/Dialogs');
toolPane.openInWindow();
toolPane.owner.name = toolPane.name +"Window";
toolPane.owner.minExtent = pt(700,370);
var corner = toolPane.withAllSubmorphsDetect(function (ea) {
return ea.name == "ResizeCorner";
});
corner && toolPane.owner.addMorph(corner)
}
var part = toolPane.openMethodFinderFor(searchString)
part.setExtent(toolPane.tabPaneExtent)
part.owner.layout = part.owner.layout || {};
part.owner.layout.resizeWidth = true;
part.owner.layout.resizeHeight = true;
part.owner.layout.adjustForNewBounds = true;
return part;
},
openVersionViewer: function(evt) {
return this.openPartItem('VersionViewer', 'PartsBin/Wiki');
},
openTestRunner: function() {
var m = this.openPartItem('TestRunner', 'PartsBin/Tools');
m.align(m.bounds().topCenter().addPt(pt(0,-20)), this.visibleBounds().topCenter());
return m
},
openClassBrowserFor: function(searchString) {
var part = this.openPartItem('ClassBrowser', 'PartsBin/Tools');
part.targetMorph.searchClass(searchString);
return part;
},
openPublishPartDialogFor: function(morph) {
var publishDialog = this.loadPartItem('PublishPartDialog', 'PartsBin/Dialogs');
var metaInfo = morph.getPartsBinMetaInfo();
publishDialog.targetMorph.setTarget(morph);
publishDialog.openInWorldCenter();
$world.publishPartDialog = publishDialog;
return publishDialog;
},
openConnectDocumentation: function() {
return this.openPartItem('HowConnectWorks', 'PartsBin/Documentation');
},
openShortcutDocumentation: function() {
return this.openPartItem('HelpfulShortcuts', 'PartsBin/Documentation');
},
openPartsBinDocumentation: function() {
return this.openPartItem('LivelysPartsBin', 'PartsBin/Documentation');
},
openSystemBrowser: function(evt) {
var world = this,
browser;
require('lively.ide.SystemCodeBrowser').toRun(function() {
browser = new lively.ide.SystemBrowser();
browser.openIn(world);
var lastOpened = lively.ide.SourceControl.registeredBrowsers.last();
lastOpened && browser.setTargetURL(lastOpened.targetURL)
});
return browser;
},
browseCode: function(/*args*/) {
// find code and browse it
// args can be objectName, methodName, sourceModuleName
// see lively.ide.browse for more options
var args = Array.from(arguments);
require('lively.ide.SystemCodeBrowser').toRun(function() {
lively.ide.browse.apply(lively.ide, args);
});
},
openWorkspace: function(evt) {
var text = this.addTextWindow({title: 'Workspace',
content: '3 + 4', syntaxHighlighting: true})
text.accessibleInInactiveWindow = true;
text.setFontFamily('Monaco,monospace');
text.selectAll();
return text;
},
openAboutBox: function() {
var text = this.addTextWindow({title: 'About Lively Kernel'});
text.owner.setExtent(pt(390, 105));
var webR = new WebResource(new URL(Config.rootPath));
var licenseURL = 'http://lively-kernel.org/license/index.html';
var headRevision = webR.getHeadRevision().headRevision;
var repositoryString = 'Repository: ' + Config.rootPath;
var revisionString = '\n\nRevision: ' + headRevision;
var licenseString = '\n\nLicense: ' + licenseURL;
text.setTextString(repositoryString + revisionString + licenseString);
text.changeEmphasis('Repository: '.length, repositoryString.length + 1, function(emph, doEmph) {
doEmph({uri: Config.rootPath});
});
text.changeEmphasis(repositoryString.length + revisionString.length + '\n\nLicense: '.length, repositoryString.length + revisionString.length + licenseString.length + 1, function(emph, doEmph) {
doEmph({uri: licenseURL});
});
text.setSelectionRange(0,0)
return text;
},
openBootstrapParts: function() {
// load the bootstrap part from webwerkstat
// this part can fetch all his friends :-)
var oldRootPath = Config.rootPath
try {
Config.rootPath = 'http://lively-kernel.org/repository/webwerkstatt/'
this.openPartItem("BootstrapParts", "PartsBin/Tools")
} finally {
Config.rootPath = oldRootPath
}
},
openSystemConsole: function() {
return this.openPartItem('SystemConsole', 'PartsBin/Tools');
},
openBuildSpecEditor: function() {
require('lively.ide.tools.BuildSpecEditor').toRun(function() {
lively.BuildSpec('lively.ide.tools.BuildSpecEditor').createMorph().openInWorldCenter().comeForward();
});
},
openSubserverViewer: function() {
require('lively.ide.tools.SubserverViewer').toRun(function() {
lively.BuildSpec('lively.ide.tools.SubserverViewer').createMorph().openInWorldCenter().comeForward();
});
},
openServerWorkspace: function() {
require('lively.ide.tools.ServerWorkspace').toRun(function() {
lively.BuildSpec('lively.ide.tools.ServerWorkspace').createMorph().openInWorldCenter().comeForward();
});
},
openOMetaWorkspace: function() {
return this.openPartItem('OMetaWorkspace', 'core/lively/ide/tools/');
},
openGitControl: function() {
return this.openPartItem('GitControl', 'core/lively/ide/tools/');
},
},
'menu', {
morphMenuPartsBinItems: function() {
var partSpaceName = 'PartsBin/NewWorld'
var partSpace = lively.PartsBin.partsSpaceNamed(partSpaceName);
partSpace.load()
return partSpace.getPartNames().sort().collect(function(ea) { return [ea, function() {
var part = lively.PartsBin.getPart(ea, partSpaceName)
lively.morphic.World.current().firstHand().addMorph(part)
}]})
},
morphMenuDefaultPartsItems: function() {
var items = [],
partNames = ["Rectangle", "Ellipse", "Image", "Text", 'Line'].sort();
items.pushAll(partNames.collect(function(ea) { return [ea, function() {
var partSpaceName = 'PartsBin/Basic',
part = lively.PartsBin.getPart(ea, partSpaceName);
if (!part) return;
lively.morphic.World.current().firstHand().grabMorph(part);
}]}))
partNames = ["List", "Slider", "Button"].sort()
items.pushAll(partNames.collect(function(ea) { return [ea, function() {
var partSpaceName = 'PartsBin/Inputs',
part = lively.PartsBin.getPart(ea, partSpaceName);
if (!part) return;
lively.morphic.World.current().firstHand().grabMorph(part);
}]}))
return items;
},
debuggingMenuItems: function(world) {
var items = [
['Reset world scale', this.resetScale.bind(this)],
['Check app cache', this.checkApplicationCache.bind(this)],
['World serialization info', function() {
require('lively.persistence.Debugging').toRun(function() {
var json = lively.persistence.Serializer.serialize(world),
printer = lively.persistence.Debugging.Helper.listObjects(json);
var text = world.addTextWindow({content: printer.toString(),
extent: pt(600, 250),
title: 'Objects in this world'});
text.setFontFamily('Monaco,monospace');
text.setFontSize(9);
})}]];
// world requirements
var worldRequirements = world.getWorldRequirements(),
removeRequirement = function(name) {
world.removeWorldRequirement(name);
alertOK(name + ' is not loaded at startup anymore');
},
menuItems = worldRequirements.collect(function(name) {
return [name, [['Remove', removeRequirement.curry(name)]]];
});
items.push(['Requirements', menuItems]);
// method tracing items
function disableGlobalTracing() {
// FIXME better to move this functionality into lively.Tracing
var controller = $morph("TracingController");
if (controller) {
controller.stopTrace();
} else {
lively.Tracing.stopGlobalDebugging();
}
}
var tracersInstalled = lively.Tracing && lively.Tracing.stackTracingEnabled,
globalTracingEnabled = tracersInstalled && lively.Tracing.globalTracingEnabled;
if (tracersInstalled) {
items.push(["Remove trace wrappers", function() {
if (globalTracingEnabled) disableGlobalTracing();
lively.Tracing.uninstallStackTracers();
}]);
if (!globalTracingEnabled) {
items.push(['Start global tracing', function() {
lively.Tracing.startGlobalTracing()
}]);
items.push(['Start global debugging', function() {
require('lively.ast.Morphic').toRun(function() {
lively.Tracing.startGlobalDebugging()
});
}]);
}
} else {
items.push(['Prepare system for tracing/debugging', function() {
require("lively.Tracing").toRun(function() {
lively.Tracing.installStackTracers();
});
}]);
}
if (Global.DebugScriptsLayer && DebugScriptsLayer.isGlobal()) {
items.push(['[X] Debug Morphic Scripts', function() {
DebugScriptsLayer.beNotGlobal()
}]);
} else {
items.push(['[ ] Debug Morphic Scripts', function() {
require('lively.ast.Morphic').toRun(function() {
DebugScriptsLayer.beGlobal()
});
}]);
}
if (Global.DebugMethodsLayer && DebugMethodsLayer.isGlobal()) {
items.push(['[X] Debug Methods', function() {
DebugMethodsLayer.beNotGlobal()
}]);
} else {
items.push(['[ ] Debug Methods', function() {
require('lively.ast.Morphic').toRun(function() {
DebugMethodsLayer.beGlobal()
});
}]);
}
if (module('lively.ast.IDESupport').isEnabled) {
items.push(['[X] Advanced Syntax Highlighting', function() {
require('lively.ast.IDESupport').toRun(function() {
lively.ast.IDESupport.disable();
});
}]);
} else {
items.push(['[ ] Advanced Syntax Highlighting', function() {
require('lively.ast.IDESupport').toRun(function() {
lively.ast.IDESupport.enable();
})
}]);
}
if (Global.AutoIndentLayer && AutoIndentLayer.isGlobal()) {
items.push(['[X] Auto Indent', function() {
AutoIndentLayer.beNotGlobal();
}]);
} else {
items.push(['[ ] Auto Indent', function() {
require('users.cschuster.AutoIndent').toRun(function() {
AutoIndentLayer.beGlobal();
});
}]);
}
if (localStorage['Config_quickLoad'] == "false") {
items.push(['[ ] Quick Load', function() {
localStorage['Config_quickLoad'] = "true"
}]);
} else {
items.push(['[X] Quick Load', function() {
localStorage['Config_quickLoad'] = "false";
}]);
}
if (localStorage['Config_CopyAndPaste'] == "false") {
items.push(['[ ] Copy And Paste', function() {
localStorage['Config_CopyAndPaste'] = "true"
module('lively.experimental.CopyAndPaste').load(true)
ClipboardLayer.beGlobal()
}]);
} else {
items.push(['[X] Copy And Paste', function() {
localStorage['Config_CopyAndPaste'] = "false";
ClipboardLayer.beNotGlobal()
}]);
}
return items;
},
morphMenuItems: function() {
var world = this;
var items = [
['PartsBin', this.openPartsBin.bind(this)],
['Parts', this.morphMenuDefaultPartsItems()],
['Tools', [
['Workspace', this.openWorkspace.bind(this)],
['System Code Browser', this.openSystemBrowser.bind(this)],
['Object Editor', this.openObjectEditor.bind(this)],
['BuildSpec Editor', this.openBuildSpecEditor.bind(this)],
['Test Runner', this.openTestRunner.bind(this)],
['Method Finder', this.openMethodFinder.bind(this)],
['Text Editor', function() { require('lively.ide').toRun(function() { lively.ide.openFile(URL.source.toString()); }); }],
['System Console', this.openSystemConsole.bind(this)],
['OMeta Workspace', this.openOMetaWorkspace.bind(this)],
['Subserver Viewer', this.openSubserverViewer.bind(this)],
['Server Workspace', this.openServerWorkspace.bind(this)],
['Terminal', this.openTerminal.bind(this)],
['Git Control', this.openGitControl.bind(this)]
]],
['Stepping', [
['Start stepping', function() { world.submorphs.each(
function(ea) {ea.startSteppingScripts && ea.startSteppingScripts()})}],
['Stop stepping', function() { world.submorphs.each(
function(ea) {ea.stopStepping && ea.stopStepping()})}],
]],
['Preferences', [
['Set username', this.askForUserName.bind(this)],
['My user config', this.showUserConfig.bind(this)],
['Set world extent', this.askForNewWorldExtent.bind(this)],
['Set background color', this.askForNewBackgroundColor.bind(this)]]
],
['Debugging', this.debuggingMenuItems(world)],
['Wiki', [
// ['About this wiki', this.openAboutBox.bind(this)],
// ['Bootstrap parts from webwerkstatt', this.openBootstrapParts.bind(this)],
// ['View versions of this world', this.openVersionViewer.bind(this)],
['Download world', function() {
require('lively.persistence.StandAlonePackaging').toRun(function() {
lively.persistence.StandAlonePackaging.packageCurrentWorld();
});
}],
['Delete world', this.interactiveDeleteWorldOnServer.bind(this)]
]],
['Documentation', [
["On short cuts", this.openShortcutDocumentation.bind(this)],
["On connect data bindings", this.openConnectDocumentation.bind(this)],
["On Lively's PartsBin", this.openPartsBinDocumentation.bind(this)],
["More ...", function() { window.open(Config.rootPath + 'documentation/'); }]
]],
['Save world as ...', this.interactiveSaveWorldAs.bind(this), 'synchron'],
['Save world', this.saveWorld.bind(this), 'synchron']
];
return items;
}
},
'positioning', {
positionForNewMorph: function (newMorph, relatedMorph) {
// this should be much smarter than the following:
if (relatedMorph)
return relatedMorph.bounds().topLeft().addPt(pt(5, 0));
var pos = this.firstHand().getPosition();
if (!newMorph) return pos;
var viewRect = this.visibleBounds().insetBy(80),
newMorphBounds = pos.extent(newMorph.getExtent());
// newShowRect(viewRect)
return viewRect.containsRect(newMorphBounds) ?
pos : viewRect.center().subPt(newMorphBounds.extent().scaleBy(0.5));
},
},
'windows', {
addFramedMorph: function(morph, title, optLoc, optSuppressControls, suppressReframeHandle) {
var w = this.addMorph(new lively.morphic.Window(morph, title || 'Window', optSuppressControls, suppressReframeHandle));
w.setPosition(optLoc || this.positionForNewMorph(morph));
return w;
},
addTextWindow: function(spec) {
// FIXME: typecheck the spec
if (Object.isString(spec.valueOf())) spec = {content: spec}; // convenience
var extent = spec.extent || pt(500, 200),
textMorph = new lively.morphic.Text(extent.extentAsRectangle(), spec.content || ""),
pane = this.internalAddWindow(textMorph, spec.title, spec.position);
textMorph.applyStyle({
clipMode: 'auto',
fixedWidth: true, fixedHeight: true,
resizeWidth: true, resizeHeight: true,
syntaxHighlighting: spec.syntaxHighlighting,
padding: Rectangle.inset(4,2),
fontSize: Config.get('defaultCodeFontSize')
});
return pane;
},
internalAddWindow: function(morph, title, pos, suppressReframeHandle) {
morph.applyStyle({borderWidth: 1, borderColor: CrayonColors.iron});
pos = pos || this.firstHand().getPosition().subPt(pt(5, 5));
var win = this.addFramedMorph(morph, String(title || ""), pos, suppressReframeHandle);
return morph;
},
addModal: function(morph, optModalOwner) {
// add morph inside the world or in a window (if one currently is
// marked active) so that the rest of the world/window is grayed out
// and blocked.
var modalOwner = optModalOwner || this,
modalBounds = modalOwner.innerBounds(),
blockMorph = lively.morphic.Morph.makeRectangle(modalBounds),
transparentMorph = lively.morphic.Morph.makeRectangle(blockMorph.innerBounds());
blockMorph.isEpiMorph = true;
blockMorph.applyStyle({
fill: null,
borderWidth: 0,
enableGrabbing: false,
enableDragging: false
});
transparentMorph.applyStyle({
fill: Color.black,
opacity: 0.5,
enableGrabbing: false,
enableDragging: false
});
transparentMorph.isEpiMorph = true;
blockMorph.addMorph(transparentMorph);
if (modalOwner.modalMorph) modalOwner.modalMorph.remove();
blockMorph.addMorph(morph);
var alignBounds = modalOwner.visibleBounds ?
modalOwner.visibleBounds() : modalOwner.innerBounds();
morph.align(morph.bounds().center(), alignBounds.center());
modalOwner.modalMorph = modalOwner.addMorph(blockMorph);
lively.bindings.connect(morph, 'remove', blockMorph, 'remove');
morph.focus();
return morph;
},
},
'dialogs', {
openDialog: function(dialog) {
var focusedMorph = lively.morphic.Morph.focusedMorph(),
win = this.getActiveWindow();
dialog.openIn(this, this.visibleBounds().topLeft(), focusedMorph);
this.addModal(dialog.panel, win ? win : this);
return dialog;
},
confirm: function (message, callback) {
return this.openDialog(new lively.morphic.ConfirmDialog(message, callback));
},
prompt: function (message, callback, defaultInput) {
return this.openDialog(new lively.morphic.PromptDialog(message, callback, defaultInput))
},
listPrompt: function (message, callback, list, defaultInput, optExtent) {
// $world.listPrompt('test', alert, [1,2,3,4], 3, pt(400,300));
module('lively.morphic.tools.ConfirmList').load(true);
var listPrompt = lively.BuildSpec('lively.morphic.tools.ConfirmList').createMorph();
listPrompt.promptFor({
prompt: message,
list: list,
selection: defaultInput,
extent: optExtent
});
(function() { listPrompt.get('target').focus(); }).delay(0);
lively.bindings.connect(listPrompt, 'result', {cb: callback}, 'cb');
return this.addModal(listPrompt);
},
editPrompt: function (message, callback, defaultInput) {
return this.openDialog(new lively.morphic.EditDialog(message, callback, defaultInput))
}
},
'progress bar', {
addProgressBar: function(optPt, optLabel) {
var progressBar = new lively.morphic.ProgressBar(),
center = optPt || this.visibleBounds().center();
this.addMorph(progressBar);
progressBar.align(progressBar.bounds().center(), center);
progressBar.setLabel(optLabel || '');
progressBar.ignoreEvents();
return progressBar
},
},
'preferences', {
askForUserName: function() {
var world = this;
this.prompt("Please enter your username", function(name) {
if (name) {
world.setCurrentUser(name);
alertOK("set username to: " + name);
} else {
alertOK("removing username")
world.setCurrentUser(undefined);
}
}, world.getUserName(true));
},
askForNewWorldExtent: function() {
var world = this;
this.prompt("Please enter new world extent", function(str) {
if (!str) return;
var newExtent;
try {
newExtent = eval(str);
} catch(e) {
alert("Could not eval: " + str)
};
if (! (newExtent instanceof lively.Point)) {
alert("" + newExtent + " " + "is not a proper extent")
return
}
world.setExtent(newExtent);
alertOK("Set world extent to " + newExtent);
}, this.getExtent())
},
askForNewBackgroundColor: function() {
var world = this,
oldColor = this.getFill();
if(! (oldColor instanceof Color)){
oldColor = Color.rgb(255,255,255);
}
this.prompt("Please enter new world background color", function(str) {
if (!str) return;
var newColor;
try {
newColor = eval(str);
} catch(e) {
alert("Could not eval: " + str)
};
if (! (newColor instanceof Color)) {
alert("" + newColor + " " + "is not a proper Color")
return
}
world.setFill(newColor);
alertOK("Set world background to " + newColor);
}, "Color." + oldColor)
},
setCurrentUser: function(username) {
this.currentUser = username;
if (lively.LocalStorage)
lively.LocalStorage.set('UserName', username);
},
},
'morph selection', {
withSelectedMorphsDo: function(func, context) {
// FIXME currently it is the halo target...
if (!this.currentHaloTarget) return;
func.call(context || Global, this.currentHaloTarget);
},
},
'debugging', {
resetAllScales: function() {
this.withAllSubmorphsDo(function(ea) {
ea.setScale(1);
})
},
resetScale: function () {
this.setScale(1);
this.firstHand().setScale(1)
},
checkApplicationCache: function() {
var cache = lively.ApplicationCache,
pBar = this.addProgressBar(null, 'app cache'),
handlers = {
onProgress: function(progress) {
pBar && pBar.setValue(progress.evt.loaded/progress.evt.total);
},
done: function(progress) {
disconnect(cache, 'progress', handlers, 'onProgress');
disconnect(cache, 'noupdate', handlers, 'done');
disconnect(cache, 'updateready', handlers, 'done');
pBar && pBar.remove(); }
}
connect(cache, 'progress', handlers, 'onProgress');
connect(cache, 'noupdate', handlers, 'done');
connect(cache, 'updaetready', handlers, 'done');
cache.update();
},
resetAllButtonLabels: function() {
this.withAllSubmorphsDo(function(ea) {
if (ea instanceof lively.morphic.Button) {
// doppelt haellt besser ;) (old german proverb)
ea.setLabel(ea.getLabel());
ea.setLabel(ea.getLabel());
}
})
},
},
'wiki', {
interactiveDeleteWorldOnServer: function() {
var url = URL.source;
this.world().confirm('Do you really want to delete ' + url.filename() + '?',
function(answer) {
if (!answer) return;
new WebResource(URL.source)
.statusMessage('Removed ' + url, 'Error removing ' + url, true)
.del();
})
},
getActiveWindow: function () {
for (var i = this.submorphs.length-1; i >= 0; i--) {
var morph = this.submorphs[i];
if (morph.isWindow && morph.isActive()) return morph;
}
return null;
},
closeActiveWindow: function() {
var win = this.getActiveWindow();
win && win.initiateShutdown();
return !!win;
},
activateTopMostWindow: function() {
var morphBelow = this.topMorph();
if (morphBelow && morphBelow.isWindow) {
var scroll = this.getScrollOffset && this.getScrollOffset();
morphBelow.comeForward();
if (scroll) this.setScroll(scroll.x, scroll.y);
}
},
});
lively.morphic.List.addMethods(
'documentation', {
connections: {
selection: {},
itemList: {},
selectedLineNo: {}
},
},
'settings', {
style: {
borderColor: Color.black,
borderWidth: 0,
fill: Color.gray.lighter().lighter(),
clipMode: 'auto',
fontFamily: 'Helvetica',
fontSize: 10,
enableGrabbing: false
},
selectionColor: Color.green.lighter(),
isList: true
},
'initializing', {
initialize: function($super, bounds, optItems) {
$super(bounds);
this.itemList = [];
this.selection = null;
this.selectedLineNo = -1;
if (optItems) this.updateList(optItems);
},
},
'accessing', {
setExtent: function($super, extent) {
$super(extent);
this.resizeList();
},
getListExtent: function() { return this.renderContextDispatch('getListExtent') }
},
'list interface', {
getMenu: function() { /*FIXME actually menu items*/ return [] },
updateList: function(items) {
if (!items) items = [];
this.itemList = items;
var that = this,
itemStrings = items.collect(function(ea) { return that.renderFunction(ea); });
this.renderContextDispatch('updateListContent', itemStrings);
},
addItem: function(item) {
this.updateList(this.itemList.concat([item]));
},
selectAt: function(idx) {
if (!this.isMultipleSelectionList) this.clearSelections();
this.renderContextDispatch('selectAllAt', [idx]);
this.updateSelectionAndLineNoProperties(idx);
},
saveSelectAt: function(idx) {
this.selectAt(Math.max(0, Math.min(this.itemList.length-1, idx)));
},
deselectAt: function(idx) { this.renderContextDispatch('deselectAt', idx) },
updateSelectionAndLineNoProperties: function(selectionIdx) {
var item = this.itemList[selectionIdx];
this.selectedLineNo = selectionIdx;
this.selection = item && (item.value !== undefined) ? item.value : item;
},
setList: function(items) { return this.updateList(items) },
getList: function() { return this.itemList },
getValues: function() {
return this.getList().collect(function(ea) { return ea.isListItem ? ea. value : ea})
},
setSelection: function(sel) {
this.selectAt(this.find(sel));
},
getSelection: function() { return this.selection },
getItem: function(value) {
return this.itemList[this.find(value)];
},
removeItemOrValue: function(itemOrValue) {
var idx = this.find(itemOrValue), item = this.itemList[idx];
this.updateList(this.itemList.without(item));
return item;
},
getSelectedItem: function() {
return this.selection && this.selection.isListItem ?
this.selection : this.itemList[this.selectedLineNo];
},
moveUpInList: function(itemOrValue) {
if (!itemOrValue) return;
var idx = this.find(itemOrValue);
if (idx === undefined) return;
this.changeListPosition(idx, idx-1);
},
moveDownInList: function(itemOrValue) {
if (!itemOrValue) return;
var idx = this.find(itemOrValue);
if (idx === undefined) return;
this.changeListPosition(idx, idx+1);
},
clearSelections: function() { this.renderContextDispatch('clearSelections') }
},
'private list functions', {
changeListPosition: function(oldIdx, newIdx) {
var item = this.itemList[oldIdx];
this.itemList.removeAt(oldIdx);
this.itemList.pushAt(item, newIdx);
this.updateList(this.itemList);
this.selectAt(newIdx);
},
resizeList: function(idx) {
return this.renderContextDispatch('resizeList');
},
find: function(itemOrValue) {
// returns the index in this.itemList
for (var i = 0; i < this.itemList.length; i++) {
var val = this.itemList[i];
if (val === itemOrValue || (val && val.isListItem && val.value === itemOrValue)) {
return i;
}
}
// return -1?
return undefined;
}
},
'styling', {
applyStyle: function($super, spec) {
if (spec.fontFamily !== undefined) this.setFontFamily(spec.fontFamily);
if (spec.fontSize !== undefined) this.setFontSize(spec.fontSize);
return $super(spec);
},
setFontSize: function(fontSize) { return this.morphicSetter('FontSize', fontSize) },
getFontSize: function() { return this.morphicGetter('FontSize') || 10 },
setFontFamily: function(fontFamily) { return this.morphicSetter('FontFamily', fontFamily) },
getFontFamily: function() { return this.morphicSetter('FontFamily') || 'Helvetica' }
},
'multiple selection support', {
enableMultipleSelections: function() {
this.isMultipleSelectionList = true;
this.renderContextDispatch('enableMultipleSelections');
},
getSelectedItems: function() {
var items = this.itemList;
return this.getSelectedIndexes().collect(function(i) { return items[i] });
},
getSelectedIndexes: function() { return this.renderContextDispatch('getSelectedIndexes'); },
getSelections: function() {
return this.getSelectedItems().collect(function(ea) { return ea.isListItem ? ea.value : ea; })
},
setSelections: function(arr) {
var indexes = arr.collect(function(ea) { return this.find(ea) }, this);
this.selectAllAt(indexes);
},
setSelectionMatching: function(string) {
for (var i = 0; i < this.itemList.length; i++) {
var itemString = this.itemList[i].string || String(this.itemList[i]);
if (string == itemString) this.selectAt(i);
}
},
selectAllAt: function(indexes) {
this.renderContextDispatch('selectAllAt', indexes)
},
renderFunction: function(anObject) {
return anObject.string || String(anObject);
}
});
lively.morphic.DropDownList.addMethods(
'initializing', {
initialize: function($super, bounds, optItems) {
$super(bounds, optItems);
},
});
lively.morphic.Box.subclass('lively.morphic.MorphList',
'settings', {
style: {
fill: Color.gray.lighter(3),
borderColor: Color.gray.lighter(),
borderWidth: 1,
borderStyle: 'outset',
},
isList: true
},
'initializing', {
initialize: function($super, items) {
$super(new Rectangle(0,0, 100,100));
this.itemMorphs = [];
this.setList(items || []);
this.initializeLayout();
},
initializeLayout: function(layoutStyle) {
// layoutStyle: {
// type: "tiling"|"horizontal"|"vertical",
// spacing: NUMBER,
// border: NUMBER
// }
var defaultLayout = {
type: 'tiling',
border: 0, spacing: 20
}
layoutStyle = Object.extend(defaultLayout, layoutStyle || {});
this.applyStyle({
fill: Color.white, borderWidth: 0,
borderColor: Color.black, clipMode: 'auto',
resizeWidth: true, resizeHeight: true
})
var klass;
switch (layoutStyle.type) {
case 'vertical': klass = lively.morphic.Layout.VerticalLayout; break;
case 'horizontal': klass = lively.morphic.Layout.HorizontalLayout; break;
case 'tiling': klass = lively.morphic.Layout.TileLayout; break;
default: klass = lively.morphic.Layout.TileLayout; break;
}
layouter = new klass(this);
layouter.setBorderSize(layoutStyle.border);
layouter.setSpacing(layoutStyle.spacing);
this.setLayouter(layouter);
},
},
'morph menu', {
getMenu: function() { /*FIXME actually menu items*/ return [] }
},
'list interface', {
renderFunction: function(listItem) {
if (!listItem) return listItem = {isListItem: true, string: 'invalid list item: ' + listItem};
if (listItem.morph) return listItem.morph;
var string = listItem.string || String(listItem);
return new lively.morphic.Text(lively.rect(0,0,100,20), string);
},
updateList: function(items) {
if (!items) items = [];
this.itemList = items;
this.itemMorphs = items.collect(function(ea) { return this.renderFunction(ea); }, this);
this.removeAllMorphs();
this.itemMorphs.forEach(function(ea) { this.addMorph(ea); }, this);
},
addItem: function(item) {
// this.updateList(this.itemList.concat([item]));
},
selectAt: function(idx) {
// if (!this.isMultipleSelectionList) this.clearSelections();
// this.renderContextDispatch('selectAllAt', [idx]);
// this.updateSelectionAndLineNoProperties(idx);
},
saveSelectAt: function(idx) {
// this.selectAt(Math.max(0, Math.min(this.itemList.length-1, idx)));
},
deselectAt: function(idx) {
// this.renderContextDispatch('deselectAt', idx)
},
updateSelectionAndLineNoProperties: function(selectionIdx) {
// var item = this.itemList[selectionIdx];
// this.selectedLineNo = selectionIdx;
// this.selection = item && (item.value !== undefined) ? item.value : item;
},
setList: function(items) {
return this.updateList(items);
},
getList: function() {
return this.itemList;
},
getValues: function() {
return this.getList().collect(function(ea) { return ea.isListItem ? ea. value : ea});
},
setSelection: function(sel) {
// this.selectAt(this.find(sel));
},
getSelection: function() { return this.selection },
getItem: function(value) {
// return this.itemList[this.find(value)];
},
removeItemOrValue: function(itemOrValue) {
// var idx = this.find(itemOrValue), item = this.itemList[idx];
// this.updateList(this.itemList.without(item));
// return item;
},
getSelectedItem: function() {
// return this.selection && this.selection.isListItem ?
// this.selection : this.itemList[this.selectedLineNo];
},
moveUpInList: function(itemOrValue) {
// if (!itemOrValue) return;
// var idx = this.find(itemOrValue);
// if (idx === undefined) return;
// this.changeListPosition(idx, idx-1);
},
moveDownInList: function(itemOrValue) {
// if (!itemOrValue) return;
// var idx = this.find(itemOrValue);
// if (idx === undefined) return;
// this.changeListPosition(idx, idx+1);
},
clearSelections: function() {
// this.renderContextDispatch('clearSelections');
}
},
'multiple selection support', {
enableMultipleSelections: function() {
// this.isMultipleSelectionList = true;
// this.renderContextDispatch('enableMultipleSelections');
},
getSelectedItems: function() {
// var items = this.itemList;
// return this.getSelectedIndexes().collect(function(i) { return items[i] });
},
getSelectedIndexes: function() {
//return this.renderContextDispatch('getSelectedIndexes');
},
getSelections: function() {
// return this.getSelectedItems().collect(function(ea) { return ea.isListItem ? ea.value : ea; })
},
setSelections: function(arr) {
// var indexes = arr.collect(function(ea) { return this.find(ea) }, this);
// this.selectAllAt(indexes);
},
setSelectionMatching: function(string) {
// for (var i = 0; i < this.itemList.length; i++) {
// var itemString = this.itemList[i].string || String(this.itemList[i]);
// if (string == itemString) this.selectAt(i);
// }
},
selectAllAt: function(indexes) {
// this.renderContextDispatch('selectAllAt', indexes)
}
});
lively.morphic.Button.subclass("lively.morphic.WindowControl",
'documentation', {
documentation: "Event handling for Window morphs",
},
'settings and state', {
style: {borderWidth: 0, strokeOpacity: 0, padding: Rectangle.inset(0,2), accessibleInInactiveWindow: true},
connections: ['HelpText', 'fire'],
},
'initializing', {
initialize: function($super, bnds, inset, labelString, labelOffset) {
$super(bnds, labelString)
this.label.applyStyle({fontSize: 8})
if (labelOffset) {
this.label.setPosition(this.label.getPosition().addPt(labelOffset));
}
this.setAppearanceStylingMode(true);
this.setBorderStylingMode(true);
},
});
lively.morphic.Box.subclass("lively.morphic.TitleBar",
'documentation', {
documentation: "Title bar for lively.morphic.Window",
},
'properties', {
controlSpacing: 3,
barHeight: 22,
shortBarHeight: 15,
accessibleInInactiveWindow: true,
style: {
adjustForNewBounds: true,
resizeWidth: true
},
labelStyle: {
padding: Rectangle.inset(0,0),
fixedWidth: true,
fixedHeight: true,
resizeWidth: true,
allowInput: false
}
},
'intitializing', {
initialize: function($super, headline, windowWidth, windowMorph) {
var bounds = new Rectangle(0, 0, windowWidth, this.barHeight);
$super(bounds);
this.windowMorph = windowMorph;
this.buttons = [];
// Note: Layout of submorphs happens in adjustForNewBounds (q.v.)
var label;
if (headline instanceof lively.morphic.Text) {
label = headline;
} else if (headline != null) { // String
label = lively.morphic.Text.makeLabel(headline, this.labelStyle);
}
this.label = this.addMorph(label);
this.label.addStyleClassName('window-title');
this.label.setTextStylingMode(true);
this.disableDropping();
this.setAppearanceStylingMode(true);
this.setBorderStylingMode(true);
},
addButton: function(label, optLabelOffset, optWidth) {
var length = this.barHeight - 5;
var extent = lively.pt(optWidth || length, length);
var button = this.addMorph(
new lively.morphic.WindowControl(
lively.rect(lively.pt(0, 0), extent),
this.controlSpacing,
label,
optLabelOffset || pt(0,0)));
this.buttons.push(button);
// This will align the label properly
this.adjustLabelBounds();
return button;
},
},
'label', {
setTitle: function(string) {
this.label.replaceTextString(string);
},
getTitle: function(string) { return this.label.textString }
},
'layouting', {
adjustLabelBounds: function($super) {
// $super(); adjustForNewBounds()
var innerBounds = this.innerBounds(),
sp = this.controlSpacing;
var buttonLocation = this.innerBounds().topRight().subXY(sp, -sp);
this.buttons.forEach(function(ea) {
buttonLocation = buttonLocation.subXY(ea.shape.getBounds().width, 0);
ea.setPosition(buttonLocation);
buttonLocation = buttonLocation.subXY(sp, 0)
});
if (this.label) {
var start = this.innerBounds().topLeft().addXY(sp, sp),
end = lively.pt(buttonLocation.x, innerBounds.bottomRight().y).subXY(sp, sp);
this.label.setBounds(rect(start, end));
}
},
adjustForNewBounds: function() {
this.adjustLabelBounds();
},
lookCollapsedOrNot: function(collapsed) {
this.applyStyle({borderRadius: collapsed ? "8px 8px 8px 8px" : "8px 8px 0px 0px"});
}
},
'event handling', {
onMouseDown: function (evt) {
//Functions.False,
// TODO: refactor to evt.hand.clickedOnMorph when everything else is ready for it
evt.world.clickedOnMorph = this.windowMorph;
},
onMouseUp: Functions.False
});
lively.morphic.Morph.subclass('lively.morphic.Window', Trait('lively.morphic.DragMoveTrait').derive({override: ['onDrag','onDragStart', 'onDragEnd']}),
'documentation', {
documentation: "Full-fledged windows with title bar, menus, etc"
},
'settings and state', {
state: 'expanded',
spacing: 4, // window border
minWidth: 200,
minHeight: 100,
debugMode: false,
style: {
borderWidth: false,
fill: null,
borderRadius: false,
strokeOpacity: false,
adjustForNewBounds: true,
enableDragging: true
},
isWindow: true,
isCollapsed: function() { return this.state === 'collapsed'; }
},
'initializing', {
initialize: function($super, targetMorph, titleString, optSuppressControls) {
$super(new lively.morphic.Shapes.Rectangle());
var bounds = targetMorph.bounds(),
spacing = this.spacing;
bounds.width += 2 * spacing;
bounds.height += 1 * spacing;
var titleBar = this.makeTitleBar(titleString, bounds.width, optSuppressControls),
titleHeight = titleBar.bounds().height - titleBar.getBorderWidth();
this.setBounds(bounds.withHeight(bounds.height + titleHeight));
this.makeReframeHandles();
this.titleBar = this.addMorph(titleBar);
this.contentOffset = pt(spacing, titleHeight);
this.collapsedTransform = null;
this.collapsedExtent = null;
this.expandedTransform = null;
this.expandedExtent = null;
this.ignoreEventsOnExpand = false;
this.disableDropping();
this.setAppearanceStylingMode(true);
this.setBorderStylingMode(true);
this.targetMorph = this.addMorph(targetMorph);
this.targetMorph.setPosition(this.contentOffset);
},
makeReframeHandles: function() {
// create three reframe handles (bottom, right, and bottom-right) and align them to the window
var e = this.getExtent();
this.reframeHandle = this.addMorph(new lively.morphic.ReframeHandle('corner', pt(14,14)));
this.rightReframeHandle = this.addMorph(new lively.morphic.ReframeHandle('right', e.withX(this.spacing)));
this.bottomReframeHandle = this.addMorph(new lively.morphic.ReframeHandle('bottom', e.withY(this.spacing)));
this.alignAllHandles();
},
makeTitleBar: function(titleString, width, optSuppressControls) {
// Overridden in TabbedPanelMorph
var titleBar = new lively.morphic.TitleBar(titleString, width, this);
if (optSuppressControls) return titleBar;
var closeButton = titleBar.addButton("X", pt(0,-1));
closeButton.addStyleClassName('close');
var collapseButton = titleBar.addButton("–", pt(0,1));
var menuButton = titleBar.addButton("Menu", null, 40);
closeButton.plugTo(this, {getHelpText: '->getCloseHelp', fire: '->initiateShutdown'});
menuButton.plugTo(this, {getHelpText: '->getMenuHelp', fire: '->showTargetMorphMenu'});
collapseButton.plugTo(this, {getHelpText: '->getCollapseHelp', fire: '->toggleCollapse'});
return titleBar;
},
resetTitleBar: function() {
var oldTitleBar = this.titleBar;
oldTitleBar.remove();
this.titleBar = this.makeTitleBar(oldTitleBar.label.textString, this.getExtent().x);
this.addMorph(this.titleBar);
},
},
'window behavior', {
initiateShutdown: function() {
if (this.isShutdown()) return null;
var owner = this.owner;
if (this.onShutdown) this.onShutdown();
if (this.targetMorph && this.targetMorph.onShutdown) this.targetMorph.onShutdown();
this.remove();
if (owner.activateTopMostWindow) owner.activateTopMostWindow();
this.state = 'shutdown'; // no one will ever know...
return true;
},
isShutdown: function() { return this.state === 'shutdown' }
},
'accessing', {
setTitle: function(string) { this.titleBar.setTitle(string) },
getTitle: function() { return this.titleBar.getTitle() },
getBounds: function($super) {
if (this.titleBar && this.isCollapsed()) {
var titleBarTranslation = this.titleBar.getGlobalTransform().getTranslation();
return this.titleBar.bounds().translatedBy(titleBarTranslation);
}
return $super();
}
},
'reframe handles', {
removeHalos: function($super, optWorld) {
// Sadly, this doesn't get called when click away from halo
// Need to patch World.removeHalosFor, or refactor so it calls this
this.alignAllHandles();
$super(optWorld);
},
alignAllHandles: function() {
if (this.isCollapsed()) return;
this.reframeHandle && this.reframeHandle.alignWithWindow();
this.bottomReframeHandle && this.bottomReframeHandle.alignWithWindow();
this.rightReframeHandle && this.rightReframeHandle.alignWithWindow();
}
},
'menu', {
showTargetMorphMenu: function() {
var target = this.targetMorph || this, itemFilter;
if (this.targetMorph) {
var self = this;
itemFilter = function (items) {
items[0] = ['Publish window', function(evt) {
self.copyToPartsBinWithUserRequest();
}];
// set fixed support
var fixItem = items.find(function (ea) {
return ea[0] == "set fixed" || ea[0] == "set unfixed" });
if (fixItem) {
if (self.isFixed) {
fixItem[0] = "set unfixed";
fixItem[1] = function() {
self.setFixed(false);
}
} else {
fixItem[0] = "set fixed"
fixItem[1] = function() {
self.setFixed(true);
}
}
}
items[1] = ['Set window title', function(evt) {
self.world().prompt('Set window title', function(input) {
if (input !== null) self.titleBar.setTitle(input || '');
}, self.titleBar.getTitle());
}];
if (self.targetMorph.ownerApp && self.targetMorph.ownerApp.morphMenuItems) {
self.targetMorph.ownerApp.morphMenuItems().each(function(ea) {items.push(ea)})
}
return items;
}
}
var menu = target.createMorphMenu(itemFilter);
var menuBtnTopLeft = this.menuButton.bounds().topLeft();
var menuTopLeft = menuBtnTopLeft.subPt(pt(menu.bounds().width, 0));
menu.openIn(
lively.morphic.World.current(),
this.getGlobalTransform().transformPoint(menuTopLeft),
false);
},
morphMenuItems: function($super) {
var self = this, world = this.world(), items = $super();
items[0] = ['Publish window', function(evt) { self.copyToPartsBinWithUserRequest(); }];
items.push([
'Set title', function(evt) {
world.prompt('Enter new title', function(input) {
if (input || input == '') self.setTitle(input);
}, self.getTitle()); }]);
return items;
}
},
'mouse event handling', {
highlight: function(trueForLight) {
this.highlighted = trueForLight;
if (trueForLight) {
this.addStyleClassName('highlighted');
} else {
this.removeStyleClassName('highlighted');
}
},
isInFront: function() { return this.owner && this.owner.topMorph() === this },
isActive: function() {
return this.isInFront() && this.world() && this.highlighted;
},
comeForward: function() {
// adds the window before each other morph in owner
// this resets the scroll in HTML, fix for now -- gather before and set it afterwards
// step 1: highlight me and remove highlight from other windows
if (!this.isActive()) {
this.world().submorphs.forEach(function(ea) {
ea !== this && ea.isWindow && ea.highlight(false); }, this);
this.highlight(true);
}
var inner = this.targetMorph,
callGetsFocus = inner && !!inner.onWindowGetsFocus;
if (this.isInFront()) { if (callGetsFocus) { inner.onWindowGetsFocus(this); }; return; }
// step 2: make me the frontmost morph of the world
var scrolledMorphs = [], scrolls = [];
this.withAllSubmorphsDo(function(ea) {
var scroll = ea.getScroll();
if (!scroll[0] && !scroll[1]) return;
scrolledMorphs.push(ea); scrolls.push(scroll);
});
this.owner.addMorphFront(this); // come forward
this.alignAllHandles();
(function() {
scrolledMorphs.forEach(function(ea, i) { ea.setScroll(scrolls[i][0], scrolls[i][1]) });
if (callGetsFocus) { inner.onWindowGetsFocus(this); }
}).bind(this).delay(0);
},
onMouseDown: function(evt) {
var wasInFront = this.isActive();
if (wasInFront) return false; // was: $super(evt);
this.comeForward();
// rk 2013-04-27: disable accessibleInInactiveWindow test for now
// this test is not used and windows seem to work fine without it
// the code for that feature was:
// if (this.morphsContainingPoint(evt.getPosition()).detect(function(ea) {
// return ea.accessibleInInactiveWindow || true })) return false;
// this.cameForward = true; // for stopping the up as well
// evt.world.clickedOnMorph = null; // dont initiate drag, FIXME, global state!
// evt.stop(); // so that text, lists that are automatically doing things are not modified
// return true;
this.cameForward = true; // for stopping the up as well
return false;
},
onMouseUp: function(evt) {
if (!this.cameForward) return false;
this.cameForward = false;
return false;
},
wantsToBeDroppedInto: function(dropTarget) {
return dropTarget.isWorld;
}
},
'debugging', {
toString: function($super) {
return $super() + ' ' + (this.titleBar ? this.titleBar.getTitle() : '');
}
},
'removing', {
remove: function($super) {
// should trigger remove of submorphs but remove is also usedelsewhere (grab)
// this.targetMorph && this.targetMorph.remove();
return $super();
}
},
'collapsing', {
toggleCollapse: function() {
return this.isCollapsed() ? this.expand() : this.collapse();
},
collapse: function() {
if (this.isCollapsed()) return;
this.expandedTransform = this.getTransform();
this.expandedExtent = this.getExtent();
this.expandedPosition = this.getPosition();
this.targetMorph.onWindowCollapse && this.targetMorph.onWindowCollapse();
this.targetMorph.remove();
this.helperMorphs = this.submorphs.withoutAll([this.targetMorph, this.titleBar]);
this.helperMorphs.invoke('remove');
if(this.titleBar.lookCollapsedOrNot) this.titleBar.lookCollapsedOrNot(true);
var finCollapse = function () {
this.state = 'collapsed'; // Set it now so setExtent works right
if (this.collapsedTransform) this.setTransform(this.collapsedTransform);
if (this.collapsedExtent) this.setExtent(this.collapsedExtent);
if (this.collapsedPosition) this.setPosition(this.collapsedPosition);
this.shape.setBounds(this.titleBar.bounds());
}.bind(this);
if (this.collapsedPosition && this.collapsedPosition.dist(this.getPosition()) > 100)
this.animatedInterpolateTo(this.collapsedPosition, 5, 50, finCollapse);
else finCollapse();
},
expand: function() {
if (!this.isCollapsed()) return;
this.collapsedTransform = this.getTransform();
this.collapsedExtent = this.innerBounds().extent();
this.collapsedPosition = this.getPosition();
var finExpand = function () {
this.state = 'expanded';
if (this.expandedTransform)
this.setTransform(this.expandedTransform);
if (this.expandedExtent) {
this.setExtent(this.expandedExtent);
}
if (this.expandedPosition) {
this.setPosition(this.expandedPosition);
}
this.addMorph(this.targetMorph);
this.helperMorphs.forEach(function(ea) {
this.addMorph(ea)
}, this);
// Bring this window forward if it wasn't already
this.owner && this.owner.addMorphFront(this);
this.targetMorph.onWindowExpand && this.targetMorph.onWindowExpand();
}.bind(this);
if (this.expandedPosition && this.expandedPosition.dist(this.getPosition()) > 100)
this.animatedInterpolateTo(this.expandedPosition, 5, 50, finExpand);
else finExpand();
if(this.titleBar.lookCollapsedOrNot) this.titleBar.lookCollapsedOrNot(false);
}
});
lively.morphic.Box.subclass('lively.morphic.ReframeHandle',
'initializing', {
initialize: function($super, type, extent) {
// type is either "bottom" or "right" or "corner"
// FIXME refactor this into subclasses?
$super(extent.extentAsRectangle());
this.type = type;
this.addStyleClassName('reframe-handle ' + type);
var style = {};
if (this.type === 'right' || this.type === 'corner') { style.moveHorizontal = true; }
if (this.type === 'bottom' || this.type === 'corner') { style.moveVertical = true; }
this.applyStyle(style);
}
},
'event handling', {
onDragStart: function($super, evt) {
this.startDragPos = evt.getPosition();
this.originalTargetExtent = this.owner.getExtent();
evt.stop(); return true;
},
onDrag: function($super, evt) {
var moveDelta = evt.getPosition().subPt(this.startDragPos);
if (this.type === 'bottom') { moveDelta.x = 0; }
if (this.type === 'right') { moveDelta.y = 0; }
var newExtent = this.originalTargetExtent.addPt(moveDelta);
if (newExtent.x < this.owner.minWidth) newExtent.x = this.owner.minWidth;
if (newExtent.y < this.owner.minHeight) newExtent.y = this.owner.minHeight;
this.owner.setExtent(newExtent);
evt.stop(); return true;
},
onDragEnd: function($super, evt) {
delete this.originalTargetExtent;
delete this.startDragPos;
this.owner.alignAllHandles();
evt.stop(); return true;
}
},
'alignment', {
alignWithWindow: function() {
this.bringToFront();
var window = this.owner,
windowExtent = window.getExtent(),
handleExtent = this.getExtent(),
handleBounds = this.bounds();
if (this.type === 'corner') {
this.align(handleBounds.bottomRight(), windowExtent);
}
if (this.type === 'bottom') {
var newExtent = handleExtent.withX(windowExtent.x - window.reframeHandle.getExtent().x);
this.setExtent(newExtent);
this.align(handleBounds.bottomLeft(), windowExtent.withX(0));
}
if (this.type === 'right') {
var newExtent = handleExtent.withY(windowExtent.y - window.reframeHandle.getExtent().y);
this.setExtent(newExtent);
this.align(handleBounds.topRight(), windowExtent.withY(0));
}
}
});
Object.subclass('lively.morphic.App',
'properties', {
initialViewExtent: pt(350, 200)
},
'initializing', {
buildView: function(extent) {
throw new Error('buildView not implemented!');
}
},
'accessing', {
getInitialViewExtent: function(hint) {
return hint || this.initialViewExtent;
}
},
'opening', {
openIn: function(world, pos) {
var view = this.buildView(this.getInitialViewExtent());
view.ownerApp = this; // for debugging
this.view = view;
if (pos) view.setPosition(pos);
if (world.currentScene) world = world.currentScene;
return world.addMorph(view);
},
open: function() {
return this.openIn(lively.morphic.World.current());
}
},
'removing', {
removeTopLevel: function() {
if (this.view) this.view.remove();
}
});
lively.morphic.App.subclass('lively.morphic.AbstractDialog',
'documentation', {
connections: ['result']
},
'properties', {
doNotSerialize: ['lastFocusedMorph'],
initialViewExtent: pt(300, 90),
inset: 4
},
'initializing', {
initialize: function(message, callback) {
this.result = null;
this.message = message || '?';
if (callback) this.setCallback(callback);
},
openIn: function($super, owner, pos) {
this.lastFocusedMorph = lively.morphic.Morph.focusedMorph();
return $super(owner, pos);
},
buildPanel: function(bounds) {
this.panel = new lively.morphic.Box(bounds);
this.panel.applyStyle({
fill: Color.rgb(210,210,210),
borderColor: Color.gray.darker(),
borderWidth: 1,
adjustForNewBounds: true, // layouting
enableGrabbing: false,
enableDragging: false,
lock: true
});
},
buildLabel: function() {
var bounds = new lively.Rectangle(this.inset, this.inset,
this.panel.getExtent().x - 2*this.inset, 18);
this.label = new lively.morphic.Text(bounds, this.message).beLabel({
fill: Color.white,
fixedHeight: false, fixedWidth: false,
padding: Rectangle.inset(0,0),
enableGrabbing: false, enableDragging: false});
this.panel.addMorph(this.label);
// FIXME ugly hack for wide dialogs:
// wait until dialog opens and text is rendered so that we can
// determine its extent
this.label.fit();
(function fit() {
this.label.cachedBounds=null
var labelBoundsFit = this.label.bounds(),
origPanelExtent = this.panel.getExtent(),
panelExtent = origPanelExtent;
if (labelBoundsFit.width > panelExtent.x) {
panelExtent = panelExtent.withX(labelBoundsFit.width + 2*this.inset);
}
if (labelBoundsFit.height > bounds.height) {
var morphsBelowLabel = this.panel.submorphs.without(this.label).select(function(ea) {
return ea.bounds().top() <= labelBoundsFit.bottom(); }),
diff = labelBoundsFit.height - bounds.height;
panelExtent = panelExtent.addXY(0, diff);
}
this.panel.setExtent(panelExtent);
this.panel.moveBy(panelExtent.subPt(origPanelExtent).scaleBy(0.5).negated());
}).bind(this).delay(0);
},
buildCancelButton: function() {
var bounds = new Rectangle(0,0, 60, 30),
btn = new lively.morphic.Button(bounds, 'Cancel');
btn.align(btn.bounds().bottomRight().addXY(this.inset, this.inset), this.panel.innerBounds().bottomRight())
btn.applyStyle({moveHorizontal: true, moveVertical: true, padding: rect(pt(0,6),pt(0,6))})
this.cancelButton = this.panel.addMorph(btn);
lively.bindings.connect(btn, 'fire', this, 'removeTopLevel')
},
buildOKButton: function() {
var bounds = new Rectangle(0,0, 60, 30),
btn = new lively.morphic.Button(bounds, 'OK');
btn.align(btn.bounds().bottomRight().addXY(this.inset, 0), this.cancelButton.bounds().bottomLeft())
btn.applyStyle({moveHorizontal: true, moveVertical: true, padding: rect(pt(0,6),pt(0,6))})
this.okButton = this.panel.addMorph(btn);
lively.bindings.connect(btn, 'fire', this, 'removeTopLevel')
},
buildView: function(extent) {
this.buildPanel(extent.extentAsRectangle());
this.buildLabel();
this.buildCancelButton();
this.buildOKButton();
return this.panel;
},
},
'callbacks', {
setCallback: function(func) {
this.callback = func;
connect(this, 'result', this, 'triggerCallback')
},
triggerCallback: function(resultBool) {
this.removeTopLevel();
if (this.callback) this.callback(resultBool);
if (this.lastFocusedMorph) this.lastFocusedMorph.focus();
},
});
lively.morphic.AbstractDialog.subclass('lively.morphic.ConfirmDialog',
'properties', {
initialViewExtent: pt(260, 70),
},
'initializing', {
buildView: function($super, extent) {
var panel = $super(extent);
lively.bindings.connect(this.cancelButton, 'fire', this, 'result', {
converter: function() { return false; }});
lively.bindings.connect(this.okButton, 'fire', this, 'result', {
converter: function() { return true; }});
lively.bindings.connect(panel, 'onEscPressed', this, 'result', {
converter: function(evt) { Global.event && Global.event.stop(); return false; }});
lively.bindings.connect(panel, 'onEnterPressed', this, 'result', {
converter: function(evt) { Global.event && Global.event.stop(); return true; }});
return panel;
},
});
lively.morphic.AbstractDialog.subclass('lively.morphic.PromptDialog',
// new lively.morphic.PromptDialog('Test', function(input) { alert(input) }).open()
'initializing', {
initialize: function($super, label, callback, defaultInput) {
$super(label, callback, defaultInput);
this.defaultInput = defaultInput;
},
buildTextInput: function(bounds) {
var input = lively.BuildSpec("lively.ide.tools.CommandLine").createMorph();
input.textString = this.defaultInput || '';
input.setBounds(this.label.bounds().insetByPt(pt(this.label.getPosition().x * 2, 0)));
input.align(input.getPosition(), this.label.bounds().bottomLeft().addPt(pt(0,5)));
lively.bindings.connect(input, 'savedTextString', this, 'result');
lively.bindings.connect(input, 'onEscPressed', this, 'result', {converter: function() { return null } });
lively.bindings.connect(this.panel, 'onEscPressed', this, 'result', {converter: function() { return null}});
input.applyStyle({resizeWidth: true, moveVertical: true});
this.inputText = this.panel.addMorph(input);
},
buildView: function($super, extent) {
var panel = $super(extent);
this.buildTextInput();
lively.bindings.connect(this.cancelButton, 'fire', this, 'result', {
converter: function() { return null }});
lively.bindings.connect(this.okButton, 'fire', this.inputText, 'doSave')
return panel;
},
},
'opening', {
openIn: function($super, owner, pos) {
var view = $super(owner, pos);
// delayed because selectAll will scroll the world on text focus
// sometimes the final pos of the dialog is different to the pos here
// so dialog will open at wrong place, focus, world scrolls to the top,
// dialog is moved and out of frame
this.inputText.focus();
this.inputText.selectAll.bind(this.inputText).delay(0);
return view;
},
});
lively.morphic.AbstractDialog.subclass('lively.morphic.EditDialog',
// new lively.morphic.PromptDialog('Test', function(input) { alert(input) }).open()
'initializing', {
initialize: function($super, label, callback, defaultInput) {
$super(label, callback, defaultInput);
this.defaultInput = defaultInput;
},
buildTextInput: function() {
var bounds = rect(this.label.bounds().bottomLeft(), this.cancelButton.bounds().topRight()).insetBy(5),
input = lively.ide.newCodeEditor(bounds, this.defaultInput || '').applyStyle({
resizeWidth: true, moveVertical: true,
gutter: false, lineWrapping: true,
borderWidth: 1, borderColor: Color.gray.lighter(),
textMode: 'text'
});
input.setBounds(bounds);
this.inputText = this.panel.addMorph(input);
input.focus.bind(input).delay(0);
lively.bindings.connect(input, 'savedTextString', this, 'result');
},
buildView: function($super, extent) {
var panel = $super(extent);
panel.setExtent(pt(400,200))
this.buildTextInput();
lively.bindings.connect(this.cancelButton, 'fire', this, 'result', {
converter: function() { return null }});
lively.bindings.connect(this.okButton, 'fire', this.inputText, 'doSave')
return panel;
}
},
'opening', {
openIn: function($super, owner, pos) {
var view = $super(owner, pos);
// delayed because selectAll will scroll the world on text focus
// sometimes the final pos of the dialog is different to the pos here
// so dialog will open at wrong place, focus, world scrolls to the top,
// dialog is moved and out of frame
this.inputText.selectAll.bind(this.inputText).delay(0);
return view;
}
});
lively.morphic.App.subclass('lively.morphic.WindowedApp',
'opening', {
openIn: function(world, pos) {
var view = this.buildView(this.getInitialViewExtent()),
window = world.addFramedMorph(view, this.defaultTitle);
if (world.currentScene) world.currentScene.addMorph(window); // FIXME
view.ownerApp = this; // for debugging
this.view = window;
return window;
}
});
// COPIED from Widgets.js SelectionMorph
lively.morphic.Box.subclass('lively.morphic.Selection',
'documentation', {
documentation: 'selection "tray" object that allows multiple objects to be moved and otherwise manipulated simultaneously'
},
'settings', {
style: {fill: null, borderWidth: 1, borderColor: Color.darkGray},
isEpiMorph: true,
doNotRemove: true,
propagate: true,
isSelection: true,
},
'initializing', {
initialize: function($super, initialBounds) {
$super(initialBounds);
this.applyStyle(this.style);
this.selectedMorphs = [];
this.selectionIndicators = [];
this.setBorderStylingMode(true);
this.setAppearanceStylingMode(true);
},
},
'propagation', {
withoutPropagationDo: function(func) {
// emulate COP
this.propagate = false;
func.call(this);
this.propagate = true;
},
isPropagating: function() {
return this.propagate
},
},
'menu', {
morphMenuItems: function($super) {
var items = $super();
if (this.selectedMorphs.length === 1) {
var self = this;
items.push(["open ObjectEditor for selection", function(){
$world.openObjectEditorFor(self.selectedMorphs[0])
}])
}
items.push(["align vertically", this.alignVertically.bind(this)]);
items.push(["space vertically", this.spaceVertically.bind(this)]);
items.push(["align horizontally", this.alignHorizontally.bind(this)]);
items.push(["space horizontally", this.spaceHorizontally.bind(this)]);
if (this.selectedMorphs.length == 1) {
items.push(["ungroup", this.unGroup.bind(this)]);
} else {
items.push(["group", this.makeGroup.bind(this)]);
}
items.push(["align to grid...", this.alignToGrid.bind(this)]);
return items;
},
},
'copying', {
copy: function($super) {
this.isEpiMorph = false;
var selOwner = this.owner, copied;
try { copied = this.addSelectionWhile($super); } finally { this.isEpiMorph = true }
this.reset();
this.selectedMorphs = copied.selectedMorphs.clone();
copied.reset();
return this;
},
},
'selection handling', {
addSelectionWhile: function(func) {
// certain operations require selected morphs to be added to selection frame
// e.g. for transformations or copying
// use this method to add them for certain operations
var world = this.world();
if (!world || !this.isPropagating()) return func();
var owners = [];
for (var i = 0; i < this.selectedMorphs.length; i++) {
owners[i] = this.selectedMorphs[i].owner;
this.addMorph(this.selectedMorphs[i]);
}
try { return func() } finally {
for (var i = 0; i < this.selectedMorphs.length; i++)
owners[i].addMorph(this.selectedMorphs[i]);
}
},
},
'removing', {
remove: function() {
if (this.isPropagating())
this.selectedMorphs.invoke('remove');
this.removeOnlyIt();
},
removeOnlyIt: function() {
if (this.myWorld == null) {
this.myWorld = this.world();
}
// this.myWorld.currentSelection = null;
Class.getSuperPrototype(this).remove.call(this);
},
},
'accessing', {
world: function($super) {
return $super() || this.owner || this.myWorld
},
setBorderWidth: function($super, width) {
if (!this.selectedMorphs || !this.isPropagating()) $super(width);
else this.selectedMorphs.invoke('withAllSubmorphsDo',
function(ea) { ea.setBorderWidth(width)});
},
setFill: function($super, color) {
if (!this.selectedMorphs || !this.isPropagating())
$super(color);
else this.selectedMorphs.invoke('withAllSubmorphsDo',
function(ea) { ea.setFill(color)});
},
setBorderColor: function($super, color) {
if (!this.selectedMorphs || !this.isPropagating()) $super(color);
else this.selectedMorphs.invoke('withAllSubmorphsDo',
function(ea) { ea.setBorderColor(color)});
},
shapeRoundEdgesBy: function($super, r) {
if (!this.selectedMorphs || !this.isPropagating()) $super(r);
else this.selectedMorphs.forEach(
function(m) { if (m.shape.roundEdgesBy) m.shapeRoundEdgesBy(r); });
},
setFillOpacity: function($super, op) {
if (!this.selectedMorphs || !this.isPropagating()) $super(op);
else this.selectedMorphs.invoke('withAllSubmorphsDo',
function(ea) { ea.setFillOpacity(op)});
},
setStrokeOpacity: function($super, op) {
if (!this.selectedMorphs || !this.isPropagating()) $super(op);
else this.selectedMorphs.invoke('callOnAllSubmorphs',
function(ea) { ea.setStrokeOpacity(op)});
},
setTextColor: function(c) {
if (!this.selectedMorphs || !this.isPropagating()) return;
this.selectedMorphs.forEach( function(m) { if (m.setTextColor) m.setTextColor(c); });
},
setFontSize: function(c) {
if (!this.selectedMorphs || !this.isPropagating()) return;
this.selectedMorphs.forEach( function(m) { if (m.setFontSize) m.setFontSize(c); });
},
setFontFamily: function(c) {
if (!this.selectedMorphs || !this.isPropagating()) return;
this.selectedMorphs.forEach( function(m) { if (m.setFontFamily) m.setFontFamily(c); });
},
setRotation: function($super, theta) {
this.addSelectionWhile($super.curry(theta));
},
setScale: function($super, scale) {
this.addSelectionWhile($super.curry(scale));
},
adjustOrigin: function($super, origin) {
this.withoutPropagationDo(function() {
return $super(origin)
});
},
},
'aligning', {
// Note: the next four methods should be removed after we have gridding, i think (DI)
alignVertically: function() {
// Align all morphs to same left x as the top one.
//console.log("this=" + Object.inspect(this)); if(true) return;
var morphs = this.selectedMorphs.slice(0).sort(function(m,n) {return m.getPosition().y - n.getPosition().y});
var minX = morphs[0].getPosition().x; // align to left x of top morph
morphs.forEach(function(m) { m.setPosition(pt(minX,m.getPosition().y)) });
},
alignHorizontally: function() {
var minY = 9999;
this.selectedMorphs.forEach(function(m) { minY = Math.min(minY, m.getPosition().y); });
this.selectedMorphs.forEach(function(m) { m.setPosition(pt(m.getPosition().x, minY)) });
},
spaceVertically: function() {
// Sort the morphs vertically
var morphs = this.selectedMorphs.clone().sort(function(m,n) {return m.getPosition().y - n.getPosition().y});
// Align all morphs to same left x as the top one.
var minX = morphs[0].getPosition().x;
var minY = morphs[0].getPosition().y;
// Compute maxY and sumOfHeights
var maxY = minY;
var sumOfHeights = 0;
morphs.forEach(function(m) {
var ht = m.innerBounds().height;
sumOfHeights += ht;
maxY = Math.max(maxY, m.getPosition().y + ht);
});
// Now spread them out to fit old top and bottom with even spacing between
var separation = (maxY - minY - sumOfHeights)/Math.max(this.selectedMorphs.length - 1, 1);
var y = minY;
morphs.forEach(function(m) {
m.setPosition(pt(minX, y));
y += m.innerBounds().height + separation;
});
},
spaceHorizontally: function() {
// Sort the morphs vertically
var morphs = this.selectedMorphs.clone().sort(function(m, n) {
return m.getPosition().x - n.getPosition().x;
});
// Align all morphs to same left x as the top one.
var minX = morphs[0].getPosition().x;
var minY = morphs[0].getPosition().y;
// Compute maxX and sumOfWidths
var maxX = minY;
var sumOfWidths = 0;
morphs.forEach(function(m) {
var wid = m.innerBounds().width;
sumOfWidths += wid;
maxX = Math.max(maxX, m.getPosition().x + wid);
}); // Now spread them out to fit old top and bottom with even spacing between
var separation = (maxX - minX - sumOfWidths)/Math.max(this.selectedMorphs.length - 1, 1);
var x = minX;
morphs.forEach(function(m) {
m.setPosition(pt(x, minY));
x += m.innerBounds().width + separation;
});
},
alignToGrid: function() {
this.selectedMorphs.forEach(function(ea) {
ea.setPosition(ea.getPosition().roundTo(10));
});
}
},
'grabbing', {
grabByHand: function(hand) {
this.withoutPropagationDo(function() {
hand.addMorph(this);
for (var i = 0; i < this.selectedMorphs.length; i++) {
hand.addMorph(this.selectedMorphs[i]);
}
})
},
dropOn: function(morph) {
this.withoutPropagationDo(function() {
morph.addMorph(this);
for (var i = 0; i < this.selectedMorphs.length; i++) {
morph.addMorph(this.selectedMorphs[i]);
}
});
},
},
'geometry', {
moveBy: function($super, delta) {
// Jens: I would like to express this in a layer...
if (this.isPropagating()) {
for (var i = 0; i < this.selectedMorphs.length; i++ )
this.selectedMorphs[i].moveBy(delta);
}
$super(delta);
},
setPosition: function($super, pos) {
var delta = pos.subPt(this.getPosition())
// Jens: I would like to express this in a layer...
if (this.isPropagating() && this.selectedMorphs) {
for (var i = 0; i < this.selectedMorphs.length; i++ ) {
// alertOK("set pos move " + printStack())
this.selectedMorphs[i].moveBy(delta);
}
}
return $super(pos);
},
},
'world', {
reset: function() {
this.selectedMorphs = [];
this.setRotation(0)
this.setScale(1)
this.removeOnlyIt();
this.removeSelecitonIndicators();
this.adjustOrigin(pt(0,0));
},
selectMorphs: function(selectedMorphs) {
if (!this.owner) lively.morphic.World.current().addMorph(this);
this.selectedMorphs = selectedMorphs;
// add selection indicators for all selected morphs
this.removeSelecitonIndicators();
selectedMorphs.forEach(function(ea) {
var innerBounds = ea.getTransform().inverse().transformRectToRect(ea.bounds().insetBy(-4)),
bounds = ea.getTransform().transformRectToRect(innerBounds),
selectionIndicator = new lively.morphic.Morph.makeRectangle(innerBounds);
selectionIndicator.name = 'Selection of ' + ea;
selectionIndicator.isEpiMorph = true;
selectionIndicator.isSelectionIndicator = true;
selectionIndicator.setBorderStylingMode(true);
selectionIndicator.setAppearanceStylingMode(true);
selectionIndicator.addStyleClassName('selection-indicator');
ea.addMorph(selectionIndicator);
this.selectionIndicators.push(selectionIndicator);
}, this);
// resize selection morphs so ot fits selection indicators
var bnds = this.selectionIndicators.invoke('globalBounds'),
selBounds = bnds.slice(1).inject(bnds[0], function(bounds, selIndicatorBounds) {
return bounds.union(selIndicatorBounds); });
this.withoutPropagationDo(function() { this.setBounds(selBounds); });
},
removeSelecitonIndicators: function() {
if (this.selectionIndicators)
this.selectionIndicators.invoke('remove');
this.selectionIndicators.clear();
},
makeGroup: function() {
if (!this.selectedMorphs) return;
var group = new lively.morphic.Box(this.bounds());
group.isGroup = true;
this.owner.addMorph(group);
this.selectedMorphs.forEach(function(ea) {
group.addMorph(ea); });
this.selectMorphs([group]);
return group;
},
unGroup: function() {
if (!this.selectedMorphs || this.selectedMorphs.length !== 1) return;
var group = this.selectedMorphs[0]
var all = group.submorphs
group.submorphs.forEach(function(ea) {
this.owner.addMorph(ea)
}.bind(this))
this.selectMorphs(all)
},
},
'keyboard events', {
doKeyCopy: function() {
if (!this.selectedMorphs.length) return;
var copies = this.selectedMorphs.invoke('copy'),
carrier = lively.morphic.Morph.makeRectangle(0,0,1,1);
carrier.isMorphClipboardCarrier = true;
copies.forEach(function(ea) {
carrier.addMorph(ea);
ea.setPosition(this.localize(ea.getPosition()));
}, this);
carrier.doKeyCopy();
}
});
Trait('SelectionMorphTrait',
'selection', {
getSelectedMorphs: function() {
return this.selectionMorph.selectedMorphs
},
setSelectedMorphs: function(morphs) {
if (!morphs || morphs.length === 0) { this.resetSelection(); return; }
if (!this.selectionMorph) this.resetSelection();
this.selectionMorph.selectMorphs(morphs);
this.selectionMorph.showHalos();
return morphs;
},
hasSelection: function() {
return this.selectionMorph && !!this.selectionMorph.owner;
},
onDragStart: function(evt) {
if (evt.isRightMouseButtonDown()) {
return; // no selection with right mouse button (fbo 2011-09-13)
}
this.resetSelection()
if (this.selectionMorph.owner !== this)
this.addMorph(this.selectionMorph);
var pos = this.localize(this.eventStartPos || evt.getPosition());
this.selectionMorph.withoutPropagationDo(function() {
this.selectionMorph.setPosition(pos)
this.selectionMorph.setExtent(pt(1, 1))
this.selectionMorph.initialPosition = pos;
}.bind(this))
},
onDrag: function(evt) {
if (!this.selectionMorph) return
var p1 = this.localize(evt.getPosition()),
p2 = this.selectionMorph.initialPosition;
// alert("p1" + p1 + " p2" + p2)
var topLeft = pt(Math.min(p1.x, p2.x), Math.min(p1.y, p2.y))
var bottomRight = pt(Math.max(p1.x, p2.x), Math.max(p1.y, p2.y))
this.selectionMorph.setPosition(topLeft);
this.selectionMorph.setExtent(bottomRight.subPt(topLeft));
},
onDragEnd: function(evt) {
var self = this;
if (!self.selectionMorph) return;
var selectionBounds = self.selectionMorph.bounds();
var selectedMorphs = this.submorphs
.reject(function(ea){
return ea === self || ea.isEpiMorph || ea instanceof lively.morphic.HandMorph
})
.select(function(m) {
return selectionBounds.containsRect(m.bounds())})
.reverse()
this.selectionMorph.selectedMorphs = selectedMorphs;
if (selectedMorphs.length == 0) {
this.selectionMorph.removeOnlyIt();
return
}
this.selectionMorph.selectMorphs(selectedMorphs);
this.selectionMorph.showHalos()
},
resetSelection: function() {
if (!this.selectionMorph || !this.selectionMorph.isSelection)
this.selectionMorph = new lively.morphic.Selection(new Rectangle(0,0,0,0))
this.selectionMorph.reset();
},
})
.applyTo(lively.morphic.World, {override: ['onDrag', 'onDragStart', 'onDragEnd']});
module('lively.ide'); // so that the namespace is defined even if ide is not loaded
Object.extend(lively.ide, {
openFile: function(url) {
require('lively.ide.tools.TextEditor').toRun(function() {
var editor = lively.BuildSpec('lively.ide.tools.TextEditor').createMorph();
if (url) {
if (!String(url).startsWith('http')) url = URL.codeBase.withFilename(url);
editor.openURL(url);
}
editor.openInWorld($world.positionForNewMorph(editor)).comeForward();
});
}
});
lively.morphic.Box.subclass('lively.morphic.HorizontalDivider',
'settings', {
style: {fill: Color.gray, enableDragging: true},
},
'initializing', {
initialize: function($super, bounds) {
$super(bounds);
this.fixed = [];
this.scalingBelow = [];
this.scalingAbove = [];
this.minHeight = 20;
this.pointerConnection = null;
},
},
'mouse events', {
onDragStart: function(evt) {
this.oldPoint = evt.getPosition();
return true;
},
onDrag: function(evt) {
var p1 = this.oldPoint,
p2 = evt.getPosition(),
deltaY = p2.y - p1.y;
this.oldPoint = p2;
this.movedVerticallyBy(deltaY);
return true;
},
correctForDragOffset: Functions.False
},
'internal slider logic', {
divideRelativeToParent: function(ratio) {
// 0 <= ratio <= 1. Set divider so that it divides its owner by ration.
// |--------| |--------| |<======>|
// | | | | | |
// | | | | | |
// |<======>| = 0.5 | | = 1 | | = 0
// | | | | | |
// | | | | | |
// |--------| |<======>| |--------|
if (!this.owner || !Object.isNumber(ratio) || ratio < 0 || ratio > 1) return;
var ownerHeight = this.owner.getExtent().y - this.getExtent().y;
if (ownerHeight < 0) return;
var currentRatio = this.getRelativeDivide(),
deltaRation = ratio - currentRatio,
deltaY = ownerHeight * deltaRation;
this.movedVerticallyBy(deltaY);
},
getRelativeDivide: function(ratio) {
var bounds = this.bounds(),
myTop = bounds.top(),
myHeight = bounds.height,
ownerHeight = this.owner.getExtent().y - myHeight;
if (ownerHeight < 0) return NaN;
return myTop / ownerHeight;
},
movedVerticallyBy: function(deltaY) {
if (!this.resizeIsSave(deltaY)) return;
var morphsForPosChange = this.fixed.concat(this.scalingBelow);
morphsForPosChange.forEach(function(m) {
var pos = m.getPosition();
m.setPosition(pt(pos.x, pos.y + deltaY));
});
this.scalingAbove.forEach(function(m) {
var ext = m.getExtent();
m.setExtent(pt(ext.x, ext.y + deltaY));
});
this.scalingBelow.forEach(function(m) {
var ext = m.getExtent();
m.setExtent(pt(ext.x, ext.y - deltaY));
});
this.setPosition(this.getPosition().addPt(pt(0, deltaY)));
},
resizeIsSave: function(deltaY) {
return this.scalingAbove.all(function(m) { return (m.getExtent().y + deltaY) >= this.minHeight }, this)
&& this.scalingBelow.all(function(m) { return (m.getExtent().y - deltaY) >= this.minHeight }, this);
},
addFixed: function(m) { if (!this.fixed.include(m)) this.fixed.push(m) },
addScalingAbove: function(m) { this.scalingAbove.push(m) },
addScalingBelow: function(m) { this.scalingBelow.push(m) }
});
lively.morphic.Box.subclass('lively.morphic.Slider',
'settings', {
style: {
borderColor: Color.darkGray,
borderWidth: 1,
borderRadius: 6,
fill: Styles.sliderBackgroundGradient(Color.gray, "NorthSouth")
},
connections: {
value: {}
},
mss: 12, // "minimum slider size"
isSlider: true
},
'initializing', {
initialize: function($super, initialBounds, scaleIfAny) {
$super(initialBounds);
connect(this, 'value', this, 'adjustSliderParts');
this.setValue(0);
this.setSliderExtent(0.1);
this.valueScale = (scaleIfAny === undefined) ? 1.0 : scaleIfAny;
this.sliderKnob = this.addMorph(
new lively.morphic.SliderKnob(new Rectangle(0, 0, this.mss, this.mss), this));
this.adjustSliderParts();
this.sliderKnob.setAppearanceStylingMode(true);
this.sliderKnob.setBorderStylingMode(true);
this.setAppearanceStylingMode(true);
this.setBorderStylingMode(true);
},
},
'accessing', {
getValue: function() { return this.value },
setValue: function(value) { return this.value = value },
getScaledValue: function() {
var v = (this.getValue() || 0); // FIXME remove 0
if (Object.isNumber(this.min) && Object.isNumber(this.max)) {
return (v-this.min)/(this.max-this.min);
} else {
return v / this.valueScale;
}
},
setScaledValue: function(value) {
if (Object.isNumber(this.min) && Object.isNumber(this.max)) {
return this.setValue((this.max-this.min)*value + this.min);
} else {
return this.setValue(value * this.valueScale);
}
},
getSliderExtent: function() { return this.sliderExtent },
setSliderExtent: function(value) {
this.sliderExtent = value
this.adjustSliderParts();
return value;
},
setExtent: function($super, value) {
$super(value);
this.adjustSliderParts();
return value;
},
},
'mouse events', {
onMouseDown: function(evt) {
// FIXME: a lot of this is handled in Morph>>onMouseDown. remove.
if (!evt.isLeftMouseButtonDown() || evt.isCommandKey()) return false;
var handPos = this.localize(evt.getPosition());
if (this.sliderKnob.bounds().containsPoint(handPos)) return false; // knob handles move
if (!this.innerBounds().containsPoint(handPos)) return false; // don't involve, eg, pins
var inc = this.getSliderExtent(),
newValue = this.getValue(),
delta = handPos.subPt(this.sliderKnob.bounds().center());
if (this.vertical() ? delta.y > 0 : delta.x > 0) newValue += inc;
else newValue -= inc;
if (isNaN(newValue)) newValue = 0;
this.setScaledValue(this.clipValue(newValue));
return true;
}
},
'slider logic', {
vertical: function() {
var bnds = this.shape.bounds();
return bnds.height > bnds.width;
},
clipValue: function(val) {
return Math.min(1.0,Math.max(0,0,val.roundTo(0.0001)));
}
},
'layouting', {
adjustSliderParts: function() {
if (!this.sliderKnob) return;
// This method adjusts the slider for changes in value as well as geometry
var val = this.getScaledValue(),
bnds = this.shape.bounds(),
ext = this.getSliderExtent();
if (this.vertical()) { // more vertical...
var elevPix = Math.max(ext*bnds.height, this.mss), // thickness of elevator in pixels
topLeft = pt(0, (bnds.height - elevPix)*val),
sliderExt = pt(bnds.width, elevPix);
} else { // more horizontal...
var elevPix = Math.max(ext*bnds.width, this.mss), // thickness of elevator in pixels
topLeft = pt((bnds.width - elevPix)*val, 0),
sliderExt = pt(elevPix, bnds.height);
}
this.sliderKnob.setBounds(bnds.topLeft().addPt(topLeft).extent(sliderExt));
this.adjustFill();
},
adjustFill: function() {this.setupFill();},
setupFill: function() {
if (this.vertical()) {
this.addStyleClassName('vertical');
} else {
this.removeStyleClassName('vertical');
}
}
})
// FIXME move somewhere else
lively.morphic.Box.subclass('lively.morphic.SliderKnob',
'settings', {
style: {borderColor: Color.black, borderWidth: 1, fill: Color.gray, enableDragging: true},
dragTriggerDistance: 0,
isSliderKnob: true
},
'initializing', {
initialize: function($super, initialBounds, slider) {
$super(initialBounds);
this.slider = slider;
},
},
'mouse events', {
onDragStart: function($super, evt) {
this.hitPoint = this.owner.localize(evt.getPosition());
return true;
},
onDrag: function($super, evt) {
// the hitpoint is the offset that make the slider move smooth
if (!this.hitPoint) return; // we were not clicked on...
// Compute the value from a new mouse point, and emit it
var delta = this.owner.localize(evt.getPosition()).subPt(this.hitPoint),
p = this.bounds().topLeft().addPt(delta),
bnds = this.slider.innerBounds(),
ext = this.slider.getSliderExtent();
this.hitPoint = this.owner.localize(evt.getPosition());
if (this.slider.vertical()) {
// thickness of elevator in pixels
var elevPix = Math.max(ext*bnds.height,this.slider.mss),
newValue = p.y / (bnds.height-elevPix);
} else {
// thickness of elevator in pixels
var elevPix = Math.max(ext*bnds.width,this.slider.mss),
newValue = p.x / (bnds.width-elevPix);
}
if (isNaN(newValue)) newValue = 0;
this.slider.setScaledValue(this.slider.clipValue(newValue));
},
onDragEnd: function($super, evt) { return $super(evt) },
onMouseDown: function(evt) {
return true;
},
});
Object.extend(Array.prototype, {
asListItemArray: function() {
return this.collect(function(ea) {
return {isListItem: true, string: ea.toString(), value: ea};
});
}
})
lively.morphic.Box.subclass('lively.morphic.Tree',
'documentation', {
example: function() {
var tree = new lively.morphic.Tree();
tree.openInHand();
tree.setItem({
name: "root",
children: [
{name: "item 1", children: [{name: "subitem"}]},
{name: "item 2"}]
});
}
},
'initializing', {
initialize: function($super, item, optParent, optDragAndDrop) {
this.item = item;
this.parent = optParent;
this.depth = this.parent ? this.parent.depth + 1 : 0;
$super(pt(0, 0).extent(pt(300,20)));
this.initializeLayout();
this.disableDragging();
if (!optDragAndDrop && !(this.parent && this.parent.dragAndDrop)) {
this.disableDropping();
this.disableGrabbing();
} else {
this.dragAndDrop = true;
}
if (item) this.setItem(item);
},
initializeLayout: function() {
this.setFill(Color.white);
this.setBorderWidth(0);
this.setBorderColor(Color.black);
if (!this.layout) this.layout = {};
this.layout.resizeWidth = true;
this.setLayouter(new lively.morphic.Layout.TreeLayout(this));
},
initializeNode: function() {
var bounds = pt(0,0).extent(pt(200,20));
var node = new lively.morphic.Box(bounds);
node.ignoreEvents();
if (!node.layout) node.layout = {};
node.layout.resizeWidth = true;
var layouter = new lively.morphic.Layout.HorizontalLayout(node);
layouter.setSpacing(5);
layouter.setBorderSize(0);
node.setLayouter(layouter);
if (!node.layout) node.layout = {};
node.layout.resizeWidth = true;
this.icon = node.addMorph(this.createIcon());
this.label = node.addMorph(this.createLabel());
this.node = this.addMorph(node);
}
},
"accessing", {
getRootTree: function() {
return this.parent? this.parent.getRootTree() : this;
},
setItem: function(item) {
this.layoutAfter(function() {
this.item = item;
lively.bindings.connect(item, "changed", this, "update");
this.submorphs.invoke("remove");
this.childNodes = null;
if (!item.name) {
if (item.children) this.expand();
} else {
this.initializeNode();
}
});
}
},
'updating', {
update: function() {
this.updateItem(this.item);
},
updateItem: function(item) {
if (this.item !== item) {
var oldItem = this.item;
if (oldItem) {
lively.bindings.disconnect(oldItem, "changed", this, "update");
}
this.item = item;
if (item == null) { this.remove(); return; }
lively.bindings.connect(item, "changed", this, "update");
} else {
if (item.onUpdate) item.onUpdate(this);
}
if (this.childNodes) {
if (item.onUpdateChildren) item.onUpdateChildren(this);
this.updateChildren();
}
this.updateNode();
},
updateNode: function() {
if (this.node) {
this.updateIcon();
this.updateLabel();
}
},
updateIcon: function() {
var str = this.item.children ? "►" : "";
if (this.childNodes) str = "▼";
if (this.icon.textString !== str) this.icon.textString = str;
},
updateLabel: function() {
var str = this.item.name, changed = false;
if (this.item.description) str += " " + this.item.description;
if (this.label.textString !== str) {
this.label.textString = this.item.name;
if (this.item.description) {
var gray = {color: Color.web.darkgray};
this.label.appendRichText(" " + this.item.description, gray);
}
changed = true;
}
if (this.item.style && this.item.style !== this.label.oldStyle) {
this.label.firstTextChunk().styleText(this.item.style);
this.label.oldStyle = this.item.style;
changed = true;
}
var isSelected = this.label.getFill() !== null;
if (isSelected && !this.item.isSelected)
this.label.setFill(null);
if (!isSelected && this.item.isSelected)
this.label.setFill(Color.rgb(218, 218, 218));
if (changed) this.label.fit();
},
updateChildren: function() {
if (!this.childNodes) return;
var oldChildren = this.childNodes.map(function(n) { return n.item; });
var toRemove = oldChildren.withoutAll(this.item.children);
for (var i = 0; i < this.childNodes.length; i++) {
var node = this.childNodes[i];
if (toRemove.include(node.item)) {
node.remove();
this.childNodes.removeAt(i--);
}
}
var pageSize = this.childrenPerPage ? this.childrenPerPage : 100;
var currentInterval = Math.ceil(this.childNodes.length / pageSize) * pageSize;
currentInterval = Math.max(currentInterval , 100);
var numChildren = this.item.children ? this.item.children.length : 0;
var childrenToShow = Math.min(numChildren, currentInterval);
for (var j = 0; j < childrenToShow; j++) {
var item = this.item.children[j];
if (this.childNodes.length > j && this.childNodes[j].item === item) {
this.childNodes[j].update();
} else {
var newNode = this.createNodeBefore(item, this.childNodes[j]);
this.childNodes.pushAt(newNode, j);
}
}
if (!this.item.children) delete this.childNodes;
}
},
'creating', {
createIcon: function() {
var bounds = pt(0, 0).extent(pt(10, 20));
var str = this.item.children ? "►" : "";
var icon = new lively.morphic.Text(bounds, str);
icon.setBorderWidth(0);
icon.setFill(null);
icon.disableDragging();
icon.disableGrabbing();
icon.setInputAllowed(false);
icon.setHandStyle('default');
icon.setAlign("right");
icon.addScript(function onMouseDown(evt) {
if (this.owner.owner.item.children && evt.isLeftMouseButtonDown()) {
this.owner.owner.toggle();
}
});
return icon;
},
createLabel: function() {
var bounds = pt(0, 0).extent(pt(100, 20));
var label = new lively.morphic.Text(bounds);
label.setBorderWidth(0);
label.setFill(null);
label.disableDragging();
label.disableGrabbing();
label.setInputAllowed(false);
label.setHandStyle('default');
label.setWhiteSpaceHandling('pre');
label.setFixedWidth(false);
label.setFixedHeight(true);
label.addScript(function onMouseDown(evt) {
if (evt.isLeftMouseButtonDown() && this.owner.owner.item.onSelect) {
this.owner.owner.getRootTree().select(this.owner.owner);
}
});
if (this.item.isSelected) {
label.setFill(Color.rgb(218, 218, 218));
}
label.textString = this.item.name;
if (this.item.style) {
label.emphasizeAll(this.item.style);
label.oldStyle = this.item.style;
}
if (this.item.description) {
var gray = {color: Color.web.darkgray};
label.appendRichText(' ' + this.item.description, gray);
}
return label;
},
createNodeBefore: function(item, optOtherNode) {
var node = new lively.morphic.Tree(item, this);
node.childrenPerPage = this.childrenPerPage;
this.addMorph(node, optOtherNode);
return node;
},
},
'tree', {
isChild: function() {
return this.parent && this.parent.node;
},
showChildren: function() {
var that = this;
this.childNodes = [];
if (!this.item.children) return;
this.showMoreChildren();
},
showMoreChildren: function() {
this.layoutAfter(function() {
var childrenToShow = this.item.children.slice(
this.childNodes.length,
this.childNodes.length + (this.childrenPerPage ? this.childrenPerPage : 100));
if (this.showMoreNode) this.showMoreNode.remove();
this.showMoreNode = null;
var start = this.childNodes.length === 0 ? this : this.childNodes.last();
childrenToShow.each(function(currentItem) {
var node = this.createNodeBefore(currentItem);
this.childNodes.push(node);
}, this);
if (this.childNodes.length < this.item.children.length) {
var more = {name: "", description: "[show more]",
onSelect: this.showMoreChildren.bind(this)};
this.showMoreNode = this.createNodeBefore(more);
}
});
},
expand: function() {
if (!this.item.children || this.childNodes) return;
this.layoutAfter(function () {
if (this.item.onExpand) this.item.onExpand(this);
if (this.icon) this.icon.setTextString("▼");
this.showChildren();
})
},
expandAll: function() {
this.withAllTreesDo(function(tree) {
tree.expand();
});
},
collapse: function() {
if (!this.item.children || !this.childNodes) return;
this.layoutAfter(function() {
if (this.item.onCollapse) this.item.onCollapse(this.item);
if (this.icon) this.icon.setTextString("►");
if (this.childNodes) this.childNodes.invoke("remove");
this.childNodes = null;
if (this.showMoreNode) this.showMoreNode.remove();
this.showMoreNode = null;
});
},
toggle: function() {
this.childNodes ? this.collapse() : this.expand();
},
select: function(tree) {
this.withAllTreesDo(function(t) {
if (t.item.isSelected) {
delete t.item.isSelected;
t.label.setFill(null);
}
});
if (tree) {
tree.label.setFill(Color.rgb(218, 218, 218));
tree.item.isSelected = true;
tree.item.onSelect(tree);
}
},
layoutAfter: function(callback) {
var layouter = this.getLayouter();
try {
layouter && layouter.defer();
callback.call(this);
} finally {
layouter && layouter.resume();
}
}
},
'editing', {
edit: function() { console.warn('editing tree node label not supported yet'); },
editDescription: function() {
this.label.textString = this.item.name + (this.item.description ? " " : "");
this.label.growOrShrinkToFit();
var bounds = pt(0,0).extent(pt(160, 20));
var edit = new lively.morphic.Text(bounds, this.item.description);
edit.isInputLine = true;
edit.setClipMode("hidden");
edit.setFixedHeight(true);
edit.setFixedWidth(true);
edit.setBorderWidth(0);
edit.onEnterPressed = edit.onEscPressed;
this.node.addMorph(edit);
edit.growOrShrinkToFit();
edit.onBlur = function() { this.finishEditingDescription(edit); }.bind(this);
(function() { edit.focus(); edit.selectAll(); }).delay(0);
},
finishEditingDescription: function(edit) {
if (this.item.onEdit) this.item.onEdit(edit.textString);
edit.remove();
this.updateLabel();
}
},
'enumerating', {
withAllTreesDo: function(iter, context, depth) {
// only iterates through expanded childNodes, not necessarily through
// all item children! See #withAllItemsDo
if (!depth) depth = 0;
var result = iter.call(context || Global, this, depth);
if (!this.childNodes) return [result];
return [result].concat(
this.childNodes.invoke("withAllTreesDo", iter, context, depth + 1));
},
withAllItemsDo: function(iter, context) {
function visitItem(item, depth) {
var result = iter.call(context || Global, item, depth);
if (!item.children) return [result];
return item.children.inject([result], function(all, ea) {
return all.concat(visitItem(ea, depth + 1)); });
}
return this.item && visitItem(this.item, 0);
}
});
}) // end of module
| core/lively/morphic/Widgets.js | module('lively.morphic.Widgets').requires('lively.morphic.Core', 'lively.morphic.Events', 'lively.morphic.TextCore', 'lively.morphic.Styles').toRun(function() {
lively.morphic.Morph.subclass('lively.morphic.Button',
'settings', {
isButton: true,
normalColor: Color.rgbHex('#DDDDDD'),
toggleColor: Color.rgb(171,215,248),
disabledColor: Color.rgbHex('#DDDDDD'),
normalTextColor: Color.black,
disabledTextColor: Color.rgbHex('#999999'),
style: {
enableGrabbing: false,
enableDropping: false,
borderColor: Color.neutral.lightGray,
borderWidth: 1,
borderRadius: 5,
padding: Rectangle.inset(0,3),
label: {
borderWidth: 0,
fill: null,
padding: Rectangle.inset(0,3),
fontSize: 10,
align: 'center',
fixedWidth: true,
fixedHeight: true,
textColor: Color.black,
clipMode: 'hidden',
emphasize: {textShadow: {offset: pt(0,1), color: Color.white}},
allowInput: false
}
}
},
'initializing', {
initialize: function($super, bounds, labelString) {
$super(this.defaultShape());
if (bounds) this.setBounds(bounds);
this.value = false;
this.toggle = false;
this.isActive = true;
this.changeAppearanceFor(false, false);
this.ensureLabel(labelString);
this.setAppearanceStylingMode(true);
this.setBorderStylingMode(true);
},
ensureLabel: function(labelString) {
if (!this.label) {
this.label = new lively.morphic.Text(this.getExtent().extentAsRectangle(), labelString);
} else {
this.label.setBounds(this.getExtent().extentAsRectangle());
this.label.textString = labelString;
}
if (this.label.owner !== this) {
this.addMorph(this.label);
}
this.label.beLabel(this.style.label);
this.label.setTextStylingMode(true);
this.label.disableEvents();
return this.label;
},
},
'accessing', {
setLabel: function(label) {
this.label.setTextString(label);
this.label.setExtent(this.getExtent());
this.label.applyStyle(this.style.label);
return this;
},
getLabel: function(label) { return this.label.textString },
setActive: function(bool) {
this.isActive = bool;
this.updateAppearance();
},
setValue: function(bool) {
this.value = bool;
// buttons should fire on mouse up
if (!bool || this.toggle) lively.bindings.signal(this, 'fire', bool);
},
setExtent: function($super, extent) {
// FIXME use layout! spaceFill!
$super(extent);
this.label && this.label.setExtent(extent)
},
setPadding: function(padding) { this.label && this.label.setPadding(padding); },
setToggle: function(optBool) {
this.toggle = (optBool === undefined)? true : optBool;
return this.toggle
}
},
'styling', {
updateAppearance: function(){
this.changeAppearanceFor(this.isPressed, this.value);
},
changeAppearanceFor: function(pressed, toggled) {
if (this.isActive) {
this.removeStyleClassName('disabled');
var isToggled = toggled || this.value;
if (isToggled) {
this.addStyleClassName('toggled');
} else {
this.removeStyleClassName('toggled');
}
if (pressed) {
this.addStyleClassName('pressed');
} else {
this.removeStyleClassName('pressed');
}
if (this.style && this.style.label && this.style.label.padding) {
var labelPadding = pressed ? this.style.label.padding.withY(this.style.label.padding.y+1):this.style.label.padding;
this.setPadding(labelPadding);
}
if (this.label)
this.label.setExtent(this.getExtent())
} else {
this.addStyleClassName('disabled');
this.removeStyleClassName('toggled');
this.removeStyleClassName('pressed');
}
},
applyStyle: function($super, spec) {
if (spec.label && this.label) {
this.label.applyStyle(spec.label);
}
return $super(spec);
},
generateFillWith: function(color, shade, upperCenter, lowerCenter, bottomShade){
return new lively.morphic.LinearGradient(
[{offset: 0, color: color.mixedWith(shade, 0.2)},
{offset: upperCenter || 0.3, color: color},
{offset: lowerCenter || 0.7, color: color},
{offset: 1, color: color.mixedWith(bottomShade|| shade, 0.2)}],
"NorthSouth");
}
},
'events', {
isValidEvent: function(evt) {
if (!this.isActive) return false;
if (evt.isLeftMouseButtonDown() && !evt.isCommandKey()) return true;
if (evt.isKeyboardEvent && evt.keyCode === Event.KEY_RETURN) return true;
return false;
},
onMouseOut: function (evt) {
this.isPressed && this.changeAppearanceFor(false);
},
onMouseOver: function (evt) {
if (evt.isLeftMouseButtonDown()) {
this.isPressed && this.changeAppearanceFor(true);
} else {
this.isPressed = false;
}
},
onMouseDown: function (evt) {
if (this.isValidEvent(evt) && this.isActive) {
this.activate();
}
return false;
},
onMouseUp: function(evt) {
if (this.isValidEvent(evt) && this.isPressed) {
this.deactivate();
}
return false;
},
onKeyDown: function(evt) {
if (this.isValidEvent(evt) && this.isActive) {
this.activate();
}
return false;
},
onKeyUp: function(evt) {
if (this.isValidEvent(evt) && this.isPressed) {
this.deactivate();
}
return false;
},
simulateButtonClick: function() {
var world = this.world() || lively.morphic.World.current(),
hand = world.firstHand();
function createEvent() {
return {
isLeftMouseButtonDown: Functions.True,
isRightMouseButtonDown: Functions.False,
isCommandKey: Functions.False,
isAltDown: Functions.False,
world: world,
hand: hand,
getPosition: function() { return hand.getPosition() }
}
}
this.onMouseDown(createEvent());
this.onMouseUp(createEvent());
},
activate: function() {
this.isPressed = true;
this.changeAppearanceFor(true);
},
deactivate: function() {
var newValue = this.toggle ? !this.value : false;
this.setValue(newValue);
this.changeAppearanceFor(false);
this.isPressed = false;
}
},
'menu', {
morphMenuItems: function($super) {
var self = this, items = $super();
items.push([
'Set label', function(evt) {
$world.prompt('Set label', function(input) {
if (input !== null)
self.setLabel(input || '');
}, self.getLabel());
}])
return items;
}
});
lively.morphic.Button.subclass('lively.morphic.ImageButton',
'initializing', {
initialize: function($super, bounds, url) {
//if (bounds) this.setBounds(bounds);
$super(bounds, '');
this.image = new lively.morphic.Image(this.getExtent().extentAsRectangle(), url, true);
this.addMorph(this.image);
this.image.ignoreEvents();
this.image.disableHalos();
},
},
'accessing', {
setImage: function(url) {
this.image.setImageURL(url);
return this;
},
getImage: function() { return this.image.getImageURL() },
setImageOffset: function(padding) { this.image && this.image.setPosition(padding) },
},
'menu', {
morphMenuItems: function($super) {
var self = this, items = $super();
items.push([
'Set image', function(evt) {
$world.prompt('Set image URL', function(input) {
if (input !== null)
self.setImage(input || '');
}, self.getImage());
}])
return items;
},
});
lively.morphic.ImageButton.subclass('lively.morphic.ImageOptionButton',
'buttonstuff', {
setValue: function(bool) {
this.value = bool;
this.changeAppearanceFor(bool);
},
onMouseDown: function (evt) {
if (this.isActive && evt.isLeftMouseButtonDown()
&& !this.value && !evt.isCommandKey()) {
this.changeAppearanceFor(true);
}
},
onMouseUp: function(evt) {
if (this.isActive && evt.isLeftMouseButtonDown()
&& !evt.isCommandKey() && !this.value && this.otherButtons) {
this.setValue(true);
this.otherButtons.each(function(btn){btn.setValue(false);});
return false;
}
return false;
},
setOtherButtons: function(morphs) {
var otherButtons = [];
if (morphs.first()) { // if the list is empty, apply the empty list
if (morphs.first().toUpperCase) { // if the list contains strings, get the morphs first
var t = this;
morphs.each(function(btn){
var a = t.get(btn);
a && a.setOtherButtons && otherButtons.push(a);
});
} else {
otherButtons = morphs;
}
}
this.otherButtons = otherButtons;
},
});
lively.morphic.Morph.subclass('lively.morphic.Image',
'initializing', {
initialize: function($super, bounds, url, useNativeExtent) {
var imageShape = this.defaultShape(bounds.extent().extentAsRectangle(), url);
$super(imageShape);
this.setPosition(bounds.topLeft());
this.setImageURL(url, useNativeExtent);
},
defaultShape: function(bounds, url) {
url = url || '';
return new lively.morphic.Shapes.Image(bounds, url);
}
},
'accessing', {
setImageURL: function(url, useNativeExtent) {
if (!url) return null;
if (useNativeExtent) {
connect(this.shape, 'isLoaded', this, 'setNativeExtent',
{removeAfterUpdate: true});
} else {
connect(this.shape, 'isLoaded', this, 'setExtent',
{removeAfterUpdate: true, converter: function() {
return this.targetObj.getExtent(); }});
}
return this.shape.setImageURL(url);
},
getImageURL: function() { return this.shape.getImageURL() },
getNativeExtent: function() { return this.shape.getNativeExtent() },
setNativeExtent: function() {
var ext = this.getNativeExtent();
// FIXME magic numbers
if (ext.x < 10) ext.x = 10;
if (ext.y < 10) ext.y = 10;
return this.setExtent(ext);
},
},
'halos', {
getHaloClasses: function($super) {
return $super().concat([lively.morphic.SetImageURLHalo]);
},
},
'menu', {
morphMenuItems: function($super) {
var items = $super();
items.push(['set to original extent', this.setNativeExtent.bind(this)]);
items.push(['inline image data', this.convertToBase64.bind(this)]);
return items;
},
},
'keyboard events', {
onKeyPress: function($super, evt) {
// The extent of iages should can be changed by using the + and - key
var key = evt.getKeyChar();
switch (key) {
case "-": {
this.setExtent(this.getExtent().scaleBy(0.8))
return true;
}
case "+": {
this.setExtent(this.getExtent().scaleBy(1.1))
return true;
}
}
return $super(evt)
}
},
'inline image', {
convertToBase64: function() {
var urlString = this.getImageURL(),
type = urlString.substring(urlString.lastIndexOf('.') + 1, urlString.length);
if (type == 'jpg') type = 'jpeg';
if (!['gif', 'jpeg', 'png', 'tiff'].include(type)) type = 'gif';
if (false && Global.btoa) {
// FIXME actually this should work but the encoding result is wrong...
// maybe the binary image content is not loaded correctly because of encoding?
urlString = URL.makeProxied(urlString);
var content = new WebResource(urlString).get(null, 'image/' + type).content,
fixedContent = content.replace(/./g, function(m) {
return String.fromCharCode(m.charCodeAt(0) & 0xff);
}),
encoded = btoa(fixedContent);
this.setImageURL('data:image/' + type + ';base64,' + encoded);
} else {
var image = this;
if (!urlString.startsWith('http')) {
urlString = URL.source.getDirectory().withFilename(urlString).toString();
}
require('lively.ide.CommandLineInterface').toRun(function() { // FIXME
var cmd = 'curl --silent "' + urlString + '" | openssl base64'
lively.ide.CommandLineInterface.exec(cmd, function(cmd) {
image.setImageURL('data:image/' + type + ';base64,' + cmd.getStdout());
});
});
}
}
});
Object.extend(lively.morphic.Image, {
fromURL: function(url, optBounds) {
var bounds = optBounds || new Rectangle(0,0, 100, 100);
return new lively.morphic.Image(bounds, url, optBounds == undefined)
},
});
lively.morphic.Morph.subclass('lively.morphic.CheckBox',
'properties', {
connections: {
setChecked: {}
}
},
'initializing', {
initialize: function($super, isChecked) {
$super(this.defaultShape());
this.setChecked(isChecked);
},
defaultShape: function() {
// FIXME: render context dependent
var node = XHTMLNS.create('input');
node.type = 'checkbox';
return new lively.morphic.Shapes.External(node);
}
},
'accessing', {
setChecked: function(bool) {
// FIXME: render context dependent
this.checked = bool;
this.renderContext().shapeNode.checked = bool;
return bool;
}
},
'testing', {
isChecked: function() {
return this.checked;
},
},
'event handling', {
onClick: function(evt) {
// for halos/menus
if (evt.isCommandKey() || !evt.isLeftMouseButtonDown()) {
evt.stop()
return true;
}
// we do it ourselves
this.setChecked(!this.isChecked());
return true;
},
},
'serialization', {
prepareForNewRenderContext: function ($super, renderCtx) {
$super(renderCtx);
// FIXME what about connections to this.isChecked?
// they would be updated here...
this.setChecked(this.isChecked());
}
});
lively.morphic.Morph.subclass('lively.morphic.PasswordInput',
'initializing', {
initialize: function($super, isChecked) {
$super(this.createShape());
},
createShape: function() {
var node = XHTMLNS.create('input');
node.type = 'password';
node.className = 'visibleSelection';
return new lively.morphic.Shapes.External(node);
},
},
'accessing', {
set value(string) {
// FIXME move to lively.morphic.HTML
var inputNode = this.renderContext().shapeNode;
if (inputNode) {
inputNode.value = string;
}
lively.bindings.signal(this, 'value', string);
return string;
},
get value() {
// FIXME move to lively.morphic.HTML
var inputNode = this.renderContext().shapeNode;
return inputNode ? inputNode.value : '';
}
});
lively.morphic.Box.subclass('lively.morphic.ProgressBar',
'settings', {
style: {
fill: Color.white, borderColor: Color.rgb(170,170,170), borderWidth: 1, borderRadius: 5,
adjustForNewBounds: true,
clipMode: 'hidden', // so that sharp borders of progress do not stick out
},
progressStyle: {
scaleHorizontal: true,
scaleVertical: true,
borderColor: Color.rgb(170,170,170),
borderWidth: 1,
borderRadius: "5px 0px 0px 5px",
fill: new lively.morphic.LinearGradient([
{offset: 0, color: Color.rgb(223,223,223)},
{offset: 1, color: Color.rgb(204,204,204)}]),
clipMode: 'hidden', // for label
},
labelStyle: {
fontSize: 11,
fixedWidth: true,
fixedHeight: false,
clipMode: 'hidden',
align: 'center',
},
},
'initializing', {
initialize: function($super, bounds) {
bounds = bounds || new Rectangle(0,0, 200,22);
$super(bounds);
this.createProgressMorph();
this.createLabel();
this.value = 0;
},
createProgressMorph: function() {
var bounds = this.innerBounds();
this.progressMorph = this.addMorph(lively.morphic.Morph.makeRectangle(bounds.withWidth(0)));
this.progressMorph.applyStyle(this.progressStyle);
this.progressMorph.ignoreEvents();
},
createLabel: function() {
this.labelBlack = lively.morphic.Text.makeLabel('', Object.extend({textColor: Color.black, centeredVertical: true, scaleHorizontal: true}, this.labelStyle));
this.labelWhite = lively.morphic.Text.makeLabel('', Object.extend({textColor: Color.white}, this.labelStyle));
this.addMorphBack(this.labelBlack);
this.progressMorph.addMorph(this.labelWhite);
this.labelBlack.ignoreEvents();
this.labelWhite.ignoreEvents();
connect(this.labelBlack, 'extent', this.labelWhite, 'setExtent')
connect(this.labelBlack, 'position', this.labelWhite, 'setPosition')
this.labelBlack.setBounds(this.innerBounds());
this.labelBlack.fit();
},
},
'accessing', {
getValue: function() { return this.value },
setValue: function(v) { this.updateBar(v); return this.value = v },
setLabel: function(string) {
this.labelBlack.textString = string;
this.labelWhite.textString = string;
},
},
'updating', {
updateBar: function(value) {
var maxExt = this.getExtent();
this.progressMorph.setExtent(pt(Math.floor(maxExt.x * value), maxExt.y));
}
});
lively.morphic.Text.subclass('lively.morphic.FrameRateMorph', {
initialize: function($super, shape) {
// Steps at maximum speed, and gathers stats on ticks per sec and max latency
$super(shape);
this.setTextString('FrameRateMorph')
this.reset(new Date());
},
reset: function(date) {
this.lastTick = date.getSeconds();
this.lastMS = date.getTime();
this.stepsSinceTick = 0;
this.maxLatency = 0;
},
nextStep: function() {
var date = new Date();
this.stepsSinceTick++;
var nowMS = date.getTime();
this.maxLatency = Math.max(this.maxLatency, nowMS - this.lastMS);
this.lastMS = nowMS;
var nowTick = date.getSeconds();
if (nowTick != this.lastTick) {
this.lastTick = nowTick;
var ms = (1000 / Math.max(this. stepsSinceTick,1)).roundTo(1);
this.setTextString(this.stepsSinceTick + " frames/sec (" + ms + "ms avg),\nmax latency " + this.maxLatency + " ms.");
this.reset(date);
}
},
startSteppingScripts: function() { this.startStepping(1, 'nextStep'); }
});
lively.morphic.Box.subclass('lively.morphic.Menu',
'settings', {
style: {
fill: Color.gray.lighter(3),
borderColor: Color.gray.lighter(),
borderWidth: 1,
borderStyle: 'outset',
borderRadius: 4,
opacity: 0.95
},
isEpiMorph: true,
isMenu: true,
removeOnMouseOut: false
},
'initializing', {
initialize: function($super, title, items) {
$super(new Rectangle(0,0, 120, 10));
this.items = [];
this.itemMorphs = [];
if (title) this.setupTitle(title);
if (items) this.addItems(items);
},
setupTitle: function(title) {
if (this.title) this.title.remove()
this.title = new lively.morphic.Text(
new Rectangle(0,0, this.getExtent().x, 25),
String(title).truncate(26)).beLabel({
borderRadius: this.getBorderRadius(),
borderColor: this.getBorderColor(),
borderWidth: 0,
fill: new lively.morphic.LinearGradient([{offset: 0, color: Color.white},
{offset: 1, color: Color.gray}]),
textColor: CrayonColors.lead,
clipMode: 'hidden',
fixedWidth: false,
fixedHeight: true,
borderColor: Color.gray.lighter(2),
borderWidth: 1,
borderStyle: 'outset',
borderRadius: 4,
padding: Rectangle.inset(5,5,5,5),
emphasize: {fontWeight: 'bold'}
});
this.title.align(this.title.bounds().bottomLeft(), pt(0,0));
this.addMorph(this.title);
this.fitToItems()
}
},
'mouse events', {
onMouseOut: function() {
if (this.removeOnMouseOut) {
this.remove()
};
return this.removeOnMouseOut;
}
},
'opening', {
openIn: function(parentMorph, pos, remainOnScreen, captionIfAny) {
this.setPosition(pos || pt(0,0));
if (captionIfAny) { this.setupTitle(captionIfAny) };
var owner = parentMorph || lively.morphic.World.current();
this.remainOnScreen = remainOnScreen;
if (!remainOnScreen) {
if (owner.currentMenu) { owner.currentMenu.remove() };
owner.currentMenu = this;
} else {
this.isEpiMorph = false;
}
owner.addMorph(this);
this.fitToItems.bind(this).delay(0);
this.offsetForWorld(pos);
// delayed because of fitToItems
// currently this is deactivated because the initial bounds are correct
// for our current usage
// this.offsetForWorld.curry(pos).bind(this).delay(0);
return this;
},
},
'removing', {
remove: function($super) {
var w = this.world();
if (w && w.currentMenu === this) w.currentMenu = null;
$super();
},
},
'item management', {
removeAllItems: function() {
this.items = [];
this.itemMorphs = [];
this.submorphs.without(this.title).invoke('remove');
},
createMenuItems: function(items) {
function createItem(string, value, idx, callback, callback2, isSubMenu) {
return {
isMenuItem: true,
isListItem: true,
isSubMenu: isSubMenu,
string: string,
value: value,
idx: idx,
onClickCallback: callback,
onMouseOverCallback: callback2
}
}
var result = [], self = this;
items.forEach(function(item, i) {
if (item.isMenuItem) { item.idx = i; result.push(item); return };
// item = [name, callback]
if (Object.isArray(item) && Object.isFunction(item[1])) {
result.push(createItem(String(item[0]), item[0], i, item[1]))
return;
}
// item = [name, target, methodName, args...]
if (Object.isArray(item) && Object.isString(item[2])) {
result.push(createItem(String(item[0]), item[0], i, function(evt) {
var receiver = item[1],
method = receiver[item[2]],
args = item.slice(3);
method.apply(receiver, args) }))
return;
}
// sub menu item = [name, [sub elements]]
if (Object.isArray(item) && Object.isArray(item[1])) {
var name = item[0], subItems = item[1];
result.push(createItem(name, name, i, null, function(evt) {
self.openSubMenu(evt, name, subItems) }, true));
return;
}
// [name, {getItems: function() { return submenu items }}]
if (Object.isArray(item) && Object.isObject(item[1])) {
var name = item[0], spec = item[1];
if (Object.isFunction(spec.condition)) {
if (!spec.condition()) return;
}
if (Object.isFunction(spec.getItems)) {
result.push(createItem(name, name, i, null, function(evt) {
self.openSubMenu(evt, name, spec.getItems()) }, true));
}
return;
}
// item = "some string"
result.push(createItem(String(item), item, i, function() { alert('clicked ' + self.idx) }));
});
return result;
},
addItems: function(items) {
this.removeAllItems();
this.items = this.createMenuItems(items);
var y = 0, x = 0;
this.items.forEach(function(item) {
var itemMorph = new lively.morphic.MenuItem(item);
this.itemMorphs.push(this.addMorph(itemMorph));
itemMorph.setPosition(pt(0, y));
y += itemMorph.getExtent().y;
x = Math.max(x, itemMorph.getExtent().x);
}, this);
if (this.title) y += this.title.bounds().height;
this.setExtent(pt(x, y));
}
},
'sub menu', {
openSubMenu: function(evt, name, items) {
var m = new lively.morphic.Menu(null, items);
this.addMorph(m);
m.fitToItems.bind(m).delay(0);
this.subMenu = m;
m.ownerMenu = this;
// delayed so we can use the real text extent
(function() {
if (!m.ownerMenu) return; // we might have removed that submenu already again
m.offsetForOwnerMenu();
m.setVisible(true);
}).delay(0);
return m;
},
removeSubMenu: function() {
if (!this.subMenu) return;
var m = this.subMenu;
m.ownerMenu = null;
this.subMenu = null;
m.remove();
},
removeOwnerMenu: function() {
if (!this.ownerMenu) return;
var m = this.ownerMenu;
this.ownerMenu = null;
m.remove();
},
},
'removal', {
remove: function($super) {
$super();
this.removeSubMenu();
this.removeOwnerMenu();
},
},
'bounds calculation', {
moveBoundsForVisibility: function(menuBounds, visibleBounds) {
var offsetX = 0,
offsetY = 0;
Global.lastMenuBounds = menuBounds;
if (menuBounds.right() > visibleBounds.right())
offsetX = -1 * (menuBounds.right() - visibleBounds.right());
var overlapLeft = menuBounds.left() + offsetX;
if (overlapLeft < 0)
offsetX += -overlapLeft;
if (menuBounds.bottom() > visibleBounds.bottom()) {
offsetY = -1 * (menuBounds.bottom() - visibleBounds.bottom());
// so that hand is not directly over menu, does not work when
// menu is in the bottom right corner
offsetX += 1;
}
var overlapTop = menuBounds.top() + offsetY;
if (overlapTop < 0)
offsetY += -overlapTop;
return menuBounds.translatedBy(pt(offsetX, offsetY));
},
moveSubMenuBoundsForVisibility: function(subMenuBnds, mainMenuItemBnds, visibleBounds, direction) {
// subMenuBnds is bounds to be transformed, mainMenuItemBnds is the bounds of the menu
// item that caused the submenu to appear, visbleBounds is the bounds that the submenu
// should fit into, when there are multiple submenus force one direction with forceDirection
if (!direction) {
direction = mainMenuItemBnds.right() + subMenuBnds.width > visibleBounds.right() ?
'left' : 'right';
}
var extent = subMenuBnds.extent();
if (direction === 'left') {
subMenuBnds = mainMenuItemBnds.topLeft().addXY(-extent.x, 0).extent(extent);
} else {
subMenuBnds = mainMenuItemBnds.topRight().extent(extent);
}
if (subMenuBnds.bottom() > visibleBounds.bottom()) {
var deltaY = -1 * (subMenuBnds.bottom() - visibleBounds.bottom());
subMenuBnds = subMenuBnds.translatedBy(pt(0, deltaY));
}
// if it overlaps at the top move the bounds so that it aligns woitht he top
if (subMenuBnds.top() < visibleBounds.top()) {
var deltaY = visibleBounds.top() - subMenuBnds.top();
subMenuBnds = subMenuBnds.translatedBy(pt(0, deltaY));
}
return subMenuBnds;
},
offsetForWorld: function(pos) {
var bounds = this.innerBounds().translatedBy(pos);
if (this.title) {
bounds = bounds.withTopLeft(bounds.topLeft().addXY(0, this.title.getExtent().y));
}
if (this.owner.visibleBounds) {
bounds = this.moveBoundsForVisibility(bounds, this.owner.visibleBounds());
}
this.setBounds(bounds);
},
offsetForOwnerMenu: function() {
var owner = this.ownerMenu,
visibleBounds = this.world().visibleBounds(),
localVisibleBounds = owner.getGlobalTransform().inverse().transformRectToRect(visibleBounds),
newBounds = this.moveSubMenuBoundsForVisibility(
this.innerBounds(),
owner.overItemMorph ? owner.overItemMorph.bounds() : new Rectangle(0,0,0,0),
localVisibleBounds);
this.setBounds(newBounds);
},
fitToItems: function() {
var offset = 10 + 20,
morphs = this.itemMorphs;
if (this.title) morphs = morphs.concat([this.title]);
var widths = morphs.invoke('getTextExtent').pluck('x'),
width = Math.max.apply(Global, widths) + offset,
newExtent = this.getExtent().withX(width);
this.setExtent(newExtent);
morphs.forEach(function(ea) {
ea.setExtent(ea.getExtent().withX(newExtent.x));
if (ea.submorphs.length > 0) {
var arrow = ea.submorphs.first();
arrow.setPosition(arrow.getPosition().withX(newExtent.x-17));
}
})
}
});
Object.extend(lively.morphic.Menu, {
openAtHand: function(title, items) {
return this.openAt(lively.morphic.World.current().firstHand().getPosition(), title, items);
},
openAt: function(pos, title, items) {
var menu = new lively.morphic.Menu(title, items);
return menu.openIn(lively.morphic.World.current(), pos, false);
},
});
lively.morphic.Text.subclass("lively.morphic.MenuItem",
'settings', {
style: {
clipMode: 'hidden',
fixedHeight: true,
fixedWidth: false,
borderWidth: 0,
fill: null,
handStyle: 'default',
enableGrabbing: false,
allowInput: false,
fontSize: 10.5,
padding: Rectangle.inset(3,2),
textColor: Config.get('textColor') || Color.black,
whiteSpaceHandling: 'nowrap'
},
defaultTextColor: Config.get('textColor') || Color.black
},
'initializing', {
initialize: function($super, item) {
$super(new Rectangle(0,0, 100, 23), item.string);
this.item = item;
if (item.isSubMenu) this.addArrowMorph();
},
addArrowMorph: function() {
var extent = this.getExtent(),
arrowMorph = new lively.morphic.Text(
new Rectangle(0, 0, 10, extent.y), "▶");
arrowMorph.setPosition(pt(extent.x, 0));
arrowMorph.applyStyle(this.getStyle());
this.arrow = this.addMorph(arrowMorph);
}
},
'mouse events', {
onMouseUp: function($super, evt) {
if (evt.world.clickedOnMorph !== this && (Date.now() - evt.world.clickedOnMorphTime < 500)) {
return false; // only a click
}
$super(evt);
this.item.onClickCallback && this.item.onClickCallback(evt);
if (!this.owner.remainOnScreen) this.owner.remove(); // remove the menu
evt.stop();
return true;
},
onMouseOver: function(evt) {
if (this.isSelected) return true;
this.select();
this.item.onMouseOverCallback && this.item.onMouseOverCallback(evt);
evt.stop();
return true;
},
onMouseWheel: function(evt) {
return false; // to allow scrolling
},
onSelectStart: function(evt) {
return false; // to allow scrolling
},
select: function(evt) {
this.isSelected = true;
this.owner.itemMorphs.without(this).invoke('deselect');
this.applyStyle({
fill: new lively.morphic.LinearGradient([
{offset: 0, color: Color.rgb(100,131,248)},
{offset: 1, color: Color.rgb(34,85,245)}]),
textColor: Color.white,
borderRadius: 4
});
// if the item is a submenu, set its textColor to white
var arrow = this.submorphs.first();
if (arrow) {
arrow.applyStyle({textColor: Color.white});
}
this.owner.overItemMorph = this;
this.owner.removeSubMenu();
return true;
},
deselect: function(evt) {
this.isSelected = false;
this.applyStyle({fill: null, textColor: this.defaultTextColor});
if (this.arrow) {
this.arrow.applyStyle({textColor: this.defaultTextColor});
}
}
});
lively.morphic.Morph.addMethods(
'menu', {
enableMorphMenu: function() {
this.showsMorphMenu = true;
},
disableMorphMenu: function() { this.showsMorphMenu = false },
openMorphMenuAt: function(pos, itemFilter) {
itemFilter = Object.isFunction(itemFilter) ? itemFilter : Functions.K;
return lively.morphic.Menu.openAt(pos, this.name || this.toString(),
itemFilter(this.morphMenuItems()));
},
createMorphMenu: function(itemFilter) {
itemFilter = Object.isFunction(itemFilter) ? itemFilter : Functions.K;
return new lively.morphic.Menu(this.name || this.toString(),
itemFilter(this.morphMenuItems()));
},
showMorphMenu: function(evt) {
var pos = evt ? evt.getPosition() : this.firstHand().getPosition();
evt && evt.stop();
this.openMorphMenuAt(pos);
return true;
},
morphMenuItems: function() {
var self = this,
world = this.world(),
items = [];
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// partsbin related
items.push(['Publish', function(evt) { self.copyToPartsBinWithUserRequest(); }]);
if (this.reset) {
[].pushAt
var idx=-1; items.detect(function(item, i) { idx = i; return item[0] === 'Publish'; });
idx > -1 && items.pushAt(['Reset', this.reset.bind(this)], idx+1);
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// morphic hierarchy / windows
items.push(['Open in...', [
['Window', function(evt) { self.openInWindow(evt.mousePoint); }],
['Flap...', ['top', 'right', 'bottom', 'left'].map(function(align) {
return [align, function(evt) {
require('lively.morphic.MorphAddons').toRun(function() {
self.openInFlap(align); }); }]; })]
]]);
// Drilling into scene to addMorph or get a halo
// whew... this is expensive...
function menuItemsForMorphsBeneathMe(itemCallback) {
var morphs = world.morphsContainingPoint(self.worldPoint(pt(0,0)));
morphs.pop(); // remove world
var selfInList = morphs.indexOf(self);
// remove self and other morphs over self (the menu)
morphs = morphs.slice(selfInList + 1);
return morphs.collect(function(ea) { return [String(ea), itemCallback.bind(this, ea)]; });
}
items.push(["Add morph to...", {
getItems: menuItemsForMorphsBeneathMe.bind(this, function(morph) { morph.addMorph(self) })
}]);
items.push(["Get halo on...", {
getItems: menuItemsForMorphsBeneathMe.bind(this, function(morph, evt) { morph.toggleHalos(evt); })
}]);
if (this.owner && this.owner.submorphs.length > 1) {
var arrange = [];
arrange.push(["Bring to front", function(){self.bringToFront()}]);
arrange.push(["Send to back", function(){self.sendToBack()}]);
items.push(["Arrange morph", arrange]);
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// stepping scripts
var steppingItems = [];
if (this.startSteppingScripts) {
steppingItems.push(["Start stepping", function(){self.startSteppingScripts()}])
}
if (this.scripts.length != 0) {
steppingItems.push(["Stop stepping", function(){self.stopStepping()}])
}
if (steppingItems.length != 0) {
items.push(["Stepping", steppingItems])
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// lively bindings
items.push(["Connections...", {
getConnections: function() {
if (!this.connections) {
this.connections = !self.attributeConnections ? [] :
self.attributeConnections
// rk: come on, this is a mess!
.reject(function(ea) { return ea.dependedBy }) // Meta connection
.reject(function(ea) { return ea.targetMethodName == 'alignToMagnet'}) // Meta connection
}
return this.connections;
},
condition: function() {
return this.getConnections().length > 0;
},
getItems: function() {
return this.getConnections()
.collect(function(ea) {
var s = ea.sourceAttrName + " -> " + ea.targetObj + "." + ea.targetMethodName
return [s, [
["Disconnect", function() { alertOK("disconnecting " + ea); ea.disconnect(); }],
["Edit converter", function() { var window = lively.bindings.editConnection(ea); }],
["Show", function() { lively.bindings.showConnection(ea); }],
["Hide", function() { if (ea.visualConnector) ea.visualConnector.remove(); }]]];
});
}
}]);
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// morphic properties
var morphicMenuItems = ['Morphic properties', []];
items.push(morphicMenuItems);
morphicMenuItems[1].push(['display serialization info', function() {
require('lively.persistence.Debugging').toRun(function() {
var json = self.copy(true),
printer = lively.persistence.Debugging.Helper.listObjects(json);
var text = world.addTextWindow({content: printer.toString(),
extent: pt(600, 200),
title: 'Objects in this world'});
text.setFontFamily('Monaco,monospace');
text.setFontSize(10);
})}]);
['grabbing', 'dragging', 'dropping', 'halos'].forEach(function(propName) {
if (self[propName + 'Enabled'] || self[propName + 'Enabled'] == undefined) {
morphicMenuItems[1].push(["Disable " + propName.capitalize(), self['disable' + propName.capitalize()].bind(self)]);
} else {
morphicMenuItems[1].push(["Enable " + propName.capitalize(), self['enable' + propName.capitalize()].bind(self)]);
}
});
if (this.submorphs.length > 0) {
if (this.isLocked()) {
morphicMenuItems[1].push(["Unlock parts", this.unlock.bind(this)])
} else {
morphicMenuItems[1].push(["Lock parts", this.lock.bind(this)])
}
}
if (this.isFixed) {
morphicMenuItems[1].push(["set unfixed", function() {
self.setFixed(false);
}]);
} else {
morphicMenuItems[1].push(["set fixed", function() {
self.setFixed(true);
}]);
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// left over...
if (false) { // rk 12-06-22: what is this for???
items.push(["Enable internal selections", function() {
Trait('SelectionMorphTrait').applyTo(self, {override: ['onDrag', 'onDragStart', 'onDragEnd']});
self.enableDragging();
}])
}
return items;
},
getWindow: function() {
if (this.isWorld) {
return null;
}
if (this.isWindow) {
return this;
}
if (this.owner) {
return this.owner.getWindow();
}
return null;
},
isInInactiveWindow: function() {
var win = this.getWindow();
return win ? !win.isActive() : false;
},
},
'modal dialog', {
beModal: function(optBackgroundColor) {
/*
* Makes a morph 'modal' by adding a backpane to the world
* which is not removed as long as the morph is still there.
*
* Usage:
*
* morph.beModal(Color.gray);
*
* Enjoy
*/
if (this.backPanel) {
this.removeBackPanel();
}
function createBackPanel(extent) {
var backPanel = new lively.morphic.Box(extent.extentAsRectangle()),
style = {enableGrabbing: false, enableDragging: false};
if (optBackgroundColor) style.fill = optBackgroundColor;
backPanel.applyStyle(style).ignoreEvents();
return backPanel;
}
this.addScript(function removeBackPanel() {
this.backPanel && this.backPanel.remove && this.backPanel.remove();
delete this.backPanel;
delete this.removeBackPanel;
delete this.remove;
});
this.addScript(function remove() {
if (this.backPanelCanBeRemoved) this.removeBackPanel();
return $super();
});
this.backPanel = createBackPanel(this.owner.getExtent());
this.owner.addMorph(this.backPanel);
this.backPanel.bringToFront();
this.backPanelCanBeRemoved = false;
this.bringToFront();
this.backPanelCanBeRemoved = true;
}
});
lively.morphic.Text.addMethods(
'menu', {
morphMenuItems: function($super) {
var self = this, items = $super(), textItems = ['Text...'];
textItems.push([[
(self.inputAllowed() ? '[X]' : '[ ]') + ' input allowed',
function() { self.setInputAllowed(!self.inputAllowed()); }
], [
(self.evalEnabled ? '[X]' : '[ ]') + ' eval',
function() { self.evalEnabled = !self.evalEnabled }
], [
(self.syntaxHighlightingWhileTyping ? '[X]' : '[ ]') + ' syntax highlighting',
function() { self.syntaxHighlightingWhileTyping ?
self.disableSyntaxHighlighting() : self.enableSyntaxHighlighting() }
], [
'convert to annotation',
function() {
var part = $world.openPartItem('AnnotationPin', 'PartsBin/Documentation');
part.setPosition(self.getPosition());
part.createAnnotationFromText(self);
self.remove();
}
], [
'debugging', [
[(self.isInChunkDebugMode() ? 'disable' : 'enable') + ' text chunk debugging',
function() { self.setChunkDebugMode(!self.isInChunkDebugMode()) }],
['open text inspector', function() {
var inspector = $world.openPartItem('TextInspector', 'PartsBin/Debugging');
inspector.targetMorph.findAndConnectMorph(self);
}]
]]
]);
items.push(textItems);
return items;
},
});
lively.morphic.World.addMethods(
'tools', {
loadPartItem: function(partName, optPartspaceName) {
var optPartspaceName = optPartspaceName || 'PartsBin/NewWorld',
part = lively.PartsBin.getPart(partName, optPartspaceName);
if (!part) return;
if (part.onCreateFromPartsBin) part.onCreateFromPartsBin();
return part;
},
openPartItem: function(partName, optPartspaceName) {
var part = this.loadPartItem(partName, optPartspaceName);
part.openInWorld(pt(0,0))
part.align(part.bounds().center(), this.visibleBounds().center());
return part;
},
openPartsBin: function(evt) {
module('lively.morphic.tools.PartsBin').load(true);
return lively.BuildSpec('lively.morphic.tools.PartsBin').createMorph().openInWorldCenter();
},
openInspectorFor: function(object, evt) {
module('lively.ide.tools.Inspector').load(true);
var inspector = lively.BuildSpec('lively.ide.tools.Inspector').createMorph().openInWorldCenter();
inspector.comeForward();
inspector.inspect(object);
return inspector;
},
openStyleEditorFor: function(morph, evt) {
module('lively.ide.tools.StyleEditor').load(true);
var styleEditorWindow = lively.BuildSpec('lively.ide.tools.StyleEditor').createMorph().openInWorld();
styleEditorWindow.setTarget(morph);
var alignPos = morph.getGlobalTransform().transformPoint(morph.innerBounds().bottomLeft()),
edBounds = styleEditorWindow.innerBounds(),
visibleBounds = this.visibleBounds();
if (visibleBounds.containsRect(edBounds.translatedBy(alignPos))) {
styleEditorWindow.setPosition(alignPos);
} else {
styleEditorWindow.setPositionCentered(visibleBounds.center());
}
return styleEditorWindow;
},
openObjectEditor: function() {
module('lively.ide.tools.ObjectEditor').load(true);
return lively.BuildSpec('lively.ide.tools.ObjectEditor').createMorph().openInWorldCenter();
},
openTerminal: function() {
require('lively.ide.tools.Terminal').toRun(function() {
lively.BuildSpec('lively.ide.tools.Terminal').createMorph().openInWorldCenter().comeForward();
});
},
openObjectEditorFor: function(morph) {
var part = this.openObjectEditor();
part.setTarget(morph);
return part;
},
openMethodFinder: function() {
return this.openPartItem('MethodFinder', 'PartsBin/Tools');
},
openMethodFinderFor: function(searchString) {
var toolPane = this.get('ToolTabPane');
if (!toolPane) {
toolPane = this.openPartItem('ToolTabPane', 'PartsBin/Dialogs');
toolPane.openInWindow();
toolPane.owner.name = toolPane.name +"Window";
toolPane.owner.minExtent = pt(700,370);
var corner = toolPane.withAllSubmorphsDetect(function (ea) {
return ea.name == "ResizeCorner";
});
corner && toolPane.owner.addMorph(corner)
}
var part = toolPane.openMethodFinderFor(searchString)
part.setExtent(toolPane.tabPaneExtent)
part.owner.layout = part.owner.layout || {};
part.owner.layout.resizeWidth = true;
part.owner.layout.resizeHeight = true;
part.owner.layout.adjustForNewBounds = true;
return part;
},
openVersionViewer: function(evt) {
return this.openPartItem('VersionViewer', 'PartsBin/Wiki');
},
openTestRunner: function() {
var m = this.openPartItem('TestRunner', 'PartsBin/Tools');
m.align(m.bounds().topCenter().addPt(pt(0,-20)), this.visibleBounds().topCenter());
return m
},
openClassBrowserFor: function(searchString) {
var part = this.openPartItem('ClassBrowser', 'PartsBin/Tools');
part.targetMorph.searchClass(searchString);
return part;
},
openPublishPartDialogFor: function(morph) {
var publishDialog = this.loadPartItem('PublishPartDialog', 'PartsBin/Dialogs');
var metaInfo = morph.getPartsBinMetaInfo();
publishDialog.targetMorph.setTarget(morph);
publishDialog.openInWorldCenter();
$world.publishPartDialog = publishDialog;
return publishDialog;
},
openConnectDocumentation: function() {
return this.openPartItem('HowConnectWorks', 'PartsBin/Documentation');
},
openShortcutDocumentation: function() {
return this.openPartItem('HelpfulShortcuts', 'PartsBin/Documentation');
},
openPartsBinDocumentation: function() {
return this.openPartItem('LivelysPartsBin', 'PartsBin/Documentation');
},
openSystemBrowser: function(evt) {
var world = this,
browser;
require('lively.ide.SystemCodeBrowser').toRun(function() {
browser = new lively.ide.SystemBrowser();
browser.openIn(world);
var lastOpened = lively.ide.SourceControl.registeredBrowsers.last();
lastOpened && browser.setTargetURL(lastOpened.targetURL)
});
return browser;
},
browseCode: function(/*args*/) {
// find code and browse it
// args can be objectName, methodName, sourceModuleName
// see lively.ide.browse for more options
var args = Array.from(arguments);
require('lively.ide.SystemCodeBrowser').toRun(function() {
lively.ide.browse.apply(lively.ide, args);
});
},
openWorkspace: function(evt) {
var text = this.addTextWindow({title: 'Workspace',
content: '3 + 4', syntaxHighlighting: true})
text.accessibleInInactiveWindow = true;
text.setFontFamily('Monaco,monospace');
text.selectAll();
return text;
},
openAboutBox: function() {
var text = this.addTextWindow({title: 'About Lively Kernel'});
text.owner.setExtent(pt(390, 105));
var webR = new WebResource(new URL(Config.rootPath));
var licenseURL = 'http://lively-kernel.org/license/index.html';
var headRevision = webR.getHeadRevision().headRevision;
var repositoryString = 'Repository: ' + Config.rootPath;
var revisionString = '\n\nRevision: ' + headRevision;
var licenseString = '\n\nLicense: ' + licenseURL;
text.setTextString(repositoryString + revisionString + licenseString);
text.changeEmphasis('Repository: '.length, repositoryString.length + 1, function(emph, doEmph) {
doEmph({uri: Config.rootPath});
});
text.changeEmphasis(repositoryString.length + revisionString.length + '\n\nLicense: '.length, repositoryString.length + revisionString.length + licenseString.length + 1, function(emph, doEmph) {
doEmph({uri: licenseURL});
});
text.setSelectionRange(0,0)
return text;
},
openBootstrapParts: function() {
// load the bootstrap part from webwerkstat
// this part can fetch all his friends :-)
var oldRootPath = Config.rootPath
try {
Config.rootPath = 'http://lively-kernel.org/repository/webwerkstatt/'
this.openPartItem("BootstrapParts", "PartsBin/Tools")
} finally {
Config.rootPath = oldRootPath
}
},
openSystemConsole: function() {
return this.openPartItem('SystemConsole', 'PartsBin/Tools');
},
openBuildSpecEditor: function() {
require('lively.ide.tools.BuildSpecEditor').toRun(function() {
lively.BuildSpec('lively.ide.tools.BuildSpecEditor').createMorph().openInWorldCenter().comeForward();
});
},
openSubserverViewer: function() {
require('lively.ide.tools.SubserverViewer').toRun(function() {
lively.BuildSpec('lively.ide.tools.SubserverViewer').createMorph().openInWorldCenter().comeForward();
});
},
openServerWorkspace: function() {
require('lively.ide.tools.ServerWorkspace').toRun(function() {
lively.BuildSpec('lively.ide.tools.ServerWorkspace').createMorph().openInWorldCenter().comeForward();
});
},
openOMetaWorkspace: function() {
return this.openPartItem('OMetaWorkspace', 'core/lively/ide/tools/');
},
openGitControl: function() {
return this.openPartItem('GitControl', 'core/lively/ide/tools/');
},
},
'menu', {
morphMenuPartsBinItems: function() {
var partSpaceName = 'PartsBin/NewWorld'
var partSpace = lively.PartsBin.partsSpaceNamed(partSpaceName);
partSpace.load()
return partSpace.getPartNames().sort().collect(function(ea) { return [ea, function() {
var part = lively.PartsBin.getPart(ea, partSpaceName)
lively.morphic.World.current().firstHand().addMorph(part)
}]})
},
morphMenuDefaultPartsItems: function() {
var items = [],
partNames = ["Rectangle", "Ellipse", "Image", "Text", 'Line'].sort();
items.pushAll(partNames.collect(function(ea) { return [ea, function() {
var partSpaceName = 'PartsBin/Basic',
part = lively.PartsBin.getPart(ea, partSpaceName);
if (!part) return;
lively.morphic.World.current().firstHand().grabMorph(part);
}]}))
partNames = ["List", "Slider", "Button"].sort()
items.pushAll(partNames.collect(function(ea) { return [ea, function() {
var partSpaceName = 'PartsBin/Inputs',
part = lively.PartsBin.getPart(ea, partSpaceName);
if (!part) return;
lively.morphic.World.current().firstHand().grabMorph(part);
}]}))
return items;
},
debuggingMenuItems: function(world) {
var items = [
['Reset world scale', this.resetScale.bind(this)],
['Check app cache', this.checkApplicationCache.bind(this)],
['World serialization info', function() {
require('lively.persistence.Debugging').toRun(function() {
var json = lively.persistence.Serializer.serialize(world),
printer = lively.persistence.Debugging.Helper.listObjects(json);
var text = world.addTextWindow({content: printer.toString(),
extent: pt(600, 250),
title: 'Objects in this world'});
text.setFontFamily('Monaco,monospace');
text.setFontSize(9);
})}]];
// world requirements
var worldRequirements = world.getWorldRequirements(),
removeRequirement = function(name) {
world.removeWorldRequirement(name);
alertOK(name + ' is not loaded at startup anymore');
},
menuItems = worldRequirements.collect(function(name) {
return [name, [['Remove', removeRequirement.curry(name)]]];
});
items.push(['Requirements', menuItems]);
// method tracing items
function disableGlobalTracing() {
// FIXME better to move this functionality into lively.Tracing
var controller = $morph("TracingController");
if (controller) {
controller.stopTrace();
} else {
lively.Tracing.stopGlobalDebugging();
}
}
var tracersInstalled = lively.Tracing && lively.Tracing.stackTracingEnabled,
globalTracingEnabled = tracersInstalled && lively.Tracing.globalTracingEnabled;
if (tracersInstalled) {
items.push(["Remove trace wrappers", function() {
if (globalTracingEnabled) disableGlobalTracing();
lively.Tracing.uninstallStackTracers();
}]);
if (!globalTracingEnabled) {
items.push(['Start global tracing', function() {
lively.Tracing.startGlobalTracing()
}]);
items.push(['Start global debugging', function() {
require('lively.ast.Morphic').toRun(function() {
lively.Tracing.startGlobalDebugging()
});
}]);
}
} else {
items.push(['Prepare system for tracing/debugging', function() {
require("lively.Tracing").toRun(function() {
lively.Tracing.installStackTracers();
});
}]);
}
if (Global.DebugScriptsLayer && DebugScriptsLayer.isGlobal()) {
items.push(['[X] Debug Morphic Scripts', function() {
DebugScriptsLayer.beNotGlobal()
}]);
} else {
items.push(['[ ] Debug Morphic Scripts', function() {
require('lively.ast.Morphic').toRun(function() {
DebugScriptsLayer.beGlobal()
});
}]);
}
if (Global.DebugMethodsLayer && DebugMethodsLayer.isGlobal()) {
items.push(['[X] Debug Methods', function() {
DebugMethodsLayer.beNotGlobal()
}]);
} else {
items.push(['[ ] Debug Methods', function() {
require('lively.ast.Morphic').toRun(function() {
DebugMethodsLayer.beGlobal()
});
}]);
}
if (module('lively.ast.IDESupport').isEnabled) {
items.push(['[X] Advanced Syntax Highlighting', function() {
require('lively.ast.IDESupport').toRun(function() {
lively.ast.IDESupport.disable();
});
}]);
} else {
items.push(['[ ] Advanced Syntax Highlighting', function() {
require('lively.ast.IDESupport').toRun(function() {
lively.ast.IDESupport.enable();
})
}]);
}
if (Global.AutoIndentLayer && AutoIndentLayer.isGlobal()) {
items.push(['[X] Auto Indent', function() {
AutoIndentLayer.beNotGlobal();
}]);
} else {
items.push(['[ ] Auto Indent', function() {
require('users.cschuster.AutoIndent').toRun(function() {
AutoIndentLayer.beGlobal();
});
}]);
}
if (localStorage['Config_quickLoad'] == "false") {
items.push(['[ ] Quick Load', function() {
localStorage['Config_quickLoad'] = "true"
}]);
} else {
items.push(['[X] Quick Load', function() {
localStorage['Config_quickLoad'] = "false";
}]);
}
if (localStorage['Config_CopyAndPaste'] == "false") {
items.push(['[ ] Copy And Paste', function() {
localStorage['Config_CopyAndPaste'] = "true"
module('lively.experimental.CopyAndPaste').load(true)
ClipboardLayer.beGlobal()
}]);
} else {
items.push(['[X] Copy And Paste', function() {
localStorage['Config_CopyAndPaste'] = "false";
ClipboardLayer.beNotGlobal()
}]);
}
return items;
},
morphMenuItems: function() {
var world = this;
var items = [
['PartsBin', this.openPartsBin.bind(this)],
['Parts', this.morphMenuDefaultPartsItems()],
['Tools', [
['Workspace', this.openWorkspace.bind(this)],
['System Code Browser', this.openSystemBrowser.bind(this)],
['Object Editor', this.openObjectEditor.bind(this)],
['BuildSpec Editor', this.openBuildSpecEditor.bind(this)],
['Test Runner', this.openTestRunner.bind(this)],
['Method Finder', this.openMethodFinder.bind(this)],
['Text Editor', function() { require('lively.ide').toRun(function() { lively.ide.openFile(URL.source.toString()); }); }],
['System Console', this.openSystemConsole.bind(this)],
['OMeta Workspace', this.openOMetaWorkspace.bind(this)],
['Subserver Viewer', this.openSubserverViewer.bind(this)],
['Server Workspace', this.openServerWorkspace.bind(this)],
['Terminal', this.openTerminal.bind(this)],
['Git Control', this.openGitControl.bind(this)]
]],
['Stepping', [
['Start stepping', function() { world.submorphs.each(
function(ea) {ea.startSteppingScripts && ea.startSteppingScripts()})}],
['Stop stepping', function() { world.submorphs.each(
function(ea) {ea.stopStepping && ea.stopStepping()})}],
]],
['Preferences', [
['Set username', this.askForUserName.bind(this)],
['My user config', this.showUserConfig.bind(this)],
['Set world extent', this.askForNewWorldExtent.bind(this)],
['Set background color', this.askForNewBackgroundColor.bind(this)]]
],
['Debugging', this.debuggingMenuItems(world)],
['Wiki', [
// ['About this wiki', this.openAboutBox.bind(this)],
// ['Bootstrap parts from webwerkstatt', this.openBootstrapParts.bind(this)],
// ['View versions of this world', this.openVersionViewer.bind(this)],
['Download world', function() {
require('lively.persistence.StandAlonePackaging').toRun(function() {
lively.persistence.StandAlonePackaging.packageCurrentWorld();
});
}],
['Delete world', this.interactiveDeleteWorldOnServer.bind(this)]
]],
['Documentation', [
["On short cuts", this.openShortcutDocumentation.bind(this)],
["On connect data bindings", this.openConnectDocumentation.bind(this)],
["On Lively's PartsBin", this.openPartsBinDocumentation.bind(this)],
["More ...", function() { window.open(Config.rootPath + 'documentation/'); }]
]],
['Save world as ...', this.interactiveSaveWorldAs.bind(this), 'synchron'],
['Save world', this.saveWorld.bind(this), 'synchron']
];
return items;
}
},
'positioning', {
positionForNewMorph: function (newMorph, relatedMorph) {
// this should be much smarter than the following:
if (relatedMorph)
return relatedMorph.bounds().topLeft().addPt(pt(5, 0));
var pos = this.firstHand().getPosition();
if (!newMorph) return pos;
var viewRect = this.visibleBounds().insetBy(80),
newMorphBounds = pos.extent(newMorph.getExtent());
// newShowRect(viewRect)
return viewRect.containsRect(newMorphBounds) ?
pos : viewRect.center().subPt(newMorphBounds.extent().scaleBy(0.5));
},
},
'windows', {
addFramedMorph: function(morph, title, optLoc, optSuppressControls, suppressReframeHandle) {
var w = this.addMorph(new lively.morphic.Window(morph, title || 'Window', optSuppressControls, suppressReframeHandle));
w.setPosition(optLoc || this.positionForNewMorph(morph));
return w;
},
addTextWindow: function(spec) {
// FIXME: typecheck the spec
if (Object.isString(spec.valueOf())) spec = {content: spec}; // convenience
var extent = spec.extent || pt(500, 200),
textMorph = new lively.morphic.Text(extent.extentAsRectangle(), spec.content || ""),
pane = this.internalAddWindow(textMorph, spec.title, spec.position);
textMorph.applyStyle({
clipMode: 'auto',
fixedWidth: true, fixedHeight: true,
resizeWidth: true, resizeHeight: true,
syntaxHighlighting: spec.syntaxHighlighting,
padding: Rectangle.inset(4,2),
fontSize: Config.get('defaultCodeFontSize')
});
return pane;
},
internalAddWindow: function(morph, title, pos, suppressReframeHandle) {
morph.applyStyle({borderWidth: 1, borderColor: CrayonColors.iron});
pos = pos || this.firstHand().getPosition().subPt(pt(5, 5));
var win = this.addFramedMorph(morph, String(title || ""), pos, suppressReframeHandle);
return morph;
},
addModal: function(morph, optModalOwner) {
// add morph inside the world or in a window (if one currently is
// marked active) so that the rest of the world/window is grayed out
// and blocked.
var modalOwner = optModalOwner || this,
modalBounds = modalOwner.innerBounds(),
blockMorph = lively.morphic.Morph.makeRectangle(modalBounds),
transparentMorph = lively.morphic.Morph.makeRectangle(blockMorph.innerBounds());
blockMorph.isEpiMorph = true;
blockMorph.applyStyle({
fill: null,
borderWidth: 0,
enableGrabbing: false,
enableDragging: false
});
transparentMorph.applyStyle({
fill: Color.black,
opacity: 0.5,
enableGrabbing: false,
enableDragging: false
});
transparentMorph.isEpiMorph = true;
blockMorph.addMorph(transparentMorph);
if (modalOwner.modalMorph) modalOwner.modalMorph.remove();
blockMorph.addMorph(morph);
var alignBounds = modalOwner.visibleBounds ?
modalOwner.visibleBounds() : modalOwner.innerBounds();
morph.align(morph.bounds().center(), alignBounds.center());
modalOwner.modalMorph = modalOwner.addMorph(blockMorph);
lively.bindings.connect(morph, 'remove', blockMorph, 'remove');
morph.focus();
return morph;
},
},
'dialogs', {
openDialog: function(dialog) {
var focusedMorph = lively.morphic.Morph.focusedMorph(),
win = this.getActiveWindow();
dialog.openIn(this, this.visibleBounds().topLeft(), focusedMorph);
this.addModal(dialog.panel, win ? win : this);
return dialog;
},
confirm: function (message, callback) {
return this.openDialog(new lively.morphic.ConfirmDialog(message, callback));
},
prompt: function (message, callback, defaultInput) {
return this.openDialog(new lively.morphic.PromptDialog(message, callback, defaultInput))
},
listPrompt: function (message, callback, list, defaultInput, optExtent) {
// $world.listPrompt('test', alert, [1,2,3,4], 3, pt(400,300));
module('lively.morphic.tools.ConfirmList').load(true);
var listPrompt = lively.BuildSpec('lively.morphic.tools.ConfirmList').createMorph();
listPrompt.promptFor({
prompt: message,
list: list,
selection: defaultInput,
extent: optExtent
});
(function() { listPrompt.get('target').focus(); }).delay(0);
lively.bindings.connect(listPrompt, 'result', {cb: callback}, 'cb');
return this.addModal(listPrompt);
},
editPrompt: function (message, callback, defaultInput) {
return this.openDialog(new lively.morphic.EditDialog(message, callback, defaultInput))
}
},
'progress bar', {
addProgressBar: function(optPt, optLabel) {
var progressBar = new lively.morphic.ProgressBar(),
center = optPt || this.visibleBounds().center();
this.addMorph(progressBar);
progressBar.align(progressBar.bounds().center(), center);
progressBar.setLabel(optLabel || '');
progressBar.ignoreEvents();
return progressBar
},
},
'preferences', {
askForUserName: function() {
var world = this;
this.prompt("Please enter your username", function(name) {
if (name) {
world.setCurrentUser(name);
alertOK("set username to: " + name);
} else {
alertOK("removing username")
world.setCurrentUser(undefined);
}
}, world.getUserName(true));
},
askForNewWorldExtent: function() {
var world = this;
this.prompt("Please enter new world extent", function(str) {
if (!str) return;
var newExtent;
try {
newExtent = eval(str);
} catch(e) {
alert("Could not eval: " + str)
};
if (! (newExtent instanceof lively.Point)) {
alert("" + newExtent + " " + "is not a proper extent")
return
}
world.setExtent(newExtent);
alertOK("Set world extent to " + newExtent);
}, this.getExtent())
},
askForNewBackgroundColor: function() {
var world = this,
oldColor = this.getFill();
if(! (oldColor instanceof Color)){
oldColor = Color.rgb(255,255,255);
}
this.prompt("Please enter new world background color", function(str) {
if (!str) return;
var newColor;
try {
newColor = eval(str);
} catch(e) {
alert("Could not eval: " + str)
};
if (! (newColor instanceof Color)) {
alert("" + newColor + " " + "is not a proper Color")
return
}
world.setFill(newColor);
alertOK("Set world background to " + newColor);
}, "Color." + oldColor)
},
setCurrentUser: function(username) {
this.currentUser = username;
if (lively.LocalStorage)
lively.LocalStorage.set('UserName', username);
},
},
'morph selection', {
withSelectedMorphsDo: function(func, context) {
// FIXME currently it is the halo target...
if (!this.currentHaloTarget) return;
func.call(context || Global, this.currentHaloTarget);
},
},
'debugging', {
resetAllScales: function() {
this.withAllSubmorphsDo(function(ea) {
ea.setScale(1);
})
},
resetScale: function () {
this.setScale(1);
this.firstHand().setScale(1)
},
checkApplicationCache: function() {
var cache = lively.ApplicationCache,
pBar = this.addProgressBar(null, 'app cache'),
handlers = {
onProgress: function(progress) {
pBar && pBar.setValue(progress.evt.loaded/progress.evt.total);
},
done: function(progress) {
disconnect(cache, 'progress', handlers, 'onProgress');
disconnect(cache, 'noupdate', handlers, 'done');
disconnect(cache, 'updateready', handlers, 'done');
pBar && pBar.remove(); }
}
connect(cache, 'progress', handlers, 'onProgress');
connect(cache, 'noupdate', handlers, 'done');
connect(cache, 'updaetready', handlers, 'done');
cache.update();
},
resetAllButtonLabels: function() {
this.withAllSubmorphsDo(function(ea) {
if (ea instanceof lively.morphic.Button) {
// doppelt haellt besser ;) (old german proverb)
ea.setLabel(ea.getLabel());
ea.setLabel(ea.getLabel());
}
})
},
},
'wiki', {
interactiveDeleteWorldOnServer: function() {
var url = URL.source;
this.world().confirm('Do you really want to delete ' + url.filename() + '?',
function(answer) {
if (!answer) return;
new WebResource(URL.source)
.statusMessage('Removed ' + url, 'Error removing ' + url, true)
.del();
})
},
getActiveWindow: function () {
for (var i = this.submorphs.length-1; i >= 0; i--) {
var morph = this.submorphs[i];
if (morph.isWindow && morph.isActive()) return morph;
}
return null;
},
closeActiveWindow: function() {
var win = this.getActiveWindow();
win && win.initiateShutdown();
return !!win;
},
activateTopMostWindow: function() {
var morphBelow = this.topMorph();
if (morphBelow && morphBelow.isWindow) {
var scroll = this.getScrollOffset && this.getScrollOffset();
morphBelow.comeForward();
if (scroll) this.setScroll(scroll.x, scroll.y);
}
},
});
lively.morphic.List.addMethods(
'documentation', {
connections: {
selection: {},
itemList: {},
selectedLineNo: {}
},
},
'settings', {
style: {
borderColor: Color.black,
borderWidth: 0,
fill: Color.gray.lighter().lighter(),
clipMode: 'auto',
fontFamily: 'Helvetica',
fontSize: 10,
enableGrabbing: false
},
selectionColor: Color.green.lighter(),
isList: true
},
'initializing', {
initialize: function($super, bounds, optItems) {
$super(bounds);
this.itemList = [];
this.selection = null;
this.selectedLineNo = -1;
if (optItems) this.updateList(optItems);
},
},
'accessing', {
setExtent: function($super, extent) {
$super(extent);
this.resizeList();
},
getListExtent: function() { return this.renderContextDispatch('getListExtent') }
},
'list interface', {
getMenu: function() { /*FIXME actually menu items*/ return [] },
updateList: function(items) {
if (!items) items = [];
this.itemList = items;
var that = this,
itemStrings = items.collect(function(ea) { return that.renderFunction(ea); });
this.renderContextDispatch('updateListContent', itemStrings);
},
addItem: function(item) {
this.updateList(this.itemList.concat([item]));
},
selectAt: function(idx) {
if (!this.isMultipleSelectionList) this.clearSelections();
this.renderContextDispatch('selectAllAt', [idx]);
this.updateSelectionAndLineNoProperties(idx);
},
saveSelectAt: function(idx) {
this.selectAt(Math.max(0, Math.min(this.itemList.length-1, idx)));
},
deselectAt: function(idx) { this.renderContextDispatch('deselectAt', idx) },
updateSelectionAndLineNoProperties: function(selectionIdx) {
var item = this.itemList[selectionIdx];
this.selectedLineNo = selectionIdx;
this.selection = item && (item.value !== undefined) ? item.value : item;
},
setList: function(items) { return this.updateList(items) },
getList: function() { return this.itemList },
getValues: function() {
return this.getList().collect(function(ea) { return ea.isListItem ? ea. value : ea})
},
setSelection: function(sel) {
this.selectAt(this.find(sel));
},
getSelection: function() { return this.selection },
getItem: function(value) {
return this.itemList[this.find(value)];
},
removeItemOrValue: function(itemOrValue) {
var idx = this.find(itemOrValue), item = this.itemList[idx];
this.updateList(this.itemList.without(item));
return item;
},
getSelectedItem: function() {
return this.selection && this.selection.isListItem ?
this.selection : this.itemList[this.selectedLineNo];
},
moveUpInList: function(itemOrValue) {
if (!itemOrValue) return;
var idx = this.find(itemOrValue);
if (idx === undefined) return;
this.changeListPosition(idx, idx-1);
},
moveDownInList: function(itemOrValue) {
if (!itemOrValue) return;
var idx = this.find(itemOrValue);
if (idx === undefined) return;
this.changeListPosition(idx, idx+1);
},
clearSelections: function() { this.renderContextDispatch('clearSelections') }
},
'private list functions', {
changeListPosition: function(oldIdx, newIdx) {
var item = this.itemList[oldIdx];
this.itemList.removeAt(oldIdx);
this.itemList.pushAt(item, newIdx);
this.updateList(this.itemList);
this.selectAt(newIdx);
},
resizeList: function(idx) {
return this.renderContextDispatch('resizeList');
},
find: function(itemOrValue) {
// returns the index in this.itemList
for (var i = 0; i < this.itemList.length; i++) {
var val = this.itemList[i];
if (val === itemOrValue || (val && val.isListItem && val.value === itemOrValue)) {
return i;
}
}
// return -1?
return undefined;
}
},
'styling', {
applyStyle: function($super, spec) {
if (spec.fontFamily !== undefined) this.setFontFamily(spec.fontFamily);
if (spec.fontSize !== undefined) this.setFontSize(spec.fontSize);
return $super(spec);
},
setFontSize: function(fontSize) { return this.morphicSetter('FontSize', fontSize) },
getFontSize: function() { return this.morphicGetter('FontSize') || 10 },
setFontFamily: function(fontFamily) { return this.morphicSetter('FontFamily', fontFamily) },
getFontFamily: function() { return this.morphicSetter('FontFamily') || 'Helvetica' }
},
'multiple selection support', {
enableMultipleSelections: function() {
this.isMultipleSelectionList = true;
this.renderContextDispatch('enableMultipleSelections');
},
getSelectedItems: function() {
var items = this.itemList;
return this.getSelectedIndexes().collect(function(i) { return items[i] });
},
getSelectedIndexes: function() { return this.renderContextDispatch('getSelectedIndexes'); },
getSelections: function() {
return this.getSelectedItems().collect(function(ea) { return ea.isListItem ? ea.value : ea; })
},
setSelections: function(arr) {
var indexes = arr.collect(function(ea) { return this.find(ea) }, this);
this.selectAllAt(indexes);
},
setSelectionMatching: function(string) {
for (var i = 0; i < this.itemList.length; i++) {
var itemString = this.itemList[i].string || String(this.itemList[i]);
if (string == itemString) this.selectAt(i);
}
},
selectAllAt: function(indexes) {
this.renderContextDispatch('selectAllAt', indexes)
},
renderFunction: function(anObject) {
return anObject.string || String(anObject);
}
});
lively.morphic.DropDownList.addMethods(
'initializing', {
initialize: function($super, bounds, optItems) {
$super(bounds, optItems);
},
});
lively.morphic.Box.subclass('lively.morphic.MorphList',
'settings', {
style: {
fill: Color.gray.lighter(3),
borderColor: Color.gray.lighter(),
borderWidth: 1,
borderStyle: 'outset',
},
isList: true
},
'initializing', {
initialize: function($super, items) {
$super(new Rectangle(0,0, 100,100));
this.itemMorphs = [];
this.setList(items || []);
this.initializeLayout();
},
initializeLayout: function(layoutStyle) {
// layoutStyle: {
// type: "tiling"|"horizontal"|"vertical",
// spacing: NUMBER,
// border: NUMBER
// }
var defaultLayout = {
type: 'tiling',
border: 0, spacing: 20
}
layoutStyle = Object.extend(defaultLayout, layoutStyle || {});
this.applyStyle({
fill: Color.white, borderWidth: 0,
borderColor: Color.black, clipMode: 'auto',
resizeWidth: true, resizeHeight: true
})
var klass;
switch (layoutStyle.type) {
case 'vertical': klass = lively.morphic.Layout.VerticalLayout; break;
case 'horizontal': klass = lively.morphic.Layout.HorizontalLayout; break;
case 'tiling': klass = lively.morphic.Layout.TileLayout; break;
default: klass = lively.morphic.Layout.TileLayout; break;
}
layouter = new klass(this);
layouter.setBorderSize(layoutStyle.border);
layouter.setSpacing(layoutStyle.spacing);
this.setLayouter(layouter);
},
},
'morph menu', {
getMenu: function() { /*FIXME actually menu items*/ return [] }
},
'list interface', {
renderFunction: function(listItem) {
if (!listItem) return listItem = {isListItem: true, string: 'invalid list item: ' + listItem};
if (listItem.morph) return listItem.morph;
var string = listItem.string || String(listItem);
return new lively.morphic.Text(lively.rect(0,0,100,20), string);
},
updateList: function(items) {
if (!items) items = [];
this.itemList = items;
this.itemMorphs = items.collect(function(ea) { return this.renderFunction(ea); }, this);
this.removeAllMorphs();
this.itemMorphs.forEach(function(ea) { this.addMorph(ea); }, this);
},
addItem: function(item) {
// this.updateList(this.itemList.concat([item]));
},
selectAt: function(idx) {
// if (!this.isMultipleSelectionList) this.clearSelections();
// this.renderContextDispatch('selectAllAt', [idx]);
// this.updateSelectionAndLineNoProperties(idx);
},
saveSelectAt: function(idx) {
// this.selectAt(Math.max(0, Math.min(this.itemList.length-1, idx)));
},
deselectAt: function(idx) {
// this.renderContextDispatch('deselectAt', idx)
},
updateSelectionAndLineNoProperties: function(selectionIdx) {
// var item = this.itemList[selectionIdx];
// this.selectedLineNo = selectionIdx;
// this.selection = item && (item.value !== undefined) ? item.value : item;
},
setList: function(items) {
return this.updateList(items);
},
getList: function() {
return this.itemList;
},
getValues: function() {
return this.getList().collect(function(ea) { return ea.isListItem ? ea. value : ea});
},
setSelection: function(sel) {
// this.selectAt(this.find(sel));
},
getSelection: function() { return this.selection },
getItem: function(value) {
// return this.itemList[this.find(value)];
},
removeItemOrValue: function(itemOrValue) {
// var idx = this.find(itemOrValue), item = this.itemList[idx];
// this.updateList(this.itemList.without(item));
// return item;
},
getSelectedItem: function() {
// return this.selection && this.selection.isListItem ?
// this.selection : this.itemList[this.selectedLineNo];
},
moveUpInList: function(itemOrValue) {
// if (!itemOrValue) return;
// var idx = this.find(itemOrValue);
// if (idx === undefined) return;
// this.changeListPosition(idx, idx-1);
},
moveDownInList: function(itemOrValue) {
// if (!itemOrValue) return;
// var idx = this.find(itemOrValue);
// if (idx === undefined) return;
// this.changeListPosition(idx, idx+1);
},
clearSelections: function() {
// this.renderContextDispatch('clearSelections');
}
},
'multiple selection support', {
enableMultipleSelections: function() {
// this.isMultipleSelectionList = true;
// this.renderContextDispatch('enableMultipleSelections');
},
getSelectedItems: function() {
// var items = this.itemList;
// return this.getSelectedIndexes().collect(function(i) { return items[i] });
},
getSelectedIndexes: function() {
//return this.renderContextDispatch('getSelectedIndexes');
},
getSelections: function() {
// return this.getSelectedItems().collect(function(ea) { return ea.isListItem ? ea.value : ea; })
},
setSelections: function(arr) {
// var indexes = arr.collect(function(ea) { return this.find(ea) }, this);
// this.selectAllAt(indexes);
},
setSelectionMatching: function(string) {
// for (var i = 0; i < this.itemList.length; i++) {
// var itemString = this.itemList[i].string || String(this.itemList[i]);
// if (string == itemString) this.selectAt(i);
// }
},
selectAllAt: function(indexes) {
// this.renderContextDispatch('selectAllAt', indexes)
}
});
lively.morphic.Button.subclass("lively.morphic.WindowControl",
'documentation', {
documentation: "Event handling for Window morphs",
},
'settings and state', {
style: {borderWidth: 0, strokeOpacity: 0, padding: Rectangle.inset(0,2), accessibleInInactiveWindow: true},
connections: ['HelpText', 'fire'],
},
'initializing', {
initialize: function($super, bnds, inset, labelString, labelOffset) {
$super(bnds, labelString)
this.label.applyStyle({fontSize: 8})
if (labelOffset) {
this.label.setPosition(this.label.getPosition().addPt(labelOffset));
}
this.setAppearanceStylingMode(true);
this.setBorderStylingMode(true);
},
});
lively.morphic.Box.subclass("lively.morphic.TitleBar",
'documentation', {
documentation: "Title bar for lively.morphic.Window",
},
'properties', {
controlSpacing: 3,
barHeight: 22,
shortBarHeight: 15,
accessibleInInactiveWindow: true,
style: {
adjustForNewBounds: true,
resizeWidth: true
},
labelStyle: {
padding: Rectangle.inset(0,0),
fixedWidth: true,
fixedHeight: true,
resizeWidth: true,
allowInput: false
}
},
'intitializing', {
initialize: function($super, headline, windowWidth, windowMorph) {
var bounds = new Rectangle(0, 0, windowWidth, this.barHeight);
$super(bounds);
this.windowMorph = windowMorph;
this.buttons = [];
// Note: Layout of submorphs happens in adjustForNewBounds (q.v.)
var label;
if (headline instanceof lively.morphic.Text) {
label = headline;
} else if (headline != null) { // String
label = lively.morphic.Text.makeLabel(headline, this.labelStyle);
}
this.label = this.addMorph(label);
this.label.addStyleClassName('window-title');
this.label.setTextStylingMode(true);
this.disableDropping();
this.setAppearanceStylingMode(true);
this.setBorderStylingMode(true);
},
addButton: function(label, optLabelOffset, optWidth) {
var length = this.barHeight - 5;
var extent = lively.pt(optWidth || length, length);
var button = this.addMorph(
new lively.morphic.WindowControl(
lively.rect(lively.pt(0, 0), extent),
this.controlSpacing,
label,
optLabelOffset || pt(0,0)));
this.buttons.push(button);
// This will align the label properly
this.adjustLabelBounds();
return button;
},
},
'label', {
setTitle: function(string) {
this.label.replaceTextString(string);
},
getTitle: function(string) { return this.label.textString }
},
'layouting', {
adjustLabelBounds: function($super) {
// $super(); adjustForNewBounds()
var innerBounds = this.innerBounds(),
sp = this.controlSpacing;
var buttonLocation = this.innerBounds().topRight().subXY(sp, -sp);
this.buttons.forEach(function(ea) {
buttonLocation = buttonLocation.subXY(ea.shape.getBounds().width, 0);
ea.setPosition(buttonLocation);
buttonLocation = buttonLocation.subXY(sp, 0)
});
if (this.label) {
var start = this.innerBounds().topLeft().addXY(sp, sp),
end = lively.pt(buttonLocation.x, innerBounds.bottomRight().y).subXY(sp, sp);
this.label.setBounds(rect(start, end));
}
},
adjustForNewBounds: function() {
$super();
this.adjustLabelBounds();
},
lookCollapsedOrNot: function(collapsed) {
this.applyStyle({borderRadius: collapsed ? "8px 8px 8px 8px" : "8px 8px 0px 0px"});
}
},
'event handling', {
onMouseDown: function (evt) {
//Functions.False,
// TODO: refactor to evt.hand.clickedOnMorph when everything else is ready for it
evt.world.clickedOnMorph = this.windowMorph;
},
onMouseUp: Functions.False
});
lively.morphic.Morph.subclass('lively.morphic.Window', Trait('lively.morphic.DragMoveTrait').derive({override: ['onDrag','onDragStart', 'onDragEnd']}),
'documentation', {
documentation: "Full-fledged windows with title bar, menus, etc"
},
'settings and state', {
state: 'expanded',
spacing: 4, // window border
minWidth: 200,
minHeight: 100,
debugMode: false,
style: {
borderWidth: false,
fill: null,
borderRadius: false,
strokeOpacity: false,
adjustForNewBounds: true,
enableDragging: true
},
isWindow: true,
isCollapsed: function() { return this.state === 'collapsed'; }
},
'initializing', {
initialize: function($super, targetMorph, titleString, optSuppressControls) {
$super(new lively.morphic.Shapes.Rectangle());
var bounds = targetMorph.bounds(),
spacing = this.spacing;
bounds.width += 2 * spacing;
bounds.height += 1 * spacing;
var titleBar = this.makeTitleBar(titleString, bounds.width, optSuppressControls),
titleHeight = titleBar.bounds().height - titleBar.getBorderWidth();
this.setBounds(bounds.withHeight(bounds.height + titleHeight));
this.makeReframeHandles();
this.titleBar = this.addMorph(titleBar);
this.contentOffset = pt(spacing, titleHeight);
this.collapsedTransform = null;
this.collapsedExtent = null;
this.expandedTransform = null;
this.expandedExtent = null;
this.ignoreEventsOnExpand = false;
this.disableDropping();
this.setAppearanceStylingMode(true);
this.setBorderStylingMode(true);
this.targetMorph = this.addMorph(targetMorph);
this.targetMorph.setPosition(this.contentOffset);
},
makeReframeHandles: function() {
// create three reframe handles (bottom, right, and bottom-right) and align them to the window
var e = this.getExtent();
this.reframeHandle = this.addMorph(new lively.morphic.ReframeHandle('corner', pt(14,14)));
this.rightReframeHandle = this.addMorph(new lively.morphic.ReframeHandle('right', e.withX(this.spacing)));
this.bottomReframeHandle = this.addMorph(new lively.morphic.ReframeHandle('bottom', e.withY(this.spacing)));
this.alignAllHandles();
},
makeTitleBar: function(titleString, width, optSuppressControls) {
// Overridden in TabbedPanelMorph
var titleBar = new lively.morphic.TitleBar(titleString, width, this);
if (optSuppressControls) return titleBar;
var closeButton = titleBar.addButton("X", pt(0,-1));
closeButton.addStyleClassName('close');
var collapseButton = titleBar.addButton("–", pt(0,1));
var menuButton = titleBar.addButton("Menu", null, 40);
closeButton.plugTo(this, {getHelpText: '->getCloseHelp', fire: '->initiateShutdown'});
menuButton.plugTo(this, {getHelpText: '->getMenuHelp', fire: '->showTargetMorphMenu'});
collapseButton.plugTo(this, {getHelpText: '->getCollapseHelp', fire: '->toggleCollapse'});
return titleBar;
},
resetTitleBar: function() {
var oldTitleBar = this.titleBar;
oldTitleBar.remove();
this.titleBar = this.makeTitleBar(oldTitleBar.label.textString, this.getExtent().x);
this.addMorph(this.titleBar);
},
},
'window behavior', {
initiateShutdown: function() {
if (this.isShutdown()) return null;
var owner = this.owner;
if (this.onShutdown) this.onShutdown();
if (this.targetMorph && this.targetMorph.onShutdown) this.targetMorph.onShutdown();
this.remove();
if (owner.activateTopMostWindow) owner.activateTopMostWindow();
this.state = 'shutdown'; // no one will ever know...
return true;
},
isShutdown: function() { return this.state === 'shutdown' }
},
'accessing', {
setTitle: function(string) { this.titleBar.setTitle(string) },
getTitle: function() { return this.titleBar.getTitle() },
getBounds: function($super) {
if (this.titleBar && this.isCollapsed()) {
var titleBarTranslation = this.titleBar.getGlobalTransform().getTranslation();
return this.titleBar.bounds().translatedBy(titleBarTranslation);
}
return $super();
}
},
'reframe handles', {
removeHalos: function($super, optWorld) {
// Sadly, this doesn't get called when click away from halo
// Need to patch World.removeHalosFor, or refactor so it calls this
this.alignAllHandles();
$super(optWorld);
},
alignAllHandles: function() {
if (this.isCollapsed()) return;
this.reframeHandle && this.reframeHandle.alignWithWindow();
this.bottomReframeHandle && this.bottomReframeHandle.alignWithWindow();
this.rightReframeHandle && this.rightReframeHandle.alignWithWindow();
}
},
'menu', {
showTargetMorphMenu: function() {
var target = this.targetMorph || this, itemFilter;
if (this.targetMorph) {
var self = this;
itemFilter = function (items) {
items[0] = ['Publish window', function(evt) {
self.copyToPartsBinWithUserRequest();
}];
// set fixed support
var fixItem = items.find(function (ea) {
return ea[0] == "set fixed" || ea[0] == "set unfixed" });
if (fixItem) {
if (self.isFixed) {
fixItem[0] = "set unfixed";
fixItem[1] = function() {
self.setFixed(false);
}
} else {
fixItem[0] = "set fixed"
fixItem[1] = function() {
self.setFixed(true);
}
}
}
items[1] = ['Set window title', function(evt) {
self.world().prompt('Set window title', function(input) {
if (input !== null) self.titleBar.setTitle(input || '');
}, self.titleBar.getTitle());
}];
if (self.targetMorph.ownerApp && self.targetMorph.ownerApp.morphMenuItems) {
self.targetMorph.ownerApp.morphMenuItems().each(function(ea) {items.push(ea)})
}
return items;
}
}
var menu = target.createMorphMenu(itemFilter);
var menuBtnTopLeft = this.menuButton.bounds().topLeft();
var menuTopLeft = menuBtnTopLeft.subPt(pt(menu.bounds().width, 0));
menu.openIn(
lively.morphic.World.current(),
this.getGlobalTransform().transformPoint(menuTopLeft),
false);
},
morphMenuItems: function($super) {
var self = this, world = this.world(), items = $super();
items[0] = ['Publish window', function(evt) { self.copyToPartsBinWithUserRequest(); }];
items.push([
'Set title', function(evt) {
world.prompt('Enter new title', function(input) {
if (input || input == '') self.setTitle(input);
}, self.getTitle()); }]);
return items;
}
},
'mouse event handling', {
highlight: function(trueForLight) {
this.highlighted = trueForLight;
if (trueForLight) {
this.addStyleClassName('highlighted');
} else {
this.removeStyleClassName('highlighted');
}
},
isInFront: function() { return this.owner && this.owner.topMorph() === this },
isActive: function() {
return this.isInFront() && this.world() && this.highlighted;
},
comeForward: function() {
// adds the window before each other morph in owner
// this resets the scroll in HTML, fix for now -- gather before and set it afterwards
// step 1: highlight me and remove highlight from other windows
if (!this.isActive()) {
this.world().submorphs.forEach(function(ea) {
ea !== this && ea.isWindow && ea.highlight(false); }, this);
this.highlight(true);
}
var inner = this.targetMorph,
callGetsFocus = inner && !!inner.onWindowGetsFocus;
if (this.isInFront()) { if (callGetsFocus) { inner.onWindowGetsFocus(this); }; return; }
// step 2: make me the frontmost morph of the world
var scrolledMorphs = [], scrolls = [];
this.withAllSubmorphsDo(function(ea) {
var scroll = ea.getScroll();
if (!scroll[0] && !scroll[1]) return;
scrolledMorphs.push(ea); scrolls.push(scroll);
});
this.owner.addMorphFront(this); // come forward
this.alignAllHandles();
(function() {
scrolledMorphs.forEach(function(ea, i) { ea.setScroll(scrolls[i][0], scrolls[i][1]) });
if (callGetsFocus) { inner.onWindowGetsFocus(this); }
}).bind(this).delay(0);
},
onMouseDown: function(evt) {
var wasInFront = this.isActive();
if (wasInFront) return false; // was: $super(evt);
this.comeForward();
// rk 2013-04-27: disable accessibleInInactiveWindow test for now
// this test is not used and windows seem to work fine without it
// the code for that feature was:
// if (this.morphsContainingPoint(evt.getPosition()).detect(function(ea) {
// return ea.accessibleInInactiveWindow || true })) return false;
// this.cameForward = true; // for stopping the up as well
// evt.world.clickedOnMorph = null; // dont initiate drag, FIXME, global state!
// evt.stop(); // so that text, lists that are automatically doing things are not modified
// return true;
this.cameForward = true; // for stopping the up as well
return false;
},
onMouseUp: function(evt) {
if (!this.cameForward) return false;
this.cameForward = false;
return false;
},
wantsToBeDroppedInto: function(dropTarget) {
return dropTarget.isWorld;
}
},
'debugging', {
toString: function($super) {
return $super() + ' ' + (this.titleBar ? this.titleBar.getTitle() : '');
}
},
'removing', {
remove: function($super) {
// should trigger remove of submorphs but remove is also usedelsewhere (grab)
// this.targetMorph && this.targetMorph.remove();
return $super();
}
},
'collapsing', {
toggleCollapse: function() {
return this.isCollapsed() ? this.expand() : this.collapse();
},
collapse: function() {
if (this.isCollapsed()) return;
this.expandedTransform = this.getTransform();
this.expandedExtent = this.getExtent();
this.expandedPosition = this.getPosition();
this.targetMorph.onWindowCollapse && this.targetMorph.onWindowCollapse();
this.targetMorph.remove();
this.helperMorphs = this.submorphs.withoutAll([this.targetMorph, this.titleBar]);
this.helperMorphs.invoke('remove');
if(this.titleBar.lookCollapsedOrNot) this.titleBar.lookCollapsedOrNot(true);
var finCollapse = function () {
this.state = 'collapsed'; // Set it now so setExtent works right
if (this.collapsedTransform) this.setTransform(this.collapsedTransform);
if (this.collapsedExtent) this.setExtent(this.collapsedExtent);
if (this.collapsedPosition) this.setPosition(this.collapsedPosition);
this.shape.setBounds(this.titleBar.bounds());
}.bind(this);
if (this.collapsedPosition && this.collapsedPosition.dist(this.getPosition()) > 100)
this.animatedInterpolateTo(this.collapsedPosition, 5, 50, finCollapse);
else finCollapse();
},
expand: function() {
if (!this.isCollapsed()) return;
this.collapsedTransform = this.getTransform();
this.collapsedExtent = this.innerBounds().extent();
this.collapsedPosition = this.getPosition();
var finExpand = function () {
this.state = 'expanded';
if (this.expandedTransform)
this.setTransform(this.expandedTransform);
if (this.expandedExtent) {
this.setExtent(this.expandedExtent);
}
if (this.expandedPosition) {
this.setPosition(this.expandedPosition);
}
this.addMorph(this.targetMorph);
this.helperMorphs.forEach(function(ea) {
this.addMorph(ea)
}, this);
// Bring this window forward if it wasn't already
this.owner && this.owner.addMorphFront(this);
this.targetMorph.onWindowExpand && this.targetMorph.onWindowExpand();
}.bind(this);
if (this.expandedPosition && this.expandedPosition.dist(this.getPosition()) > 100)
this.animatedInterpolateTo(this.expandedPosition, 5, 50, finExpand);
else finExpand();
if(this.titleBar.lookCollapsedOrNot) this.titleBar.lookCollapsedOrNot(false);
}
});
lively.morphic.Box.subclass('lively.morphic.ReframeHandle',
'initializing', {
initialize: function($super, type, extent) {
// type is either "bottom" or "right" or "corner"
// FIXME refactor this into subclasses?
$super(extent.extentAsRectangle());
this.type = type;
this.addStyleClassName('reframe-handle ' + type);
var style = {};
if (this.type === 'right' || this.type === 'corner') { style.moveHorizontal = true; }
if (this.type === 'bottom' || this.type === 'corner') { style.moveVertical = true; }
this.applyStyle(style);
}
},
'event handling', {
onDragStart: function($super, evt) {
this.startDragPos = evt.getPosition();
this.originalTargetExtent = this.owner.getExtent();
evt.stop(); return true;
},
onDrag: function($super, evt) {
var moveDelta = evt.getPosition().subPt(this.startDragPos);
if (this.type === 'bottom') { moveDelta.x = 0; }
if (this.type === 'right') { moveDelta.y = 0; }
var newExtent = this.originalTargetExtent.addPt(moveDelta);
if (newExtent.x < this.owner.minWidth) newExtent.x = this.owner.minWidth;
if (newExtent.y < this.owner.minHeight) newExtent.y = this.owner.minHeight;
this.owner.setExtent(newExtent);
evt.stop(); return true;
},
onDragEnd: function($super, evt) {
delete this.originalTargetExtent;
delete this.startDragPos;
this.owner.alignAllHandles();
evt.stop(); return true;
}
},
'alignment', {
alignWithWindow: function() {
this.bringToFront();
var window = this.owner,
windowExtent = window.getExtent(),
handleExtent = this.getExtent(),
handleBounds = this.bounds();
if (this.type === 'corner') {
this.align(handleBounds.bottomRight(), windowExtent);
}
if (this.type === 'bottom') {
var newExtent = handleExtent.withX(windowExtent.x - window.reframeHandle.getExtent().x);
this.setExtent(newExtent);
this.align(handleBounds.bottomLeft(), windowExtent.withX(0));
}
if (this.type === 'right') {
var newExtent = handleExtent.withY(windowExtent.y - window.reframeHandle.getExtent().y);
this.setExtent(newExtent);
this.align(handleBounds.topRight(), windowExtent.withY(0));
}
}
});
Object.subclass('lively.morphic.App',
'properties', {
initialViewExtent: pt(350, 200)
},
'initializing', {
buildView: function(extent) {
throw new Error('buildView not implemented!');
}
},
'accessing', {
getInitialViewExtent: function(hint) {
return hint || this.initialViewExtent;
}
},
'opening', {
openIn: function(world, pos) {
var view = this.buildView(this.getInitialViewExtent());
view.ownerApp = this; // for debugging
this.view = view;
if (pos) view.setPosition(pos);
if (world.currentScene) world = world.currentScene;
return world.addMorph(view);
},
open: function() {
return this.openIn(lively.morphic.World.current());
}
},
'removing', {
removeTopLevel: function() {
if (this.view) this.view.remove();
}
});
lively.morphic.App.subclass('lively.morphic.AbstractDialog',
'documentation', {
connections: ['result']
},
'properties', {
doNotSerialize: ['lastFocusedMorph'],
initialViewExtent: pt(300, 90),
inset: 4
},
'initializing', {
initialize: function(message, callback) {
this.result = null;
this.message = message || '?';
if (callback) this.setCallback(callback);
},
openIn: function($super, owner, pos) {
this.lastFocusedMorph = lively.morphic.Morph.focusedMorph();
return $super(owner, pos);
},
buildPanel: function(bounds) {
this.panel = new lively.morphic.Box(bounds);
this.panel.applyStyle({
fill: Color.rgb(210,210,210),
borderColor: Color.gray.darker(),
borderWidth: 1,
adjustForNewBounds: true, // layouting
enableGrabbing: false,
enableDragging: false,
lock: true
});
},
buildLabel: function() {
var bounds = new lively.Rectangle(this.inset, this.inset,
this.panel.getExtent().x - 2*this.inset, 18);
this.label = new lively.morphic.Text(bounds, this.message).beLabel({
fill: Color.white,
fixedHeight: false, fixedWidth: false,
padding: Rectangle.inset(0,0),
enableGrabbing: false, enableDragging: false});
this.panel.addMorph(this.label);
// FIXME ugly hack for wide dialogs:
// wait until dialog opens and text is rendered so that we can
// determine its extent
this.label.fit();
(function fit() {
this.label.cachedBounds=null
var labelBoundsFit = this.label.bounds(),
origPanelExtent = this.panel.getExtent(),
panelExtent = origPanelExtent;
if (labelBoundsFit.width > panelExtent.x) {
panelExtent = panelExtent.withX(labelBoundsFit.width + 2*this.inset);
}
if (labelBoundsFit.height > bounds.height) {
var morphsBelowLabel = this.panel.submorphs.without(this.label).select(function(ea) {
return ea.bounds().top() <= labelBoundsFit.bottom(); }),
diff = labelBoundsFit.height - bounds.height;
panelExtent = panelExtent.addXY(0, diff);
}
this.panel.setExtent(panelExtent);
this.panel.moveBy(panelExtent.subPt(origPanelExtent).scaleBy(0.5).negated());
}).bind(this).delay(0);
},
buildCancelButton: function() {
var bounds = new Rectangle(0,0, 60, 30),
btn = new lively.morphic.Button(bounds, 'Cancel');
btn.align(btn.bounds().bottomRight().addXY(this.inset, this.inset), this.panel.innerBounds().bottomRight())
btn.applyStyle({moveHorizontal: true, moveVertical: true, padding: rect(pt(0,6),pt(0,6))})
this.cancelButton = this.panel.addMorph(btn);
lively.bindings.connect(btn, 'fire', this, 'removeTopLevel')
},
buildOKButton: function() {
var bounds = new Rectangle(0,0, 60, 30),
btn = new lively.morphic.Button(bounds, 'OK');
btn.align(btn.bounds().bottomRight().addXY(this.inset, 0), this.cancelButton.bounds().bottomLeft())
btn.applyStyle({moveHorizontal: true, moveVertical: true, padding: rect(pt(0,6),pt(0,6))})
this.okButton = this.panel.addMorph(btn);
lively.bindings.connect(btn, 'fire', this, 'removeTopLevel')
},
buildView: function(extent) {
this.buildPanel(extent.extentAsRectangle());
this.buildLabel();
this.buildCancelButton();
this.buildOKButton();
return this.panel;
},
},
'callbacks', {
setCallback: function(func) {
this.callback = func;
connect(this, 'result', this, 'triggerCallback')
},
triggerCallback: function(resultBool) {
this.removeTopLevel();
if (this.callback) this.callback(resultBool);
if (this.lastFocusedMorph) this.lastFocusedMorph.focus();
},
});
lively.morphic.AbstractDialog.subclass('lively.morphic.ConfirmDialog',
'properties', {
initialViewExtent: pt(260, 70),
},
'initializing', {
buildView: function($super, extent) {
var panel = $super(extent);
lively.bindings.connect(this.cancelButton, 'fire', this, 'result', {
converter: function() { return false; }});
lively.bindings.connect(this.okButton, 'fire', this, 'result', {
converter: function() { return true; }});
lively.bindings.connect(panel, 'onEscPressed', this, 'result', {
converter: function(evt) { Global.event && Global.event.stop(); return false; }});
lively.bindings.connect(panel, 'onEnterPressed', this, 'result', {
converter: function(evt) { Global.event && Global.event.stop(); return true; }});
return panel;
},
});
lively.morphic.AbstractDialog.subclass('lively.morphic.PromptDialog',
// new lively.morphic.PromptDialog('Test', function(input) { alert(input) }).open()
'initializing', {
initialize: function($super, label, callback, defaultInput) {
$super(label, callback, defaultInput);
this.defaultInput = defaultInput;
},
buildTextInput: function(bounds) {
var input = lively.BuildSpec("lively.ide.tools.CommandLine").createMorph();
input.textString = this.defaultInput || '';
input.setBounds(this.label.bounds().insetByPt(pt(this.label.getPosition().x * 2, 0)));
input.align(input.getPosition(), this.label.bounds().bottomLeft().addPt(pt(0,5)));
lively.bindings.connect(input, 'savedTextString', this, 'result');
lively.bindings.connect(input, 'onEscPressed', this, 'result', {converter: function() { return null } });
lively.bindings.connect(this.panel, 'onEscPressed', this, 'result', {converter: function() { return null}});
input.applyStyle({resizeWidth: true, moveVertical: true});
this.inputText = this.panel.addMorph(input);
},
buildView: function($super, extent) {
var panel = $super(extent);
this.buildTextInput();
lively.bindings.connect(this.cancelButton, 'fire', this, 'result', {
converter: function() { return null }});
lively.bindings.connect(this.okButton, 'fire', this.inputText, 'doSave')
return panel;
},
},
'opening', {
openIn: function($super, owner, pos) {
var view = $super(owner, pos);
// delayed because selectAll will scroll the world on text focus
// sometimes the final pos of the dialog is different to the pos here
// so dialog will open at wrong place, focus, world scrolls to the top,
// dialog is moved and out of frame
this.inputText.focus();
this.inputText.selectAll.bind(this.inputText).delay(0);
return view;
},
});
lively.morphic.AbstractDialog.subclass('lively.morphic.EditDialog',
// new lively.morphic.PromptDialog('Test', function(input) { alert(input) }).open()
'initializing', {
initialize: function($super, label, callback, defaultInput) {
$super(label, callback, defaultInput);
this.defaultInput = defaultInput;
},
buildTextInput: function() {
var bounds = rect(this.label.bounds().bottomLeft(), this.cancelButton.bounds().topRight()).insetBy(5),
input = lively.ide.newCodeEditor(bounds, this.defaultInput || '').applyStyle({
resizeWidth: true, moveVertical: true,
gutter: false, lineWrapping: true,
borderWidth: 1, borderColor: Color.gray.lighter(),
textMode: 'text'
});
input.setBounds(bounds);
this.inputText = this.panel.addMorph(input);
input.focus.bind(input).delay(0);
lively.bindings.connect(input, 'savedTextString', this, 'result');
},
buildView: function($super, extent) {
var panel = $super(extent);
panel.setExtent(pt(400,200))
this.buildTextInput();
lively.bindings.connect(this.cancelButton, 'fire', this, 'result', {
converter: function() { return null }});
lively.bindings.connect(this.okButton, 'fire', this.inputText, 'doSave')
return panel;
}
},
'opening', {
openIn: function($super, owner, pos) {
var view = $super(owner, pos);
// delayed because selectAll will scroll the world on text focus
// sometimes the final pos of the dialog is different to the pos here
// so dialog will open at wrong place, focus, world scrolls to the top,
// dialog is moved and out of frame
this.inputText.selectAll.bind(this.inputText).delay(0);
return view;
}
});
lively.morphic.App.subclass('lively.morphic.WindowedApp',
'opening', {
openIn: function(world, pos) {
var view = this.buildView(this.getInitialViewExtent()),
window = world.addFramedMorph(view, this.defaultTitle);
if (world.currentScene) world.currentScene.addMorph(window); // FIXME
view.ownerApp = this; // for debugging
this.view = window;
return window;
}
});
// COPIED from Widgets.js SelectionMorph
lively.morphic.Box.subclass('lively.morphic.Selection',
'documentation', {
documentation: 'selection "tray" object that allows multiple objects to be moved and otherwise manipulated simultaneously'
},
'settings', {
style: {fill: null, borderWidth: 1, borderColor: Color.darkGray},
isEpiMorph: true,
doNotRemove: true,
propagate: true,
isSelection: true,
},
'initializing', {
initialize: function($super, initialBounds) {
$super(initialBounds);
this.applyStyle(this.style);
this.selectedMorphs = [];
this.selectionIndicators = [];
this.setBorderStylingMode(true);
this.setAppearanceStylingMode(true);
},
},
'propagation', {
withoutPropagationDo: function(func) {
// emulate COP
this.propagate = false;
func.call(this);
this.propagate = true;
},
isPropagating: function() {
return this.propagate
},
},
'menu', {
morphMenuItems: function($super) {
var items = $super();
if (this.selectedMorphs.length === 1) {
var self = this;
items.push(["open ObjectEditor for selection", function(){
$world.openObjectEditorFor(self.selectedMorphs[0])
}])
}
items.push(["align vertically", this.alignVertically.bind(this)]);
items.push(["space vertically", this.spaceVertically.bind(this)]);
items.push(["align horizontally", this.alignHorizontally.bind(this)]);
items.push(["space horizontally", this.spaceHorizontally.bind(this)]);
if (this.selectedMorphs.length == 1) {
items.push(["ungroup", this.unGroup.bind(this)]);
} else {
items.push(["group", this.makeGroup.bind(this)]);
}
items.push(["align to grid...", this.alignToGrid.bind(this)]);
return items;
},
},
'copying', {
copy: function($super) {
this.isEpiMorph = false;
var selOwner = this.owner, copied;
try { copied = this.addSelectionWhile($super); } finally { this.isEpiMorph = true }
this.reset();
this.selectedMorphs = copied.selectedMorphs.clone();
copied.reset();
return this;
},
},
'selection handling', {
addSelectionWhile: function(func) {
// certain operations require selected morphs to be added to selection frame
// e.g. for transformations or copying
// use this method to add them for certain operations
var world = this.world();
if (!world || !this.isPropagating()) return func();
var owners = [];
for (var i = 0; i < this.selectedMorphs.length; i++) {
owners[i] = this.selectedMorphs[i].owner;
this.addMorph(this.selectedMorphs[i]);
}
try { return func() } finally {
for (var i = 0; i < this.selectedMorphs.length; i++)
owners[i].addMorph(this.selectedMorphs[i]);
}
},
},
'removing', {
remove: function() {
if (this.isPropagating())
this.selectedMorphs.invoke('remove');
this.removeOnlyIt();
},
removeOnlyIt: function() {
if (this.myWorld == null) {
this.myWorld = this.world();
}
// this.myWorld.currentSelection = null;
Class.getSuperPrototype(this).remove.call(this);
},
},
'accessing', {
world: function($super) {
return $super() || this.owner || this.myWorld
},
setBorderWidth: function($super, width) {
if (!this.selectedMorphs || !this.isPropagating()) $super(width);
else this.selectedMorphs.invoke('withAllSubmorphsDo',
function(ea) { ea.setBorderWidth(width)});
},
setFill: function($super, color) {
if (!this.selectedMorphs || !this.isPropagating())
$super(color);
else this.selectedMorphs.invoke('withAllSubmorphsDo',
function(ea) { ea.setFill(color)});
},
setBorderColor: function($super, color) {
if (!this.selectedMorphs || !this.isPropagating()) $super(color);
else this.selectedMorphs.invoke('withAllSubmorphsDo',
function(ea) { ea.setBorderColor(color)});
},
shapeRoundEdgesBy: function($super, r) {
if (!this.selectedMorphs || !this.isPropagating()) $super(r);
else this.selectedMorphs.forEach(
function(m) { if (m.shape.roundEdgesBy) m.shapeRoundEdgesBy(r); });
},
setFillOpacity: function($super, op) {
if (!this.selectedMorphs || !this.isPropagating()) $super(op);
else this.selectedMorphs.invoke('withAllSubmorphsDo',
function(ea) { ea.setFillOpacity(op)});
},
setStrokeOpacity: function($super, op) {
if (!this.selectedMorphs || !this.isPropagating()) $super(op);
else this.selectedMorphs.invoke('callOnAllSubmorphs',
function(ea) { ea.setStrokeOpacity(op)});
},
setTextColor: function(c) {
if (!this.selectedMorphs || !this.isPropagating()) return;
this.selectedMorphs.forEach( function(m) { if (m.setTextColor) m.setTextColor(c); });
},
setFontSize: function(c) {
if (!this.selectedMorphs || !this.isPropagating()) return;
this.selectedMorphs.forEach( function(m) { if (m.setFontSize) m.setFontSize(c); });
},
setFontFamily: function(c) {
if (!this.selectedMorphs || !this.isPropagating()) return;
this.selectedMorphs.forEach( function(m) { if (m.setFontFamily) m.setFontFamily(c); });
},
setRotation: function($super, theta) {
this.addSelectionWhile($super.curry(theta));
},
setScale: function($super, scale) {
this.addSelectionWhile($super.curry(scale));
},
adjustOrigin: function($super, origin) {
this.withoutPropagationDo(function() {
return $super(origin)
});
},
},
'aligning', {
// Note: the next four methods should be removed after we have gridding, i think (DI)
alignVertically: function() {
// Align all morphs to same left x as the top one.
//console.log("this=" + Object.inspect(this)); if(true) return;
var morphs = this.selectedMorphs.slice(0).sort(function(m,n) {return m.getPosition().y - n.getPosition().y});
var minX = morphs[0].getPosition().x; // align to left x of top morph
morphs.forEach(function(m) { m.setPosition(pt(minX,m.getPosition().y)) });
},
alignHorizontally: function() {
var minY = 9999;
this.selectedMorphs.forEach(function(m) { minY = Math.min(minY, m.getPosition().y); });
this.selectedMorphs.forEach(function(m) { m.setPosition(pt(m.getPosition().x, minY)) });
},
spaceVertically: function() {
// Sort the morphs vertically
var morphs = this.selectedMorphs.clone().sort(function(m,n) {return m.getPosition().y - n.getPosition().y});
// Align all morphs to same left x as the top one.
var minX = morphs[0].getPosition().x;
var minY = morphs[0].getPosition().y;
// Compute maxY and sumOfHeights
var maxY = minY;
var sumOfHeights = 0;
morphs.forEach(function(m) {
var ht = m.innerBounds().height;
sumOfHeights += ht;
maxY = Math.max(maxY, m.getPosition().y + ht);
});
// Now spread them out to fit old top and bottom with even spacing between
var separation = (maxY - minY - sumOfHeights)/Math.max(this.selectedMorphs.length - 1, 1);
var y = minY;
morphs.forEach(function(m) {
m.setPosition(pt(minX, y));
y += m.innerBounds().height + separation;
});
},
spaceHorizontally: function() {
// Sort the morphs vertically
var morphs = this.selectedMorphs.clone().sort(function(m, n) {
return m.getPosition().x - n.getPosition().x;
});
// Align all morphs to same left x as the top one.
var minX = morphs[0].getPosition().x;
var minY = morphs[0].getPosition().y;
// Compute maxX and sumOfWidths
var maxX = minY;
var sumOfWidths = 0;
morphs.forEach(function(m) {
var wid = m.innerBounds().width;
sumOfWidths += wid;
maxX = Math.max(maxX, m.getPosition().x + wid);
}); // Now spread them out to fit old top and bottom with even spacing between
var separation = (maxX - minX - sumOfWidths)/Math.max(this.selectedMorphs.length - 1, 1);
var x = minX;
morphs.forEach(function(m) {
m.setPosition(pt(x, minY));
x += m.innerBounds().width + separation;
});
},
alignToGrid: function() {
this.selectedMorphs.forEach(function(ea) {
ea.setPosition(ea.getPosition().roundTo(10));
});
}
},
'grabbing', {
grabByHand: function(hand) {
this.withoutPropagationDo(function() {
hand.addMorph(this);
for (var i = 0; i < this.selectedMorphs.length; i++) {
hand.addMorph(this.selectedMorphs[i]);
}
})
},
dropOn: function(morph) {
this.withoutPropagationDo(function() {
morph.addMorph(this);
for (var i = 0; i < this.selectedMorphs.length; i++) {
morph.addMorph(this.selectedMorphs[i]);
}
});
},
},
'geometry', {
moveBy: function($super, delta) {
// Jens: I would like to express this in a layer...
if (this.isPropagating()) {
for (var i = 0; i < this.selectedMorphs.length; i++ )
this.selectedMorphs[i].moveBy(delta);
}
$super(delta);
},
setPosition: function($super, pos) {
var delta = pos.subPt(this.getPosition())
// Jens: I would like to express this in a layer...
if (this.isPropagating() && this.selectedMorphs) {
for (var i = 0; i < this.selectedMorphs.length; i++ ) {
// alertOK("set pos move " + printStack())
this.selectedMorphs[i].moveBy(delta);
}
}
return $super(pos);
},
},
'world', {
reset: function() {
this.selectedMorphs = [];
this.setRotation(0)
this.setScale(1)
this.removeOnlyIt();
this.removeSelecitonIndicators();
this.adjustOrigin(pt(0,0));
},
selectMorphs: function(selectedMorphs) {
if (!this.owner) lively.morphic.World.current().addMorph(this);
this.selectedMorphs = selectedMorphs;
// add selection indicators for all selected morphs
this.removeSelecitonIndicators();
selectedMorphs.forEach(function(ea) {
var innerBounds = ea.getTransform().inverse().transformRectToRect(ea.bounds().insetBy(-4)),
bounds = ea.getTransform().transformRectToRect(innerBounds),
selectionIndicator = new lively.morphic.Morph.makeRectangle(innerBounds);
selectionIndicator.name = 'Selection of ' + ea;
selectionIndicator.isEpiMorph = true;
selectionIndicator.isSelectionIndicator = true;
selectionIndicator.setBorderStylingMode(true);
selectionIndicator.setAppearanceStylingMode(true);
selectionIndicator.addStyleClassName('selection-indicator');
ea.addMorph(selectionIndicator);
this.selectionIndicators.push(selectionIndicator);
}, this);
// resize selection morphs so ot fits selection indicators
var bnds = this.selectionIndicators.invoke('globalBounds'),
selBounds = bnds.slice(1).inject(bnds[0], function(bounds, selIndicatorBounds) {
return bounds.union(selIndicatorBounds); });
this.withoutPropagationDo(function() { this.setBounds(selBounds); });
},
removeSelecitonIndicators: function() {
if (this.selectionIndicators)
this.selectionIndicators.invoke('remove');
this.selectionIndicators.clear();
},
makeGroup: function() {
if (!this.selectedMorphs) return;
var group = new lively.morphic.Box(this.bounds());
group.isGroup = true;
this.owner.addMorph(group);
this.selectedMorphs.forEach(function(ea) {
group.addMorph(ea); });
this.selectMorphs([group]);
return group;
},
unGroup: function() {
if (!this.selectedMorphs || this.selectedMorphs.length !== 1) return;
var group = this.selectedMorphs[0]
var all = group.submorphs
group.submorphs.forEach(function(ea) {
this.owner.addMorph(ea)
}.bind(this))
this.selectMorphs(all)
},
},
'keyboard events', {
doKeyCopy: function() {
if (!this.selectedMorphs.length) return;
var copies = this.selectedMorphs.invoke('copy'),
carrier = lively.morphic.Morph.makeRectangle(0,0,1,1);
carrier.isMorphClipboardCarrier = true;
copies.forEach(function(ea) {
carrier.addMorph(ea);
ea.setPosition(this.localize(ea.getPosition()));
}, this);
carrier.doKeyCopy();
}
});
Trait('SelectionMorphTrait',
'selection', {
getSelectedMorphs: function() {
return this.selectionMorph.selectedMorphs
},
setSelectedMorphs: function(morphs) {
if (!morphs || morphs.length === 0) { this.resetSelection(); return; }
if (!this.selectionMorph) this.resetSelection();
this.selectionMorph.selectMorphs(morphs);
this.selectionMorph.showHalos();
return morphs;
},
hasSelection: function() {
return this.selectionMorph && !!this.selectionMorph.owner;
},
onDragStart: function(evt) {
if (evt.isRightMouseButtonDown()) {
return; // no selection with right mouse button (fbo 2011-09-13)
}
this.resetSelection()
if (this.selectionMorph.owner !== this)
this.addMorph(this.selectionMorph);
var pos = this.localize(this.eventStartPos || evt.getPosition());
this.selectionMorph.withoutPropagationDo(function() {
this.selectionMorph.setPosition(pos)
this.selectionMorph.setExtent(pt(1, 1))
this.selectionMorph.initialPosition = pos;
}.bind(this))
},
onDrag: function(evt) {
if (!this.selectionMorph) return
var p1 = this.localize(evt.getPosition()),
p2 = this.selectionMorph.initialPosition;
// alert("p1" + p1 + " p2" + p2)
var topLeft = pt(Math.min(p1.x, p2.x), Math.min(p1.y, p2.y))
var bottomRight = pt(Math.max(p1.x, p2.x), Math.max(p1.y, p2.y))
this.selectionMorph.setPosition(topLeft);
this.selectionMorph.setExtent(bottomRight.subPt(topLeft));
},
onDragEnd: function(evt) {
var self = this;
if (!self.selectionMorph) return;
var selectionBounds = self.selectionMorph.bounds();
var selectedMorphs = this.submorphs
.reject(function(ea){
return ea === self || ea.isEpiMorph || ea instanceof lively.morphic.HandMorph
})
.select(function(m) {
return selectionBounds.containsRect(m.bounds())})
.reverse()
this.selectionMorph.selectedMorphs = selectedMorphs;
if (selectedMorphs.length == 0) {
this.selectionMorph.removeOnlyIt();
return
}
this.selectionMorph.selectMorphs(selectedMorphs);
this.selectionMorph.showHalos()
},
resetSelection: function() {
if (!this.selectionMorph || !this.selectionMorph.isSelection)
this.selectionMorph = new lively.morphic.Selection(new Rectangle(0,0,0,0))
this.selectionMorph.reset();
},
})
.applyTo(lively.morphic.World, {override: ['onDrag', 'onDragStart', 'onDragEnd']});
module('lively.ide'); // so that the namespace is defined even if ide is not loaded
Object.extend(lively.ide, {
openFile: function(url) {
require('lively.ide.tools.TextEditor').toRun(function() {
var editor = lively.BuildSpec('lively.ide.tools.TextEditor').createMorph();
if (url) {
if (!String(url).startsWith('http')) url = URL.codeBase.withFilename(url);
editor.openURL(url);
}
editor.openInWorld($world.positionForNewMorph(editor)).comeForward();
});
}
});
lively.morphic.Box.subclass('lively.morphic.HorizontalDivider',
'settings', {
style: {fill: Color.gray, enableDragging: true},
},
'initializing', {
initialize: function($super, bounds) {
$super(bounds);
this.fixed = [];
this.scalingBelow = [];
this.scalingAbove = [];
this.minHeight = 20;
this.pointerConnection = null;
},
},
'mouse events', {
onDragStart: function(evt) {
this.oldPoint = evt.getPosition();
return true;
},
onDrag: function(evt) {
var p1 = this.oldPoint,
p2 = evt.getPosition(),
deltaY = p2.y - p1.y;
this.oldPoint = p2;
this.movedVerticallyBy(deltaY);
return true;
},
correctForDragOffset: Functions.False
},
'internal slider logic', {
divideRelativeToParent: function(ratio) {
// 0 <= ratio <= 1. Set divider so that it divides its owner by ration.
// |--------| |--------| |<======>|
// | | | | | |
// | | | | | |
// |<======>| = 0.5 | | = 1 | | = 0
// | | | | | |
// | | | | | |
// |--------| |<======>| |--------|
if (!this.owner || !Object.isNumber(ratio) || ratio < 0 || ratio > 1) return;
var ownerHeight = this.owner.getExtent().y - this.getExtent().y;
if (ownerHeight < 0) return;
var currentRatio = this.getRelativeDivide(),
deltaRation = ratio - currentRatio,
deltaY = ownerHeight * deltaRation;
this.movedVerticallyBy(deltaY);
},
getRelativeDivide: function(ratio) {
var bounds = this.bounds(),
myTop = bounds.top(),
myHeight = bounds.height,
ownerHeight = this.owner.getExtent().y - myHeight;
if (ownerHeight < 0) return NaN;
return myTop / ownerHeight;
},
movedVerticallyBy: function(deltaY) {
if (!this.resizeIsSave(deltaY)) return;
var morphsForPosChange = this.fixed.concat(this.scalingBelow);
morphsForPosChange.forEach(function(m) {
var pos = m.getPosition();
m.setPosition(pt(pos.x, pos.y + deltaY));
});
this.scalingAbove.forEach(function(m) {
var ext = m.getExtent();
m.setExtent(pt(ext.x, ext.y + deltaY));
});
this.scalingBelow.forEach(function(m) {
var ext = m.getExtent();
m.setExtent(pt(ext.x, ext.y - deltaY));
});
this.setPosition(this.getPosition().addPt(pt(0, deltaY)));
},
resizeIsSave: function(deltaY) {
return this.scalingAbove.all(function(m) { return (m.getExtent().y + deltaY) >= this.minHeight }, this)
&& this.scalingBelow.all(function(m) { return (m.getExtent().y - deltaY) >= this.minHeight }, this);
},
addFixed: function(m) { if (!this.fixed.include(m)) this.fixed.push(m) },
addScalingAbove: function(m) { this.scalingAbove.push(m) },
addScalingBelow: function(m) { this.scalingBelow.push(m) }
});
lively.morphic.Box.subclass('lively.morphic.Slider',
'settings', {
style: {
borderColor: Color.darkGray,
borderWidth: 1,
borderRadius: 6,
fill: Styles.sliderBackgroundGradient(Color.gray, "NorthSouth")
},
connections: {
value: {}
},
mss: 12, // "minimum slider size"
isSlider: true
},
'initializing', {
initialize: function($super, initialBounds, scaleIfAny) {
$super(initialBounds);
connect(this, 'value', this, 'adjustSliderParts');
this.setValue(0);
this.setSliderExtent(0.1);
this.valueScale = (scaleIfAny === undefined) ? 1.0 : scaleIfAny;
this.sliderKnob = this.addMorph(
new lively.morphic.SliderKnob(new Rectangle(0, 0, this.mss, this.mss), this));
this.adjustSliderParts();
this.sliderKnob.setAppearanceStylingMode(true);
this.sliderKnob.setBorderStylingMode(true);
this.setAppearanceStylingMode(true);
this.setBorderStylingMode(true);
},
},
'accessing', {
getValue: function() { return this.value },
setValue: function(value) { return this.value = value },
getScaledValue: function() {
var v = (this.getValue() || 0); // FIXME remove 0
if (Object.isNumber(this.min) && Object.isNumber(this.max)) {
return (v-this.min)/(this.max-this.min);
} else {
return v / this.valueScale;
}
},
setScaledValue: function(value) {
if (Object.isNumber(this.min) && Object.isNumber(this.max)) {
return this.setValue((this.max-this.min)*value + this.min);
} else {
return this.setValue(value * this.valueScale);
}
},
getSliderExtent: function() { return this.sliderExtent },
setSliderExtent: function(value) {
this.sliderExtent = value
this.adjustSliderParts();
return value;
},
setExtent: function($super, value) {
$super(value);
this.adjustSliderParts();
return value;
},
},
'mouse events', {
onMouseDown: function(evt) {
// FIXME: a lot of this is handled in Morph>>onMouseDown. remove.
if (!evt.isLeftMouseButtonDown() || evt.isCommandKey()) return false;
var handPos = this.localize(evt.getPosition());
if (this.sliderKnob.bounds().containsPoint(handPos)) return false; // knob handles move
if (!this.innerBounds().containsPoint(handPos)) return false; // don't involve, eg, pins
var inc = this.getSliderExtent(),
newValue = this.getValue(),
delta = handPos.subPt(this.sliderKnob.bounds().center());
if (this.vertical() ? delta.y > 0 : delta.x > 0) newValue += inc;
else newValue -= inc;
if (isNaN(newValue)) newValue = 0;
this.setScaledValue(this.clipValue(newValue));
return true;
}
},
'slider logic', {
vertical: function() {
var bnds = this.shape.bounds();
return bnds.height > bnds.width;
},
clipValue: function(val) {
return Math.min(1.0,Math.max(0,0,val.roundTo(0.0001)));
}
},
'layouting', {
adjustSliderParts: function() {
if (!this.sliderKnob) return;
// This method adjusts the slider for changes in value as well as geometry
var val = this.getScaledValue(),
bnds = this.shape.bounds(),
ext = this.getSliderExtent();
if (this.vertical()) { // more vertical...
var elevPix = Math.max(ext*bnds.height, this.mss), // thickness of elevator in pixels
topLeft = pt(0, (bnds.height - elevPix)*val),
sliderExt = pt(bnds.width, elevPix);
} else { // more horizontal...
var elevPix = Math.max(ext*bnds.width, this.mss), // thickness of elevator in pixels
topLeft = pt((bnds.width - elevPix)*val, 0),
sliderExt = pt(elevPix, bnds.height);
}
this.sliderKnob.setBounds(bnds.topLeft().addPt(topLeft).extent(sliderExt));
this.adjustFill();
},
adjustFill: function() {this.setupFill();},
setupFill: function() {
if (this.vertical()) {
this.addStyleClassName('vertical');
} else {
this.removeStyleClassName('vertical');
}
}
})
// FIXME move somewhere else
lively.morphic.Box.subclass('lively.morphic.SliderKnob',
'settings', {
style: {borderColor: Color.black, borderWidth: 1, fill: Color.gray, enableDragging: true},
dragTriggerDistance: 0,
isSliderKnob: true
},
'initializing', {
initialize: function($super, initialBounds, slider) {
$super(initialBounds);
this.slider = slider;
},
},
'mouse events', {
onDragStart: function($super, evt) {
this.hitPoint = this.owner.localize(evt.getPosition());
return true;
},
onDrag: function($super, evt) {
// the hitpoint is the offset that make the slider move smooth
if (!this.hitPoint) return; // we were not clicked on...
// Compute the value from a new mouse point, and emit it
var delta = this.owner.localize(evt.getPosition()).subPt(this.hitPoint),
p = this.bounds().topLeft().addPt(delta),
bnds = this.slider.innerBounds(),
ext = this.slider.getSliderExtent();
this.hitPoint = this.owner.localize(evt.getPosition());
if (this.slider.vertical()) {
// thickness of elevator in pixels
var elevPix = Math.max(ext*bnds.height,this.slider.mss),
newValue = p.y / (bnds.height-elevPix);
} else {
// thickness of elevator in pixels
var elevPix = Math.max(ext*bnds.width,this.slider.mss),
newValue = p.x / (bnds.width-elevPix);
}
if (isNaN(newValue)) newValue = 0;
this.slider.setScaledValue(this.slider.clipValue(newValue));
},
onDragEnd: function($super, evt) { return $super(evt) },
onMouseDown: function(evt) {
return true;
},
});
Object.extend(Array.prototype, {
asListItemArray: function() {
return this.collect(function(ea) {
return {isListItem: true, string: ea.toString(), value: ea};
});
}
})
lively.morphic.Box.subclass('lively.morphic.Tree',
'documentation', {
example: function() {
var tree = new lively.morphic.Tree();
tree.openInHand();
tree.setItem({
name: "root",
children: [
{name: "item 1", children: [{name: "subitem"}]},
{name: "item 2"}]
});
}
},
'initializing', {
initialize: function($super, item, optParent, optDragAndDrop) {
this.item = item;
this.parent = optParent;
this.depth = this.parent ? this.parent.depth + 1 : 0;
$super(pt(0, 0).extent(pt(300,20)));
this.initializeLayout();
this.disableDragging();
if (!optDragAndDrop && !(this.parent && this.parent.dragAndDrop)) {
this.disableDropping();
this.disableGrabbing();
} else {
this.dragAndDrop = true;
}
if (item) this.setItem(item);
},
initializeLayout: function() {
this.setFill(Color.white);
this.setBorderWidth(0);
this.setBorderColor(Color.black);
if (!this.layout) this.layout = {};
this.layout.resizeWidth = true;
this.setLayouter(new lively.morphic.Layout.TreeLayout(this));
},
initializeNode: function() {
var bounds = pt(0,0).extent(pt(200,20));
var node = new lively.morphic.Box(bounds);
node.ignoreEvents();
if (!node.layout) node.layout = {};
node.layout.resizeWidth = true;
var layouter = new lively.morphic.Layout.HorizontalLayout(node);
layouter.setSpacing(5);
layouter.setBorderSize(0);
node.setLayouter(layouter);
if (!node.layout) node.layout = {};
node.layout.resizeWidth = true;
this.icon = node.addMorph(this.createIcon());
this.label = node.addMorph(this.createLabel());
this.node = this.addMorph(node);
}
},
"accessing", {
getRootTree: function() {
return this.parent? this.parent.getRootTree() : this;
},
setItem: function(item) {
this.layoutAfter(function() {
this.item = item;
lively.bindings.connect(item, "changed", this, "update");
this.submorphs.invoke("remove");
this.childNodes = null;
if (!item.name) {
if (item.children) this.expand();
} else {
this.initializeNode();
}
});
}
},
'updating', {
update: function() {
this.updateItem(this.item);
},
updateItem: function(item) {
if (this.item !== item) {
var oldItem = this.item;
if (oldItem) {
lively.bindings.disconnect(oldItem, "changed", this, "update");
}
this.item = item;
if (item == null) { this.remove(); return; }
lively.bindings.connect(item, "changed", this, "update");
} else {
if (item.onUpdate) item.onUpdate(this);
}
if (this.childNodes) {
if (item.onUpdateChildren) item.onUpdateChildren(this);
this.updateChildren();
}
this.updateNode();
},
updateNode: function() {
if (this.node) {
this.updateIcon();
this.updateLabel();
}
},
updateIcon: function() {
var str = this.item.children ? "►" : "";
if (this.childNodes) str = "▼";
if (this.icon.textString !== str) this.icon.textString = str;
},
updateLabel: function() {
var str = this.item.name, changed = false;
if (this.item.description) str += " " + this.item.description;
if (this.label.textString !== str) {
this.label.textString = this.item.name;
if (this.item.description) {
var gray = {color: Color.web.darkgray};
this.label.appendRichText(" " + this.item.description, gray);
}
changed = true;
}
if (this.item.style && this.item.style !== this.label.oldStyle) {
this.label.firstTextChunk().styleText(this.item.style);
this.label.oldStyle = this.item.style;
changed = true;
}
var isSelected = this.label.getFill() !== null;
if (isSelected && !this.item.isSelected)
this.label.setFill(null);
if (!isSelected && this.item.isSelected)
this.label.setFill(Color.rgb(218, 218, 218));
if (changed) this.label.fit();
},
updateChildren: function() {
if (!this.childNodes) return;
var oldChildren = this.childNodes.map(function(n) { return n.item; });
var toRemove = oldChildren.withoutAll(this.item.children);
for (var i = 0; i < this.childNodes.length; i++) {
var node = this.childNodes[i];
if (toRemove.include(node.item)) {
node.remove();
this.childNodes.removeAt(i--);
}
}
var pageSize = this.childrenPerPage ? this.childrenPerPage : 100;
var currentInterval = Math.ceil(this.childNodes.length / pageSize) * pageSize;
currentInterval = Math.max(currentInterval , 100);
var numChildren = this.item.children ? this.item.children.length : 0;
var childrenToShow = Math.min(numChildren, currentInterval);
for (var j = 0; j < childrenToShow; j++) {
var item = this.item.children[j];
if (this.childNodes.length > j && this.childNodes[j].item === item) {
this.childNodes[j].update();
} else {
var newNode = this.createNodeBefore(item, this.childNodes[j]);
this.childNodes.pushAt(newNode, j);
}
}
if (!this.item.children) delete this.childNodes;
}
},
'creating', {
createIcon: function() {
var bounds = pt(0, 0).extent(pt(10, 20));
var str = this.item.children ? "►" : "";
var icon = new lively.morphic.Text(bounds, str);
icon.setBorderWidth(0);
icon.setFill(null);
icon.disableDragging();
icon.disableGrabbing();
icon.setInputAllowed(false);
icon.setHandStyle('default');
icon.setAlign("right");
icon.addScript(function onMouseDown(evt) {
if (this.owner.owner.item.children && evt.isLeftMouseButtonDown()) {
this.owner.owner.toggle();
}
});
return icon;
},
createLabel: function() {
var bounds = pt(0, 0).extent(pt(100, 20));
var label = new lively.morphic.Text(bounds);
label.setBorderWidth(0);
label.setFill(null);
label.disableDragging();
label.disableGrabbing();
label.setInputAllowed(false);
label.setHandStyle('default');
label.setWhiteSpaceHandling('pre');
label.setFixedWidth(false);
label.setFixedHeight(true);
label.addScript(function onMouseDown(evt) {
if (evt.isLeftMouseButtonDown() && this.owner.owner.item.onSelect) {
this.owner.owner.getRootTree().select(this.owner.owner);
}
});
if (this.item.isSelected) {
label.setFill(Color.rgb(218, 218, 218));
}
label.textString = this.item.name;
if (this.item.style) {
label.emphasizeAll(this.item.style);
label.oldStyle = this.item.style;
}
if (this.item.description) {
var gray = {color: Color.web.darkgray};
label.appendRichText(' ' + this.item.description, gray);
}
return label;
},
createNodeBefore: function(item, optOtherNode) {
var node = new lively.morphic.Tree(item, this);
node.childrenPerPage = this.childrenPerPage;
this.addMorph(node, optOtherNode);
return node;
},
},
'tree', {
isChild: function() {
return this.parent && this.parent.node;
},
showChildren: function() {
var that = this;
this.childNodes = [];
if (!this.item.children) return;
this.showMoreChildren();
},
showMoreChildren: function() {
this.layoutAfter(function() {
var childrenToShow = this.item.children.slice(
this.childNodes.length,
this.childNodes.length + (this.childrenPerPage ? this.childrenPerPage : 100));
if (this.showMoreNode) this.showMoreNode.remove();
this.showMoreNode = null;
var start = this.childNodes.length === 0 ? this : this.childNodes.last();
childrenToShow.each(function(currentItem) {
var node = this.createNodeBefore(currentItem);
this.childNodes.push(node);
}, this);
if (this.childNodes.length < this.item.children.length) {
var more = {name: "", description: "[show more]",
onSelect: this.showMoreChildren.bind(this)};
this.showMoreNode = this.createNodeBefore(more);
}
});
},
expand: function() {
if (!this.item.children || this.childNodes) return;
this.layoutAfter(function () {
if (this.item.onExpand) this.item.onExpand(this);
if (this.icon) this.icon.setTextString("▼");
this.showChildren();
})
},
expandAll: function() {
this.withAllTreesDo(function(tree) {
tree.expand();
});
},
collapse: function() {
if (!this.item.children || !this.childNodes) return;
this.layoutAfter(function() {
if (this.item.onCollapse) this.item.onCollapse(this.item);
if (this.icon) this.icon.setTextString("►");
if (this.childNodes) this.childNodes.invoke("remove");
this.childNodes = null;
if (this.showMoreNode) this.showMoreNode.remove();
this.showMoreNode = null;
});
},
toggle: function() {
this.childNodes ? this.collapse() : this.expand();
},
select: function(tree) {
this.withAllTreesDo(function(t) {
if (t.item.isSelected) {
delete t.item.isSelected;
t.label.setFill(null);
}
});
if (tree) {
tree.label.setFill(Color.rgb(218, 218, 218));
tree.item.isSelected = true;
tree.item.onSelect(tree);
}
},
layoutAfter: function(callback) {
var layouter = this.getLayouter();
try {
layouter && layouter.defer();
callback.call(this);
} finally {
layouter && layouter.resume();
}
}
},
'editing', {
edit: function() { console.warn('editing tree node label not supported yet'); },
editDescription: function() {
this.label.textString = this.item.name + (this.item.description ? " " : "");
this.label.growOrShrinkToFit();
var bounds = pt(0,0).extent(pt(160, 20));
var edit = new lively.morphic.Text(bounds, this.item.description);
edit.isInputLine = true;
edit.setClipMode("hidden");
edit.setFixedHeight(true);
edit.setFixedWidth(true);
edit.setBorderWidth(0);
edit.onEnterPressed = edit.onEscPressed;
this.node.addMorph(edit);
edit.growOrShrinkToFit();
edit.onBlur = function() { this.finishEditingDescription(edit); }.bind(this);
(function() { edit.focus(); edit.selectAll(); }).delay(0);
},
finishEditingDescription: function(edit) {
if (this.item.onEdit) this.item.onEdit(edit.textString);
edit.remove();
this.updateLabel();
}
},
'enumerating', {
withAllTreesDo: function(iter, context, depth) {
// only iterates through expanded childNodes, not necessarily through
// all item children! See #withAllItemsDo
if (!depth) depth = 0;
var result = iter.call(context || Global, this, depth);
if (!this.childNodes) return [result];
return [result].concat(
this.childNodes.invoke("withAllTreesDo", iter, context, depth + 1));
},
withAllItemsDo: function(iter, context) {
function visitItem(item, depth) {
var result = iter.call(context || Global, item, depth);
if (!item.children) return [result];
return item.children.inject([result], function(all, ea) {
return all.concat(visitItem(ea, depth + 1)); });
}
return this.item && visitItem(this.item, 0);
}
});
}) // end of module
| fixed adjustForNewBounds in TitleBar
| core/lively/morphic/Widgets.js | fixed adjustForNewBounds in TitleBar | <ide><path>ore/lively/morphic/Widgets.js
<ide> }
<ide> },
<ide> adjustForNewBounds: function() {
<del> $super();
<ide> this.adjustLabelBounds();
<ide> },
<ide> |
|
Java | apache-2.0 | 00f96f696ddbc97dd612a099a1f57ce97969a7c1 | 0 | RWTH-i5-IDSG/jamocha,RWTH-i5-IDSG/jamocha | /*
* Copyright 2002-2014 The Jamocha Team
*
*
* 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.jamocha.org/
*
* 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.jamocha.languages.common;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.jamocha.function.fwa.ExchangeableLeaf;
import org.jamocha.function.fwa.PredicateWithArguments;
import org.jamocha.languages.common.ScopeStack.Scope;
import org.jamocha.visitor.Visitable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* @author Fabian Ohler <[email protected]>
*/
@RequiredArgsConstructor
public abstract class ConditionalElement<L extends ExchangeableLeaf<L>>
implements Visitable<ConditionalElementsVisitor<L>> {
@Getter
final List<ConditionalElement<L>> children;
private static abstract class PositiveOrNegativeExistentialConditionalElement<L extends ExchangeableLeaf<L>>
extends ConditionalElement<L> {
@Getter
final Scope scope;
public PositiveOrNegativeExistentialConditionalElement(final Scope scope,
final AndFunctionConditionalElement<L> child) {
this(scope, Lists.newArrayList(ImmutableList.of(child)));
}
private PositiveOrNegativeExistentialConditionalElement(final Scope scope,
final List<ConditionalElement<L>> children) {
super(children);
this.scope = scope;
}
abstract public PositiveOrNegativeExistentialConditionalElement<L> negate();
}
public static class ExistentialConditionalElement<L extends ExchangeableLeaf<L>>
extends PositiveOrNegativeExistentialConditionalElement<L> {
public ExistentialConditionalElement(final Scope scope, final AndFunctionConditionalElement<L> child) {
super(scope, child);
}
public ExistentialConditionalElement(final Scope scope, final List<ConditionalElement<L>> children) {
super(scope, children);
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "ExistentialCE " + Objects.toString(children);
}
@Override
public NegatedExistentialConditionalElement<L> negate() {
return new NegatedExistentialConditionalElement<>(scope, children);
}
}
public static class NegatedExistentialConditionalElement<L extends ExchangeableLeaf<L>>
extends PositiveOrNegativeExistentialConditionalElement<L> {
public NegatedExistentialConditionalElement(final Scope scope, final AndFunctionConditionalElement<L> child) {
super(scope, child);
}
private NegatedExistentialConditionalElement(final Scope scope, final List<ConditionalElement<L>> children) {
super(scope, children);
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "NegatedExistentialCE " + Objects.toString(children);
}
@Override
public ExistentialConditionalElement<L> negate() {
return new ExistentialConditionalElement<>(scope, children);
}
}
public static class TestConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
@Getter
final PredicateWithArguments<L> predicateWithArguments;
public TestConditionalElement(final PredicateWithArguments<L> predicateWithArguments) {
super(new ArrayList<>());
this.predicateWithArguments = predicateWithArguments;
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "TestCE (" + Objects.toString(predicateWithArguments) + ")";
}
}
public static class OrFunctionConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
public OrFunctionConditionalElement(final List<ConditionalElement<L>> children) {
super(children);
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "OrCE " + Objects.toString(children);
}
}
public static class AndFunctionConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
public AndFunctionConditionalElement(final List<ConditionalElement<L>> children) {
super(children);
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "AndCE " + Objects.toString(children);
}
}
public static class NotFunctionConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
public NotFunctionConditionalElement(final List<ConditionalElement<L>> children) {
super(children);
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "NotCE " + Objects.toString(children);
}
}
/**
* This class is inserted into a {@link RuleCondition} iff there are no variable bindings in the {@link
* RuleCondition}.
*
* @author Fabian Ohler <[email protected]>
*/
public static class InitialFactConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
@Getter
final SingleFactVariable initialFactVariable;
public InitialFactConditionalElement(final SingleFactVariable initialFactVariable) {
super(new ArrayList<>(0));
this.initialFactVariable = initialFactVariable;
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "InitialFactCE";
}
}
/**
* @author Fabian Ohler <[email protected]>
*/
public static class TemplatePatternConditionalElement<L extends ExchangeableLeaf<L>> extends
ConditionalElement<L> {
@Getter
final SingleFactVariable factVariable;
public TemplatePatternConditionalElement(final SingleFactVariable factVariable) {
super(Collections.emptyList());
this.factVariable = factVariable;
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "TPCE [" + Objects.toString(factVariable) + "]";
}
}
}
| src/org/jamocha/languages/common/ConditionalElement.java | /*
* Copyright 2002-2014 The Jamocha Team
*
*
* 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.jamocha.org/
*
* 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.jamocha.languages.common;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.jamocha.function.fwa.ExchangeableLeaf;
import org.jamocha.function.fwa.PredicateWithArguments;
import org.jamocha.languages.common.ScopeStack.Scope;
import org.jamocha.visitor.Visitable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
/**
* @author Fabian Ohler <[email protected]>
*/
@RequiredArgsConstructor
public abstract class ConditionalElement<L extends ExchangeableLeaf<L>> implements
Visitable<ConditionalElementsVisitor<L>> {
@Getter
final List<ConditionalElement<L>> children;
private static abstract class PositiveOrNegativeExistentialConditionalElement<L extends ExchangeableLeaf<L>>
extends ConditionalElement<L> {
@Getter
final Scope scope;
public PositiveOrNegativeExistentialConditionalElement(final Scope scope,
final AndFunctionConditionalElement<L> child) {
this(scope, Lists.newArrayList(ImmutableList.of(child)));
}
private PositiveOrNegativeExistentialConditionalElement(final Scope scope,
final List<ConditionalElement<L>> children) {
super(children);
this.scope = scope;
}
abstract public PositiveOrNegativeExistentialConditionalElement<L> negate();
}
public static class ExistentialConditionalElement<L extends ExchangeableLeaf<L>> extends
PositiveOrNegativeExistentialConditionalElement<L> {
public ExistentialConditionalElement(final Scope scope, final AndFunctionConditionalElement<L> child) {
super(scope, child);
}
public ExistentialConditionalElement(final Scope scope, final List<ConditionalElement<L>> children) {
super(scope, children);
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "ExistentialCE " + Objects.toString(children);
}
@Override
public NegatedExistentialConditionalElement<L> negate() {
return new NegatedExistentialConditionalElement<>(scope, children);
}
}
public static class NegatedExistentialConditionalElement<L extends ExchangeableLeaf<L>> extends
PositiveOrNegativeExistentialConditionalElement<L> {
public NegatedExistentialConditionalElement(final Scope scope, final AndFunctionConditionalElement<L> child) {
super(scope, child);
}
private NegatedExistentialConditionalElement(final Scope scope, final List<ConditionalElement<L>> children) {
super(scope, children);
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "NegatedExistentialCE " + Objects.toString(children);
}
@Override
public ExistentialConditionalElement<L> negate() {
return new ExistentialConditionalElement<>(scope, children);
}
}
public static class TestConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
@Getter
final PredicateWithArguments<L> predicateWithArguments;
public TestConditionalElement(final PredicateWithArguments<L> predicateWithArguments) {
super(new ArrayList<>());
this.predicateWithArguments = predicateWithArguments;
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "TestCE (" + Objects.toString(predicateWithArguments) + ")";
}
}
public static class OrFunctionConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
public OrFunctionConditionalElement(final List<ConditionalElement<L>> children) {
super(children);
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "OrCE " + Objects.toString(children);
}
}
public static class AndFunctionConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
public AndFunctionConditionalElement(final List<ConditionalElement<L>> children) {
super(children);
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "AndCE " + Objects.toString(children);
}
}
public static class NotFunctionConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
public NotFunctionConditionalElement(final List<ConditionalElement<L>> children) {
super(children);
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "NotCE " + Objects.toString(children);
}
}
/**
* This class is inserted into a {@link RuleCondition} iff there are no variable bindings in the
* {@link RuleCondition}.
*
* @author Fabian Ohler <[email protected]>
*/
public static class InitialFactConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
@Getter
final SingleFactVariable initialFactVariable;
public InitialFactConditionalElement(final SingleFactVariable initialFactVariable) {
super(new ArrayList<>(0));
this.initialFactVariable = initialFactVariable;
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "InitialFactCE";
}
}
/**
* @author Fabian Ohler <[email protected]>
*/
public static class TemplatePatternConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
@Getter
final SingleFactVariable factVariable;
public TemplatePatternConditionalElement(final SingleFactVariable factVariable) {
super(Collections.emptyList());
this.factVariable = factVariable;
}
@Override
public <V extends ConditionalElementsVisitor<L>> V accept(final V visitor) {
visitor.visit(this);
return visitor;
}
@Override
public String toString() {
return "TPCE [" + Objects.toString(factVariable) + "]";
}
}
}
| code cleanup
| src/org/jamocha/languages/common/ConditionalElement.java | code cleanup | <ide><path>rc/org/jamocha/languages/common/ConditionalElement.java
<ide> */
<ide> package org.jamocha.languages.common;
<ide>
<add>import com.google.common.collect.ImmutableList;
<add>import com.google.common.collect.Lists;
<add>import lombok.Getter;
<add>import lombok.RequiredArgsConstructor;
<add>import org.jamocha.function.fwa.ExchangeableLeaf;
<add>import org.jamocha.function.fwa.PredicateWithArguments;
<add>import org.jamocha.languages.common.ScopeStack.Scope;
<add>import org.jamocha.visitor.Visitable;
<add>
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Objects;
<ide>
<del>import lombok.Getter;
<del>import lombok.RequiredArgsConstructor;
<del>
<del>import org.jamocha.function.fwa.ExchangeableLeaf;
<del>import org.jamocha.function.fwa.PredicateWithArguments;
<del>import org.jamocha.languages.common.ScopeStack.Scope;
<del>import org.jamocha.visitor.Visitable;
<del>
<del>import com.google.common.collect.ImmutableList;
<del>import com.google.common.collect.Lists;
<del>
<ide> /**
<ide> * @author Fabian Ohler <[email protected]>
<ide> */
<ide> @RequiredArgsConstructor
<del>public abstract class ConditionalElement<L extends ExchangeableLeaf<L>> implements
<del> Visitable<ConditionalElementsVisitor<L>> {
<add>public abstract class ConditionalElement<L extends ExchangeableLeaf<L>>
<add> implements Visitable<ConditionalElementsVisitor<L>> {
<ide>
<ide> @Getter
<ide> final List<ConditionalElement<L>> children;
<ide> abstract public PositiveOrNegativeExistentialConditionalElement<L> negate();
<ide> }
<ide>
<del> public static class ExistentialConditionalElement<L extends ExchangeableLeaf<L>> extends
<del> PositiveOrNegativeExistentialConditionalElement<L> {
<add> public static class ExistentialConditionalElement<L extends ExchangeableLeaf<L>>
<add> extends PositiveOrNegativeExistentialConditionalElement<L> {
<ide> public ExistentialConditionalElement(final Scope scope, final AndFunctionConditionalElement<L> child) {
<ide> super(scope, child);
<ide> }
<ide> }
<ide> }
<ide>
<del> public static class NegatedExistentialConditionalElement<L extends ExchangeableLeaf<L>> extends
<del> PositiveOrNegativeExistentialConditionalElement<L> {
<add> public static class NegatedExistentialConditionalElement<L extends ExchangeableLeaf<L>>
<add> extends PositiveOrNegativeExistentialConditionalElement<L> {
<ide> public NegatedExistentialConditionalElement(final Scope scope, final AndFunctionConditionalElement<L> child) {
<ide> super(scope, child);
<ide> }
<ide> }
<ide>
<ide> /**
<del> * This class is inserted into a {@link RuleCondition} iff there are no variable bindings in the
<del> * {@link RuleCondition}.
<add> * This class is inserted into a {@link RuleCondition} iff there are no variable bindings in the {@link
<add> * RuleCondition}.
<ide> *
<ide> * @author Fabian Ohler <[email protected]>
<ide> */
<ide> /**
<ide> * @author Fabian Ohler <[email protected]>
<ide> */
<del> public static class TemplatePatternConditionalElement<L extends ExchangeableLeaf<L>> extends ConditionalElement<L> {
<add> public static class TemplatePatternConditionalElement<L extends ExchangeableLeaf<L>> extends
<add> ConditionalElement<L> {
<ide> @Getter
<ide> final SingleFactVariable factVariable;
<ide> |
|
JavaScript | mit | a1cc4cb43dd6a0daa265aa05dc958398264de568 | 0 | piroor/fxaddonlib-bookmark-multiple-tabs,piroor/fxaddonlib-autoscroll,piroor/fxaddonlib-boxobject,piroor/fxaddonlib-prefs,piroor/fxaddonlib-uninstallation-listener,piroor/fxaddonlib-confirm-tab,piroor/fxaddonlib-animation-manager,piroor/fxaddonlib-stringbundle,piroor/fxaddonlib-jstimer,piroor/fxaddonlib-operation-history,piroor/fxaddonlib-arrowscrollbox-scroll-helper,piroor/fxaddonlib-extensions,piroor/fxaddonlib-namespace,piroor/fxaddonlib-stop-rendering,piroor/fxaddonlib-persistent-attributes,piroor/fxaddonlib-confirm-popup | utils.include('operationHistory.js', 'Shift_JIS');
var sv;
var log;
var win;
function windowSetUp() {
yield Do(utils.setUpTestWindow());
win = utils.getTestWindow();
eventListenersSetUp(win, 'window');
};
function windowTearDown() {
eventListenersTearDown(win, 'window');
yield Do(utils.tearDownTestWindow());
win = null;
}
function eventListenersSetUp(aWindow, aName) {
aWindow.addEventListener('UIOperationHistoryPreUndo:'+aName, handleEvent, false);
aWindow.addEventListener('UIOperationHistoryUndo:'+aName, handleEvent, false);
aWindow.addEventListener('UIOperationHistoryRedo:'+aName, handleEvent, false);
aWindow.addEventListener('UIOperationHistoryPostRedo:'+aName, handleEvent, false);
aWindow.addEventListener('UIOperationHistoryUndoComplete:'+aName, handleEvent, false);
aWindow.addEventListener('UIOperationHistoryRedoComplete:'+aName, handleEvent, false);
}
function eventListenersTearDown(aWindow, aName) {
aWindow.removeEventListener('UIOperationHistoryPreUndo:'+aName, handleEvent, false);
aWindow.removeEventListener('UIOperationHistoryUndo:'+aName, handleEvent, false);
aWindow.removeEventListener('UIOperationHistoryRedo:'+aName, handleEvent, false);
aWindow.removeEventListener('UIOperationHistoryPostRedo:'+aName, handleEvent, false);
aWindow.removeEventListener('UIOperationHistoryUndoComplete:'+aName, handleEvent, false);
aWindow.removeEventListener('UIOperationHistoryRedoComplete:'+aName, handleEvent, false);
}
function handleEvent(aEvent) {
var prefix;
switch (aEvent.type.split(':')[0])
{
case 'UIOperationHistoryPreUndo':
prefix = 'event(pre-undo)';
break;
case 'UIOperationHistoryUndo':
prefix = 'event(undo)';
break;
case 'UIOperationHistoryRedo':
prefix = 'event(redo)';
break;
case 'UIOperationHistoryPostRedo':
prefix = 'event(post-redo)';
break;
case 'UIOperationHistoryUndoComplete':
log.push('event(undo-complete)');
return;
case 'UIOperationHistoryRedoComplete':
log.push('event(redo-complete)');
return;
}
log.push(prefix+' '+aEvent.entry.name+' (level '+aEvent.params.level+')');
}
function toSimpleList(aString) {
return String(aString)
.replace(/^\s+|\s+$/g, '')
.replace(/\n\t+/g, '\n');
}
function setUp()
{
sv = window['piro.sakura.ne.jp'].operationHistory;
sv._db = {
histories : {},
observerRegistered : true
};
log = [];
eventListenersSetUp(window, 'global');
}
function tearDown()
{
eventListenersTearDown(window, 'global');
}
test_setGetWindowId.setUp = windowSetUp;
test_setGetWindowId.tearDown = windowTearDown;
function test_setGetWindowId()
{
sv.setWindowId(win, 'foobar');
assert.equals('foobar', sv.getWindowId(win));
assert.equals('foobar', sv.getWindowId(win, 'default'));
yield Do(windowTearDown());
yield Do(windowSetUp());
var id = sv.getWindowId(win, 'foobar');
assert.isNotNull(id);
assert.notEquals('', id);
var newId = sv.getWindowId(win, 'foobar');
assert.isNotNull(newId);
assert.equals(id, newId);
sv.setWindowId(win, 'foobar');
assert.equals('foobar', sv.getWindowId(win));
}
test_getWindowById.setUp = windowSetUp;
test_getWindowById.tearDown = windowTearDown;
function test_getWindowById()
{
var id = sv.getWindowId(win);
var windowFromId = sv.getWindowById(id);
assert.equals(win, windowFromId);
windowFromId = sv.getWindowById('does not exist!');
assert.isNull(windowFromId);
}
test_setGetElementId.setUp = windowSetUp;
test_setGetElementId.tearDown = windowTearDown;
function test_setGetElementId()
{
var element = win.gBrowser;
sv.setElementId(element, 'foobar');
assert.equals('foobar', sv.getElementId(element));
assert.equals('foobar', sv.getElementId(element, 'default'));
yield Do(windowTearDown());
yield Do(windowSetUp());
element = win.gBrowser;
var id = sv.getElementId(element, 'foobar');
assert.isNotNull(id);
assert.notEquals('', id);
var newId = sv.getElementId(element, 'foobar');
assert.equals(id, newId);
sv.setElementId(element, 'foobar');
assert.equals('foobar', sv.getElementId(element));
// duplicated id is not allowed.
newId = sv.setElementId(element.parentNode, 'foobar');
assert.equals(newId, sv.getElementId(element.parentNode));
assert.notEquals('foobar', newId);
assert.notEquals('foobar', sv.getElementId(element.parentNode));
}
test_getElementById.setUp = windowSetUp;
test_getElementById.tearDown = windowTearDown;
function test_getElementById()
{
var element = win.gBrowser;
var id = sv.getElementId(element);
var elementFromId = sv.getElementById(id, win);
assert.equals(element, elementFromId);
// returns null for a wrong parent
elementFromId = sv.getElementById(id, content);
assert.isNull(elementFromId);
elementFromId = sv.getElementById('does not exist!', win);
assert.isNull(elementFromId);
}
test_getId.setUp = windowSetUp;
test_getId.tearDown = windowTearDown;
function test_getId()
{
var id = sv.getId(win);
var windowFromId = sv.getWindowById(id);
assert.equals(win, windowFromId);
var element = win.gBrowser;
id = sv.getId(element);
assert.isNotNull(id);
var elementFromId = sv.getElementById(id, win);
assert.equals(element, elementFromId);
assert.isNull(sv.getId(''));
assert.isNull(sv.getId(0));
assert.isNull(sv.getId(false));
assert.isNull(sv.getId(null));
assert.isNull(sv.getId(undefined));
assert.raises('foo is an unknown type item.', function() {
sv.getId('foo');
});
}
test_getTargetById.setUp = windowSetUp;
test_getTargetById.tearDown = windowTearDown;
function test_getTargetById()
{
var element = win.gBrowser;
var windowId = sv.getId(win);
var elementId = sv.getId(element);
assert.equals(win, sv.getTargetById(windowId));
assert.equals(element, sv.getTargetById(elementId, win));
}
test_getTargetsByIds.setUp = windowSetUp;
test_getTargetsByIds.tearDown = windowTearDown;
function test_getTargetsByIds()
{
var tabs = [
win.gBrowser.addTab(),
win.gBrowser.addTab(),
win.gBrowser.addTab()
];
var ids = tabs.map(function(aTab) {
return sv.getId(aTab);
});
assert.equals(tabs, sv.getTargetsByIds(ids[0], ids[1], ids[2], win.gBrowser.mTabContainer));
assert.equals(tabs, sv.getTargetsByIds(ids, win.gBrowser.mTabContainer));
assert.equals([null, null, null], sv.getTargetsByIds(ids[0], ids[1], ids[2], win));
assert.equals([null, null, null], sv.getTargetsByIds(ids, win));
}
test_addEntry.setUp = windowSetUp;
test_addEntry.tearDown = windowTearDown;
function test_addEntry()
{
var name = 'foobar';
// register global-anonymous
sv.addEntry({ label : 'anonymous 1' });
sv.addEntry({ label : 'anonymous 2' });
sv.addEntry({ label : 'anonymous 3' });
// register global-named
sv.addEntry(name, { label : 'named 1' });
sv.addEntry(name, { label : 'named 2' });
sv.addEntry(name, { label : 'named 3' });
// register window-anonymous
sv.addEntry({ label : 'window, anonymous 1' }, win);
sv.addEntry({ label : 'window, anonymous 2' }, win);
sv.addEntry({ label : 'window, anonymous 3' }, win);
// register window-named
sv.addEntry(name, { label : 'window, named 1' }, win);
sv.addEntry(name, { label : 'window, named 2' }, win);
sv.addEntry(name, { label : 'window, named 3' }, win);
function assertHistory(aLabels, aCurrentIndex, aHistory)
{
assert.equals(aLabels.length, aHistory.entries.length);
assert.equals(aLabels,
aHistory.entries.map(function(aEntry) {
return aEntry.label;
}));
assert.equals(aCurrentIndex, aHistory.index);
}
assertHistory(
['anonymous 1',
'anonymous 2',
'anonymous 3'],
2,
sv.getHistory()
);
assertHistory(
['named 1',
'named 2',
'named 3'],
2,
sv.getHistory(name)
);
assertHistory(
['window, anonymous 1',
'window, anonymous 2',
'window, anonymous 3'],
2,
sv.getHistory(win)
);
assertHistory(
['window, named 1',
'window, named 2',
'window, named 3'],
2,
sv.getHistory(name, win)
);
}
function assertHistoryCount(aIndex, aCount)
{
var history = sv.getHistory();
assert.equals(
aIndex+' / '+aCount,
history.index+' / '+history.entries.length,
utils.inspect(history.entries)
);
}
function assertUndoingState(aExpectedUndoing, aExpectedRedoing, aMessage)
{
if (aExpectedUndoing)
assert.isTrue(sv.isUndoing(), aMessage);
else
assert.isFalse(sv.isUndoing(), aMessage);
if (aExpectedRedoing)
assert.isTrue(sv.isRedoing(), aMessage);
else
assert.isFalse(sv.isRedoing(), aMessage);
if (aExpectedUndoing || aExpectedRedoing)
assert.isFalse(sv.isUndoable(), aMessage);
else
assert.isTrue(sv.isUndoable(), aMessage);
}
function test_undoRedo_simple()
{
assertUndoingState(false, false);
sv.addEntry({ name : 'entry 1',
label : 'entry 1',
onUndo : function(aParams) {
log.push('u1');
assertUndoingState(true, false);
},
onRedo : function(aParams) {
log.push('r1');
assertUndoingState(false, true);
} });
sv.addEntry({ name : 'entry 2',
label : 'entry 2',
onPreUndo : function(aParams) {
log.push('u2pre');
assertUndoingState(true, false);
},
onUndo : function(aParams) {
log.push('u2');
assertUndoingState(true, false);
},
onRedo : function(aParams) {
log.push('r2');
assertUndoingState(false, true);
},
onPostRedo : function(aParams) {
log.push('r2post');
assertUndoingState(false, true);
} });
sv.addEntry({ name : 'entry 3',
label : 'entry 3' });
assertHistoryCount(2, 3);
assert.isTrue(sv.undo().done); // entry 3
assert.isTrue(sv.undo().done); // u2pre, u2
assertUndoingState(false, false);
assertHistoryCount(0, 3);
assert.isTrue(sv.redo().done); // r2, r2post
assert.isTrue(sv.redo().done); // entry 3
assertUndoingState(false, false);
assert.equals(
toSimpleList(<![CDATA[
event(pre-undo) entry 3 (level 0)
event(undo) entry 3 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
event(redo) entry 3 (level 0)
event(post-redo) entry 3 (level 0)
event(redo-complete)
]]>),
log.join('\n')
);
}
function test_undoRedo_goToIndex()
{
sv.addEntry({ name : 'entry 1',
label : 'entry 1',
onPreUndo : function(aParams) { log.push('u1pre'); },
onUndo : function(aParams) { log.push('u1'); sv.undo(); /* <= this should be ignored */ },
onRedo : function(aParams) { log.push('r1'); },
onPostRedo : function(aParams) { log.push('r1post'); } });
sv.addEntry({ name : 'entry 2',
label : 'entry 2',
onPreUndo : function(aParams) { log.push('u2pre'); },
onUndo : function(aParams) { log.push('u2'); },
onRedo : function(aParams) { log.push('r2'); sv.redo(); /* <= this should be ignored */ },
onPostRedo : function(aParams) { log.push('r2post'); sv.redo(); } });
sv.addEntry({ name : 'entry 3',
label : 'entry 3',
onPreUndo : function(aParams) { log.push('u3pre'); sv.undo(); /* <= this should be ignored */ },
onUndo : function(aParams) { log.push('u3'); sv.undo(); /* <= this should be ignored */ },
onRedo : function(aParams) { log.push('r3'); sv.redo(); /* <= this should be ignored */ },
onPostRedo : function(aParams) { log.push('r3post'); sv.redo(); /* <= this should be ignored */ } });
assertHistoryCount(2, 3);
sv.undo(); // u3pre, u3
assertHistoryCount(1, 3);
sv.redo(); // r3, r3post
assertHistoryCount(2, 3);
sv.undo(); // u3pre, u3
assertHistoryCount(1, 3);
sv.undo(); // u2pre, u2
assertHistoryCount(0, 3);
sv.undo(); // u1pre, u1
assertHistoryCount(0, 3);
sv.redo(); // r1, r1post
assertHistoryCount(0, 3);
sv.redo(); // r2, r2post
assertHistoryCount(1, 3);
sv.redo(); // r3, r3post
assertHistoryCount(2, 3);
sv.redo(); // --
assertHistoryCount(2, 3);
sv.redo(); // --
assertHistoryCount(2, 3);
sv.undo(); // u3pre, u3
assertHistoryCount(1, 3);
sv.undo(); // u2pre, u2
assertHistoryCount(0, 3);
sv.undo(); // u1pre, u1
assertHistoryCount(0, 3);
sv.undo(); // --
assertHistoryCount(0, 3);
sv.undo(); // --
assertHistoryCount(0, 3);
sv.undo(); // --
assertHistoryCount(0, 3);
sv.redo(); // r1, r1post
assertHistoryCount(0, 3);
sv.redo(); // r2, r2post
assertHistoryCount(1, 3);
log.push('----insert');
sv.addEntry({ name : 'entry 4',
label : 'entry 4',
onPreUndo : function(aParams) { log.push('u4pre'); sv.addEntry({ label: 'invalid/undo' }); },
onUndo : function(aParams) { log.push('u4'); sv.addEntry({ label: 'invalid/undo' }); },
onRedo : function(aParams) { log.push('r4'); sv.addEntry({ label: 'invalid/redo' }); },
onPostRedo : function(aParams) { log.push('r4post'); sv.addEntry({ label: 'invalid/redo' }); } });
assertHistoryCount(2, 3);
sv.undo(); // u4pre, u4
assertHistoryCount(1, 3);
sv.redo(); // r4, r4post
assertHistoryCount(2, 3);
sv.undo(); // u4pre, u4
assertHistoryCount(1, 3);
sv.undo(); // u2pre, u2
assertHistoryCount(0, 3);
sv.undo(); // u1pre, u1
assertHistoryCount(0, 3);
sv.redo(); // r1, r1post
assertHistoryCount(0, 3);
sv.redo(); // r2, r2post
assertHistoryCount(1, 3);
sv.redo(); // r4, r4post
assertHistoryCount(2, 3);
log.push('----goToIndex back');
sv.goToIndex(0);
log.push('----goToIndex same');
sv.goToIndex(0);
log.push('----goToIndex forward');
sv.goToIndex(2);
log.push('----goToIndex back');
sv.goToIndex(-5);
log.push('----goToIndex forward');
sv.goToIndex(5);
assert.equals(
toSimpleList(<![CDATA[
u3pre
event(pre-undo) entry 3 (level 0)
u3
event(undo) entry 3 (level 0)
event(undo-complete)
r3
event(redo) entry 3 (level 0)
r3post
event(post-redo) entry 3 (level 0)
event(redo-complete)
u3pre
event(pre-undo) entry 3 (level 0)
u3
event(undo) entry 3 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
u1pre
event(pre-undo) entry 1 (level 0)
u1
event(undo) entry 1 (level 0)
event(undo-complete)
r1
event(redo) entry 1 (level 0)
r1post
event(post-redo) entry 1 (level 0)
event(redo-complete)
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
r3
event(redo) entry 3 (level 0)
r3post
event(post-redo) entry 3 (level 0)
event(redo-complete)
u3pre
event(pre-undo) entry 3 (level 0)
u3
event(undo) entry 3 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
u1pre
event(pre-undo) entry 1 (level 0)
u1
event(undo) entry 1 (level 0)
event(undo-complete)
r1
event(redo) entry 1 (level 0)
r1post
event(post-redo) entry 1 (level 0)
event(redo-complete)
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
----insert
u4pre
event(pre-undo) entry 4 (level 0)
u4
event(undo) entry 4 (level 0)
event(undo-complete)
r4
event(redo) entry 4 (level 0)
r4post
event(post-redo) entry 4 (level 0)
event(redo-complete)
u4pre
event(pre-undo) entry 4 (level 0)
u4
event(undo) entry 4 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
u1pre
event(pre-undo) entry 1 (level 0)
u1
event(undo) entry 1 (level 0)
event(undo-complete)
r1
event(redo) entry 1 (level 0)
r1post
event(post-redo) entry 1 (level 0)
event(redo-complete)
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
r4
event(redo) entry 4 (level 0)
r4post
event(post-redo) entry 4 (level 0)
event(redo-complete)
----goToIndex back
u4pre
event(pre-undo) entry 4 (level 0)
u4
event(undo) entry 4 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
----goToIndex same
----goToIndex forward
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
r4
event(redo) entry 4 (level 0)
r4post
event(post-redo) entry 4 (level 0)
event(redo-complete)
----goToIndex back
u4pre
event(pre-undo) entry 4 (level 0)
u4
event(undo) entry 4 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
u1pre
event(pre-undo) entry 1 (level 0)
u1
event(undo) entry 1 (level 0)
event(undo-complete)
----goToIndex forward
r1
event(redo) entry 1 (level 0)
r1post
event(post-redo) entry 1 (level 0)
event(redo-complete)
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
r4
event(redo) entry 4 (level 0)
r4post
event(post-redo) entry 4 (level 0)
event(redo-complete)
]]>),
log.join('\n')
);
}
function handlEvent_skip(aEvent) {
if (aEvent.entry.name == 'skip both')
aEvent.skip();
}
test_undoRedo_skip.setUp = function() {
window.addEventListener('UIOperationHistoryUndo:global', handlEvent_skip, false);
window.addEventListener('UIOperationHistoryRedo:global', handlEvent_skip, false);
}
test_undoRedo_skip.tearDown = function() {
window.removeEventListener('UIOperationHistoryUndo:global', handlEvent_skip, false);
window.removeEventListener('UIOperationHistoryRedo:global', handlEvent_skip, false);
}
function test_undoRedo_skip()
{
sv.addEntry({ name : 'skip redo',
label : 'skip redo',
onUndo : function(aParams) { log.push('u redo'); },
onRedo : function(aParams) { log.push('r redo'); aParams.skip(); } });
sv.addEntry({ name : 'skip undo',
label : 'skip undo',
onUndo : function(aParams) { log.push('u undo'); aParams.skip(); },
onRedo : function(aParams) { log.push('r undo'); } });
sv.addEntry({ name : 'skip both',
label : 'skip both',
onUndo : function(aParams) { log.push('u both'); },
onRedo : function(aParams) { log.push('r both'); } });
sv.addEntry({ name : 'normal',
label : 'normal',
onUndo : function(aParams) { log.push('u normal'); },
onRedo : function(aParams) { log.push('r normal'); } });
assertHistoryCount(3, 4);
sv.undo(); // u normal
log.push('----');
assertHistoryCount(2, 4);
sv.undo(); // u both, u undo, u redo
log.push('----');
assertHistoryCount(0, 4);
sv.redo(); // r redo, r undo
log.push('----');
assertHistoryCount(1, 4);
sv.redo(); // r both, r normal
assertHistoryCount(3, 4);
assert.equals(
toSimpleList(<![CDATA[
event(pre-undo) normal (level 0)
u normal
event(undo) normal (level 0)
event(undo-complete)
----
event(pre-undo) skip both (level 0)
u both
event(undo) skip both (level 0)
event(pre-undo) skip undo (level 0)
u undo
event(undo) skip undo (level 0)
event(pre-undo) skip redo (level 0)
u redo
event(undo) skip redo (level 0)
event(undo-complete)
----
r redo
event(redo) skip redo (level 0)
event(post-redo) skip redo (level 0)
r undo
event(redo) skip undo (level 0)
event(post-redo) skip undo (level 0)
event(redo-complete)
----
r both
event(redo) skip both (level 0)
event(post-redo) skip both (level 0)
r normal
event(redo) normal (level 0)
event(post-redo) normal (level 0)
event(redo-complete)
]]>),
log.join('\n')
);
}
function test_undoRedo_wait()
{
sv.addEntry({ name : 'normal',
label : 'normal' });
sv.addEntry({
name : 'delayed',
label : 'delayed',
onPreUndo : function(aParams) {
aParams.wait();
window.setTimeout(function() {
aParams.continue();
}, 300);
},
onRedo : function(aParams) {
aParams.wait();
window.setTimeout(function() {
aParams.continue();
}, 300);
}
});
assertHistoryCount(1, 2);
var info;
assertUndoingState(false, false);
info = sv.undo();
assertHistoryCount(0, 2);
assert.isFalse(info.done);
assertUndoingState(true, false);
log.push('--waiting');
yield 600;
assert.isTrue(info.done);
assertUndoingState(false, false);
log.push('----');
info = sv.redo();
assertHistoryCount(1, 2);
assert.isFalse(info.done);
assertUndoingState(false, true);
log.push('--waiting');
yield 600;
assert.isTrue(info.done);
assertUndoingState(false, false);
assert.equals(
toSimpleList(<![CDATA[
event(pre-undo) delayed (level 0)
--waiting
event(undo) delayed (level 0)
event(undo-complete)
----
event(redo) delayed (level 0)
--waiting
event(post-redo) delayed (level 0)
event(redo-complete)
]]>),
log.join('\n')
);
}
function test_doOperation()
{
var info = sv.doOperation(
function(aParams) {
log.push('parent operation (level '+aParams.level+')');
sv.doOperation(
function(aParams) {
log.push('child operation (level '+aParams.level+')');
sv.doOperation(
function(aParams) {
log.push('deep operation (level '+aParams.level+')');
},
{ name : 'deep',
label : 'deep' }
);
// If the operation returns false,
// it should not be registered to the history.
sv.doOperation(
function(aParams) {
log.push('canceled operation (level '+aParams.level+')');
return false;
},
{ name : 'canceled',
label : 'canceled' }
);
},
{ name : 'child',
label : 'child',
onUndo : function(aParams) {
log.push('--canceled');
return false;
},
onPostRedo : function(aParams) {
log.push('--canceled');
return false;
} }
);
},
{ name : 'parent',
label : 'parent' }
);
assert.isTrue(info.done);
var history = sv.getHistory();
assert.equals(1, history.entries.length, utils.inspect(history.entries));
assert.equals('parent', history.entries[0].label, utils.inspect(history.entries[0]));
log.push('----');
sv.undo();
log.push('----');
sv.redo();
assert.equals(
toSimpleList(<![CDATA[
parent operation (level 0)
child operation (level 1)
deep operation (level 2)
canceled operation (level 2)
----
event(pre-undo) parent (level 0)
event(pre-undo) child (level 1)
event(pre-undo) deep (level 2)
event(undo) deep (level 2)
--canceled
event(undo-complete)
----
event(redo) parent (level 0)
event(redo) child (level 1)
event(redo) deep (level 2)
event(post-redo) deep (level 2)
--canceled
event(redo-complete)
]]>),
log.join('\n')
);
}
function handlEvent_cancel(aEvent) {
if (aEvent.entry.name == 'child') {
aEvent.preventDefault();
log.push('--canceled');
}
}
test_doOperation_canceledByEventListener.setUp = function() {
window.addEventListener('UIOperationHistoryUndo:global', handlEvent_cancel, false);
window.addEventListener('UIOperationHistoryPostRedo:global', handlEvent_cancel, false);
}
test_doOperation_canceledByEventListener.tearDown = function() {
window.removeEventListener('UIOperationHistoryUndo:global', handlEvent_cancel, false);
window.removeEventListener('UIOperationHistoryPostRedo:global', handlEvent_cancel, false);
}
function test_doOperation_canceledByEventListener()
{
var info = sv.doOperation(
function(aParams) {
log.push('parent operation (level '+aParams.level+')');
sv.doOperation(
function(aParams) {
log.push('child operation (level '+aParams.level+')');
sv.doOperation(
function(aParams) {
log.push('deep operation (level '+aParams.level+')');
},
{ name : 'deep',
label : 'deep' }
);
},
{ name : 'child',
label : 'child' }
);
},
{ name : 'parent',
label : 'parent' }
);
assert.isTrue(info.done);
var history = sv.getHistory();
assert.equals(1, history.entries.length, utils.inspect(history.entries));
assert.equals('parent', history.entries[0].label, utils.inspect(history.entries[0]));
log.push('----');
sv.undo();
log.push('----');
sv.redo();
assert.equals(
toSimpleList(<![CDATA[
parent operation (level 0)
child operation (level 1)
deep operation (level 2)
----
event(pre-undo) parent (level 0)
event(pre-undo) child (level 1)
event(pre-undo) deep (level 2)
event(undo) deep (level 2)
event(undo) child (level 1)
--canceled
event(undo-complete)
----
event(redo) parent (level 0)
event(redo) child (level 1)
event(redo) deep (level 2)
event(post-redo) deep (level 2)
event(post-redo) child (level 1)
--canceled
event(redo-complete)
]]>),
log.join('\n')
);
}
function test_doOperation_wait()
{
var info;
info = sv.doOperation(
function(aParams) {
log.push('op delayed parent (level '+aParams.level+')');
aParams.wait();
var info = sv.doOperation(
function(aParams) {
log.push('op normal child (level '+aParams.level+')');
},
{ name : 'normal child',
label : 'normal child' }
);
window.setTimeout(function() {
aParams.continue();
}, 300);
assert.isTrue(info.done);
},
{ name : 'delayed parent',
label : 'delayed parent' }
);
assert.isFalse(info.done);
yield 600;
assert.isTrue(info.done);
info = sv.doOperation(
function(aParams) {
log.push('op normal parent (level '+aParams.level+')');
var info = sv.doOperation(
function(aParams) {
log.push('op delayed child (level '+aParams.level+')');
aParams.wait();
window.setTimeout(function() {
aParams.continue();
}, 300);
},
{ name : 'delayed child',
label : 'delayed child' }
);
assert.isFalse(info.done);
},
{ name : 'normal parent',
label : 'normal parent' }
);
assert.isTrue(info.done);
log.push('----');
sv.undo();
log.push('----');
sv.undo();
log.push('----');
sv.redo();
log.push('----');
sv.redo();
assert.equals(
toSimpleList(<![CDATA[
op delayed parent (level 0)
op normal child (level 1)
op normal parent (level 0)
op delayed child (level 1)
----
event(pre-undo) normal parent (level 0)
event(pre-undo) delayed child (level 1)
event(undo) delayed child (level 1)
event(undo) normal parent (level 0)
event(undo-complete)
----
event(pre-undo) delayed parent (level 0)
event(pre-undo) normal child (level 1)
event(undo) normal child (level 1)
event(undo) delayed parent (level 0)
event(undo-complete)
----
event(redo) delayed parent (level 0)
event(redo) normal child (level 1)
event(post-redo) normal child (level 1)
event(post-redo) delayed parent (level 0)
event(redo-complete)
----
event(redo) normal parent (level 0)
event(redo) delayed child (level 1)
event(post-redo) delayed child (level 1)
event(post-redo) normal parent (level 0)
event(redo-complete)
]]>),
log.join('\n')
);
}
test_fakeUndoRedo.setUp = windowSetUp;
test_fakeUndoRedo.tearDown = windowTearDown;
function test_fakeUndoRedo()
{
var parent = [];
var child = [];
sv.doOperation(
function(aParams) {
sv.doOperation(
function(aParams) {
},
win,
(child[0] = {
name : 'child0',
label : 'child0'
})
);
},
win,
(parent[0] = {
name : 'parent0',
label : 'parent0'
})
);
sv.doOperation(
function(aParams) {
sv.doOperation(
function(aParams) {
},
win,
(child[1] = {
name : 'child1',
label : 'child1'
})
);
},
win,
(parent[1] = {
name : 'parent1',
label : 'parent1'
})
);
sv.doOperation(
function(aParams) {
sv.doOperation(
function(aParams) {
},
win,
(child[2] = {
name : 'child2',
label : 'child2'
})
);
},
win,
(parent[2] = {
name : 'parent2',
label : 'parent2'
})
);
var history = sv.getHistory(win);
assert.equals(2, history.index);
function assertFakeUndoSuccess(aCurrent, aEntry, aExpected)
{
log = [];
history.index = aCurrent;
sv.fakeUndo(aEntry, win);
assert.equals(aExpected, history.index);
assert.equals(['event(undo-complete)'], log);
}
function assertFakeUndoFail(aCurrent, aEntry)
{
log = [];
history.index = aCurrent;
sv.fakeUndo(aEntry, win);
var current = Math.min(aCurrent, history.entries.length-1);
assert.equals(current, history.index);
assert.equals([], log);
}
assertFakeUndoFail(2, parent[0]);
assertFakeUndoSuccess(2, parent[1], 0);
assertFakeUndoSuccess(2, parent[2], 1);
assertFakeUndoFail(3, parent[0]);
assertFakeUndoFail(3, parent[1]);
assertFakeUndoSuccess(3, parent[2], 1);
assertFakeUndoFail(2, child[0]);
assertFakeUndoSuccess(2, child[1], 0);
assertFakeUndoSuccess(2, child[2], 1);
assertFakeUndoFail(3, child[0]);
assertFakeUndoFail(3, child[1]);
assertFakeUndoSuccess(3, child[2], 1);
function assertFakeRedoSuccess(aCurrent, aEntry, aExpected)
{
log = [];
history.index = aCurrent;
sv.fakeRedo(aEntry, win);
assert.equals(aExpected, history.index);
assert.equals(['event(redo-complete)'], log);
}
function assertFakeRedoFail(aCurrent, aEntry)
{
log = [];
history.index = aCurrent;
sv.fakeRedo(aEntry, win);
var current = Math.max(aCurrent, 0);
assert.equals(current, history.index);
assert.equals([], log);
}
assertFakeRedoSuccess(-1, parent[0], 1);
assertFakeRedoFail(-1, parent[1]);
assertFakeRedoFail(-1, parent[2]);
assertFakeRedoSuccess(0, parent[0], 1);
assertFakeRedoSuccess(0, parent[1], 2);
assertFakeRedoFail(0, parent[2]);
assertFakeRedoSuccess(-1, child[0], 1);
assertFakeRedoFail(-1, child[1]);
assertFakeRedoFail(-1, child[2]);
assertFakeRedoSuccess(0, child[0], 1);
assertFakeRedoSuccess(0, child[1], 2);
assertFakeRedoFail(0, child[2]);
}
function test_exceptions()
{
assert.raises('EXCEPTION FROM UNDOABLE OPERATION', function() {
sv.doOperation(
function(aParams) {
log.push('op success (level '+aParams.level+')');
sv.doOperation(
function(aParams) {
log.push('op fail (level '+aParams.level+')');
throw 'EXCEPTION FROM UNDOABLE OPERATION';
},
{ name : 'cannot redo',
label : 'cannot redo',
onUndo : function(aParams) {
log.push('u cannot redo');
},
onRedo : function(aParams) {
throw 'EXCEPTION FROM REDO PROCESS';
log.push('r cannot redo');
} }
);
},
{ name : 'cannot undo',
label : 'cannot undo',
onUndo : function(aParams) {
throw 'EXCEPTION FROM UNDO PROCESS';
log.push('u cannot undo');
},
onRedo : function(aParams) {
log.push('r cannot undo');
} }
);
});
log.push('----');
assert.raises('EXCEPTION FROM UNDO PROCESS', function() {
sv.undo();
});
assert.raises('EXCEPTION FROM REDO PROCESS', function() {
sv.redo();
});
assert.equals(
toSimpleList(<![CDATA[
op success (level 0)
op fail (level 1)
----
event(pre-undo) cannot undo (level 0)
event(pre-undo) cannot redo (level 1)
u cannot redo
event(undo) cannot redo (level 1)
r cannot undo
event(redo) cannot undo (level 0)
]]>),
log.join('\n')
);
}
/* tests for internal classes */
function test_UIHistory_init()
{
var history = new sv.UIHistory('test', null, null);
assert.equals([], history.entries);
assert.equals([], history.metaData);
assert.equals(-1, history.index);
assert.isFalse(history.inOperation);
}
var testMaxPrefKeyGlobal = 'extensions.UIOperationsHistoryManager@piro.sakura.ne.jp.test.max.global';
var testMaxPrefKeyWindow = 'extensions.UIOperationsHistoryManager@piro.sakura.ne.jp.test.max.window';
test_UIHistory_max_global.setUp = test_UIHistory_max_window.setUp = function() {
utils.clearPref(testMaxPrefKeyGlobal);
utils.clearPref(testMaxPrefKeyWindow);
assert.isNull(utils.getPref(testMaxPrefKeyGlobal));
assert.isNull(utils.getPref(testMaxPrefKeyWindow));
};
test_UIHistory_max_global.tearDown = test_UIHistory_max_window.tearDown = function() {
utils.clearPref(testMaxPrefKeyGlobal);
utils.clearPref(testMaxPrefKeyWindow);
};
function test_UIHistory_max_global()
{
var maxDefault = sv.UIHistory.prototype.MAX_ENTRIES;
var history;
history = new sv.UIHistory('test', null, null);
assert.equals(maxDefault, history.max);
assert.equals(testMaxPrefKeyGlobal, history.maxPref);
history.max = 10;
assert.equals(10, history.max);
assert.equals(10, utils.getPref(testMaxPrefKeyGlobal));
assert.isNull(utils.getPref(testMaxPrefKeyWindow));
history = new sv.UIHistory('test', null, null);
assert.equals(10, history.max);
history = new sv.UIHistory('test', window, 'test');
assert.equals(maxDefault, history.max);
}
function test_UIHistory_max_window()
{
var maxDefault = sv.UIHistory.prototype.MAX_ENTRIES;
var history
history = new sv.UIHistory('test', window, 'test');
assert.equals(maxDefault, history.max);
assert.equals(testMaxPrefKeyWindow, history.maxPref);
history.max = 10;
assert.equals(10, history.max);
assert.isNull(utils.getPref(testMaxPrefKeyGlobal));
assert.equals(10, utils.getPref(testMaxPrefKeyWindow));
history = new sv.UIHistory('test', null, null);
assert.equals(maxDefault, history.max);
history = new sv.UIHistory('test', window, 'test');
assert.equals(10, history.max);
}
function test_UIHistory_addEntry()
{
var history = new sv.UIHistory('test', null, null);
assert.equals([], history.entries);
assert.equals([], history.metaData);
assert.equals(-1, history.index);
assert.isFalse(history.inOperation);
history.addEntry(0);
history.addEntry(1);
history.addEntry(2);
assert.equals([0, 1, 2], history.entries);
assert.equals(3, history.metaData.length);
assert.equals([], history.metaData[0].children);
assert.equals([], history.metaData[1].children);
assert.equals([], history.metaData[2].children);
assert.equals(3, history.index);
history.inOperation = true;
history.addEntry(3);
history.addEntry(4);
history.addEntry(5);
assert.equals([0, 1, 2], history.entries);
assert.equals(3, history.metaData.length);
assert.equals([], history.metaData[0].children);
assert.equals([], history.metaData[1].children);
assert.equals([3, 4, 5], history.metaData[2].children);
assert.equals(3, history.index);
history.inOperation = false;
history.addEntry(6);
assert.equals([0, 1, 2, 6], history.entries);
assert.equals(4, history.metaData.length);
assert.equals(4, history.index);
}
function test_UIHistory_canUndoRedo()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry(0);
history.addEntry(1);
history.addEntry(2);
assert.isTrue(history.canUndo);
assert.isFalse(history.canRedo);
history.index = 4;
assert.isTrue(history.canUndo);
assert.isFalse(history.canRedo);
history.index = 10;
assert.isTrue(history.canUndo);
assert.isFalse(history.canRedo);
history.index = 0;
assert.isTrue(history.canUndo);
assert.isTrue(history.canRedo);
history.index = -1;
assert.isFalse(history.canUndo);
assert.isTrue(history.canRedo);
history.index = -10;
assert.isFalse(history.canUndo);
assert.isTrue(history.canRedo);
history.index = 1;
assert.isTrue(history.canUndo);
assert.isTrue(history.canRedo);
}
function test_UIHistory_currentLastEntry()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry('0');
history.addEntry('1');
history.addEntry('2');
assert.isNull(history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = 2;
assert.equals('2', history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = 4;
assert.isNull(history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = 10;
assert.isNull(history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = 0;
assert.equals('0', history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = -1;
assert.isNull(history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = -10;
assert.isNull(history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = 1;
assert.equals('1', history.currentEntry);
assert.equals('2', history.lastEntry);
}
function test_UIHistory_currentLastMetaData()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry('0');
history.addEntry('1');
history.addEntry('2');
var metaData = history.metaData;
assert.isNull(history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = 2;
assert.strictlyEquals(metaData[2], history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = 4;
assert.isNull(history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = 10;
assert.isNull(history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = 0;
assert.strictlyEquals(metaData[0], history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = -1;
assert.isNull(history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = -10;
assert.isNull(history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = 1;
assert.strictlyEquals(metaData[1], history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
}
function test_UIHistory_currentLastEntries()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry('0');
history.inOperation = true;
history.addEntry('0.1');
history.addEntry('0.2');
history.inOperation = false;
history.addEntry('1');
history.inOperation = true;
history.addEntry('1.1');
history.addEntry('1.2');
history.inOperation = false;
history.addEntry('2');
history.inOperation = true;
history.addEntry('2.1');
history.addEntry('2.2');
history.inOperation = false;
assert.equals([], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = 2;
assert.equals(['2', '2.1', '2.2'], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = 4;
assert.equals([], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = 10;
assert.equals([], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = 0;
assert.equals(['0', '0.1', '0.2'], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = -1;
assert.equals([], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = -10;
assert.equals([], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = 1;
assert.equals(['1', '1.1', '1.2'], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
}
function test_UIHistory_namedEntry()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry({ name : '0' });
history.inOperation = true;
history.addEntry({ name : '1' });
history.addEntry({ name : '2' });
history.addEntry({ name : '3' });
history.inOperation = false;
assert.equals('0,1,2,3', history.metaData[history.safeIndex].names.join(','));
}
function test_UIHistoryProxy_index()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry('0');
history.addEntry('1');
history.addEntry('2');
var proxy = new sv.UIHistoryProxy(history);
history.index = 0;
assert.equals(0, proxy.index);
history.index = -1;
assert.equals(0, proxy.index);
history.index = -10;
assert.equals(0, proxy.index);
history.index = 2;
assert.equals(2, proxy.index);
history.index = 3;
assert.equals(2, proxy.index);
history.index = 10;
assert.equals(2, proxy.index);
}
function test_UIHistoryMetaData_children()
{
var metaData = new sv.UIHistoryMetaData();
assert.equals([], metaData.children);
}
| operationHistory.test.js | utils.include('operationHistory.js', 'Shift_JIS');
var sv;
var log;
var win;
function windowSetUp() {
yield Do(utils.setUpTestWindow());
win = utils.getTestWindow();
eventListenersSetUp(win, 'window');
};
function windowTearDown() {
eventListenersTearDown(win, 'window');
yield Do(utils.tearDownTestWindow());
win = null;
}
function eventListenersSetUp(aWindow, aName) {
aWindow.addEventListener('UIOperationHistoryPreUndo:'+aName, handleEvent, false);
aWindow.addEventListener('UIOperationHistoryUndo:'+aName, handleEvent, false);
aWindow.addEventListener('UIOperationHistoryRedo:'+aName, handleEvent, false);
aWindow.addEventListener('UIOperationHistoryPostRedo:'+aName, handleEvent, false);
aWindow.addEventListener('UIOperationHistoryUndoComplete:'+aName, handleEvent, false);
aWindow.addEventListener('UIOperationHistoryRedoComplete:'+aName, handleEvent, false);
}
function eventListenersTearDown(aWindow, aName) {
aWindow.removeEventListener('UIOperationHistoryPreUndo:'+aName, handleEvent, false);
aWindow.removeEventListener('UIOperationHistoryUndo:'+aName, handleEvent, false);
aWindow.removeEventListener('UIOperationHistoryRedo:'+aName, handleEvent, false);
aWindow.removeEventListener('UIOperationHistoryPostRedo:'+aName, handleEvent, false);
aWindow.removeEventListener('UIOperationHistoryUndoComplete:'+aName, handleEvent, false);
aWindow.removeEventListener('UIOperationHistoryRedoComplete:'+aName, handleEvent, false);
}
function handleEvent(aEvent) {
var prefix;
switch (aEvent.type.split(':')[0])
{
case 'UIOperationHistoryPreUndo':
prefix = 'event(pre-undo)';
break;
case 'UIOperationHistoryUndo':
prefix = 'event(undo)';
break;
case 'UIOperationHistoryRedo':
prefix = 'event(redo)';
break;
case 'UIOperationHistoryPostRedo':
prefix = 'event(post-redo)';
break;
case 'UIOperationHistoryUndoComplete':
log.push('event(undo-complete)');
return;
case 'UIOperationHistoryRedoComplete':
log.push('event(redo-complete)');
return;
}
log.push(prefix+' '+aEvent.entry.name+' (level '+aEvent.params.level+')');
}
function toSimpleList(aString) {
return String(aString)
.replace(/^\s+|\s+$/g, '')
.replace(/\n\t+/g, '\n');
}
function setUp()
{
sv = window['piro.sakura.ne.jp'].operationHistory;
sv._db = {
histories : {},
observerRegistered : true
};
log = [];
eventListenersSetUp(window, 'global');
}
function tearDown()
{
eventListenersTearDown(window, 'global');
}
test_setGetWindowId.setUp = windowSetUp;
test_setGetWindowId.tearDown = windowTearDown;
function test_setGetWindowId()
{
sv.setWindowId(win, 'foobar');
assert.equals('foobar', sv.getWindowId(win));
assert.equals('foobar', sv.getWindowId(win, 'default'));
yield Do(windowTearDown());
yield Do(windowSetUp());
var id = sv.getWindowId(win, 'foobar');
assert.isNotNull(id);
assert.notEquals('', id);
var newId = sv.getWindowId(win, 'foobar');
assert.isNotNull(newId);
assert.equals(id, newId);
sv.setWindowId(win, 'foobar');
assert.equals('foobar', sv.getWindowId(win));
}
test_getWindowById.setUp = windowSetUp;
test_getWindowById.tearDown = windowTearDown;
function test_getWindowById()
{
var id = sv.getWindowId(win);
var windowFromId = sv.getWindowById(id);
assert.equals(win, windowFromId);
windowFromId = sv.getWindowById('does not exist!');
assert.isNull(windowFromId);
}
test_setGetElementId.setUp = windowSetUp;
test_setGetElementId.tearDown = windowTearDown;
function test_setGetElementId()
{
var element = win.gBrowser;
sv.setElementId(element, 'foobar');
assert.equals('foobar', sv.getElementId(element));
assert.equals('foobar', sv.getElementId(element, 'default'));
yield Do(windowTearDown());
yield Do(windowSetUp());
element = win.gBrowser;
var id = sv.getElementId(element, 'foobar');
assert.isNotNull(id);
assert.notEquals('', id);
var newId = sv.getElementId(element, 'foobar');
assert.equals(id, newId);
sv.setElementId(element, 'foobar');
assert.equals('foobar', sv.getElementId(element));
// duplicated id is not allowed.
newId = sv.setElementId(element.parentNode, 'foobar');
assert.equals(newId, sv.getElementId(element.parentNode));
assert.notEquals('foobar', newId);
assert.notEquals('foobar', sv.getElementId(element.parentNode));
}
test_getElementById.setUp = windowSetUp;
test_getElementById.tearDown = windowTearDown;
function test_getElementById()
{
var element = win.gBrowser;
var id = sv.getElementId(element);
var elementFromId = sv.getElementById(id, win);
assert.equals(element, elementFromId);
// returns null for a wrong parent
elementFromId = sv.getElementById(id, content);
assert.isNull(elementFromId);
elementFromId = sv.getElementById('does not exist!', win);
assert.isNull(elementFromId);
}
test_getId.setUp = windowSetUp;
test_getId.tearDown = windowTearDown;
function test_getId()
{
var id = sv.getId(win);
var windowFromId = sv.getWindowById(id);
assert.equals(win, windowFromId);
var element = win.gBrowser;
id = sv.getId(element);
assert.isNotNull(id);
var elementFromId = sv.getElementById(id, win);
assert.equals(element, elementFromId);
assert.isNull(sv.getId(''));
assert.isNull(sv.getId(0));
assert.isNull(sv.getId(false));
assert.isNull(sv.getId(null));
assert.isNull(sv.getId(undefined));
assert.raises('foo is an unknown type item.', function() {
sv.getId('foo');
});
}
test_getTargetById.setUp = windowSetUp;
test_getTargetById.tearDown = windowTearDown;
function test_getTargetById()
{
var element = win.gBrowser;
var windowId = sv.getId(win);
var elementId = sv.getId(element);
assert.equals(win, sv.getTargetById(windowId));
assert.equals(element, sv.getTargetById(elementId, win));
}
test_getTargetsByIds.setUp = windowSetUp;
test_getTargetsByIds.tearDown = windowTearDown;
function test_getTargetsByIds()
{
var tabs = [
win.gBrowser.addTab(),
win.gBrowser.addTab(),
win.gBrowser.addTab()
];
var ids = tabs.map(function(aTab) {
return sv.getId(aTab);
});
assert.equals(tabs, sv.getTargetsByIds(ids[0], ids[1], ids[2], win.gBrowser.mTabContainer));
assert.equals(tabs, sv.getTargetsByIds(ids, win.gBrowser.mTabContainer));
assert.equals([null, null, null], sv.getTargetsByIds(ids[0], ids[1], ids[2], win));
assert.equals([null, null, null], sv.getTargetsByIds(ids, win));
}
test_addEntry.setUp = windowSetUp;
test_addEntry.tearDown = windowTearDown;
function test_addEntry()
{
var name = 'foobar';
// register global-anonymous
sv.addEntry({ label : 'anonymous 1' });
sv.addEntry({ label : 'anonymous 2' });
sv.addEntry({ label : 'anonymous 3' });
// register global-named
sv.addEntry(name, { label : 'named 1' });
sv.addEntry(name, { label : 'named 2' });
sv.addEntry(name, { label : 'named 3' });
// register window-anonymous
sv.addEntry({ label : 'window, anonymous 1' }, win);
sv.addEntry({ label : 'window, anonymous 2' }, win);
sv.addEntry({ label : 'window, anonymous 3' }, win);
// register window-named
sv.addEntry(name, { label : 'window, named 1' }, win);
sv.addEntry(name, { label : 'window, named 2' }, win);
sv.addEntry(name, { label : 'window, named 3' }, win);
function assertHistory(aLabels, aCurrentIndex, aHistory)
{
assert.equals(aLabels.length, aHistory.entries.length);
assert.equals(aLabels,
aHistory.entries.map(function(aEntry) {
return aEntry.label;
}));
assert.equals(aCurrentIndex, aHistory.index);
}
assertHistory(
['anonymous 1',
'anonymous 2',
'anonymous 3'],
2,
sv.getHistory()
);
assertHistory(
['named 1',
'named 2',
'named 3'],
2,
sv.getHistory(name)
);
assertHistory(
['window, anonymous 1',
'window, anonymous 2',
'window, anonymous 3'],
2,
sv.getHistory(win)
);
assertHistory(
['window, named 1',
'window, named 2',
'window, named 3'],
2,
sv.getHistory(name, win)
);
}
function assertHistoryCount(aIndex, aCount)
{
var history = sv.getHistory();
assert.equals(
aIndex+' / '+aCount,
history.index+' / '+history.entries.length,
utils.inspect(history.entries)
);
}
function assertUndoingState(aExpectedUndoing, aExpectedRedoing, aMessage)
{
if (aExpectedUndoing)
assert.isTrue(sv.isUndoing(), aMessage);
else
assert.isFalse(sv.isUndoing(), aMessage);
if (aExpectedRedoing)
assert.isTrue(sv.isRedoing(), aMessage);
else
assert.isFalse(sv.isRedoing(), aMessage);
if (aExpectedUndoing || aExpectedRedoing)
assert.isFalse(sv.isUndoable(), aMessage);
else
assert.isTrue(sv.isUndoable(), aMessage);
}
function test_undoRedo_simple()
{
assertUndoingState(false, false);
sv.addEntry({ name : 'entry 1',
label : 'entry 1',
onUndo : function(aParams) {
log.push('u1');
assertUndoingState(true, false);
},
onRedo : function(aParams) {
log.push('r1');
assertUndoingState(false, true);
} });
sv.addEntry({ name : 'entry 2',
label : 'entry 2',
onPreUndo : function(aParams) {
log.push('u2pre');
assertUndoingState(true, false);
},
onUndo : function(aParams) {
log.push('u2');
assertUndoingState(true, false);
},
onRedo : function(aParams) {
log.push('r2');
assertUndoingState(false, true);
},
onPostRedo : function(aParams) {
log.push('r2post');
assertUndoingState(false, true);
} });
sv.addEntry({ name : 'entry 3',
label : 'entry 3' });
assertHistoryCount(2, 3);
assert.isTrue(sv.undo().done); // entry 3
assert.isTrue(sv.undo().done); // u2pre, u2
assertUndoingState(false, false);
assertHistoryCount(0, 3);
assert.isTrue(sv.redo().done); // r2, r2post
assert.isTrue(sv.redo().done); // entry 3
assertUndoingState(false, false);
assert.equals(
toSimpleList(<![CDATA[
event(pre-undo) entry 3 (level 0)
event(undo) entry 3 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
event(redo) entry 3 (level 0)
event(post-redo) entry 3 (level 0)
event(redo-complete)
]]>),
log.join('\n')
);
}
function test_undoRedo_goToIndex()
{
sv.addEntry({ name : 'entry 1',
label : 'entry 1',
onPreUndo : function(aParams) { log.push('u1pre'); },
onUndo : function(aParams) { log.push('u1'); sv.undo(); /* <= this should be ignored */ },
onRedo : function(aParams) { log.push('r1'); },
onPostRedo : function(aParams) { log.push('r1post'); } });
sv.addEntry({ name : 'entry 2',
label : 'entry 2',
onPreUndo : function(aParams) { log.push('u2pre'); },
onUndo : function(aParams) { log.push('u2'); },
onRedo : function(aParams) { log.push('r2'); sv.redo(); /* <= this should be ignored */ },
onPostRedo : function(aParams) { log.push('r2post'); sv.redo(); } });
sv.addEntry({ name : 'entry 3',
label : 'entry 3',
onPreUndo : function(aParams) { log.push('u3pre'); sv.undo(); /* <= this should be ignored */ },
onUndo : function(aParams) { log.push('u3'); sv.undo(); /* <= this should be ignored */ },
onRedo : function(aParams) { log.push('r3'); sv.redo(); /* <= this should be ignored */ },
onPostRedo : function(aParams) { log.push('r3post'); sv.redo(); /* <= this should be ignored */ } });
assertHistoryCount(2, 3);
sv.undo(); // u3pre, u3
assertHistoryCount(1, 3);
sv.redo(); // r3, r3post
assertHistoryCount(2, 3);
sv.undo(); // u3pre, u3
assertHistoryCount(1, 3);
sv.undo(); // u2pre, u2
assertHistoryCount(0, 3);
sv.undo(); // u1pre, u1
assertHistoryCount(0, 3);
sv.redo(); // r1, r1post
assertHistoryCount(0, 3);
sv.redo(); // r2, r2post
assertHistoryCount(1, 3);
sv.redo(); // r3, r3post
assertHistoryCount(2, 3);
sv.redo(); // --
assertHistoryCount(2, 3);
sv.redo(); // --
assertHistoryCount(2, 3);
sv.undo(); // u3pre, u3
assertHistoryCount(1, 3);
sv.undo(); // u2pre, u2
assertHistoryCount(0, 3);
sv.undo(); // u1pre, u1
assertHistoryCount(0, 3);
sv.undo(); // --
assertHistoryCount(0, 3);
sv.undo(); // --
assertHistoryCount(0, 3);
sv.undo(); // --
assertHistoryCount(0, 3);
sv.redo(); // r1, r1post
assertHistoryCount(0, 3);
sv.redo(); // r2, r2post
assertHistoryCount(1, 3);
log.push('----insert');
sv.addEntry({ name : 'entry 4',
label : 'entry 4',
onPreUndo : function(aParams) { log.push('u4pre'); sv.addEntry({ label: 'invalid/undo' }); },
onUndo : function(aParams) { log.push('u4'); sv.addEntry({ label: 'invalid/undo' }); },
onRedo : function(aParams) { log.push('r4'); sv.addEntry({ label: 'invalid/redo' }); },
onPostRedo : function(aParams) { log.push('r4post'); sv.addEntry({ label: 'invalid/redo' }); } });
assertHistoryCount(2, 3);
sv.undo(); // u4pre, u4
assertHistoryCount(1, 3);
sv.redo(); // r4, r4post
assertHistoryCount(2, 3);
sv.undo(); // u4pre, u4
assertHistoryCount(1, 3);
sv.undo(); // u2pre, u2
assertHistoryCount(0, 3);
sv.undo(); // u1pre, u1
assertHistoryCount(0, 3);
sv.redo(); // r1, r1post
assertHistoryCount(0, 3);
sv.redo(); // r2, r2post
assertHistoryCount(1, 3);
sv.redo(); // r4, r4post
assertHistoryCount(2, 3);
log.push('----goToIndex back');
sv.goToIndex(0);
log.push('----goToIndex forward');
sv.goToIndex(2);
assert.equals(
toSimpleList(<![CDATA[
u3pre
event(pre-undo) entry 3 (level 0)
u3
event(undo) entry 3 (level 0)
event(undo-complete)
r3
event(redo) entry 3 (level 0)
r3post
event(post-redo) entry 3 (level 0)
event(redo-complete)
u3pre
event(pre-undo) entry 3 (level 0)
u3
event(undo) entry 3 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
u1pre
event(pre-undo) entry 1 (level 0)
u1
event(undo) entry 1 (level 0)
event(undo-complete)
r1
event(redo) entry 1 (level 0)
r1post
event(post-redo) entry 1 (level 0)
event(redo-complete)
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
r3
event(redo) entry 3 (level 0)
r3post
event(post-redo) entry 3 (level 0)
event(redo-complete)
u3pre
event(pre-undo) entry 3 (level 0)
u3
event(undo) entry 3 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
u1pre
event(pre-undo) entry 1 (level 0)
u1
event(undo) entry 1 (level 0)
event(undo-complete)
r1
event(redo) entry 1 (level 0)
r1post
event(post-redo) entry 1 (level 0)
event(redo-complete)
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
----insert
u4pre
event(pre-undo) entry 4 (level 0)
u4
event(undo) entry 4 (level 0)
event(undo-complete)
r4
event(redo) entry 4 (level 0)
r4post
event(post-redo) entry 4 (level 0)
event(redo-complete)
u4pre
event(pre-undo) entry 4 (level 0)
u4
event(undo) entry 4 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
u1pre
event(pre-undo) entry 1 (level 0)
u1
event(undo) entry 1 (level 0)
event(undo-complete)
r1
event(redo) entry 1 (level 0)
r1post
event(post-redo) entry 1 (level 0)
event(redo-complete)
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
r4
event(redo) entry 4 (level 0)
r4post
event(post-redo) entry 4 (level 0)
event(redo-complete)
----goToIndex back
u4pre
event(pre-undo) entry 4 (level 0)
u4
event(undo) entry 4 (level 0)
event(undo-complete)
u2pre
event(pre-undo) entry 2 (level 0)
u2
event(undo) entry 2 (level 0)
event(undo-complete)
----goToIndex forward
r2
event(redo) entry 2 (level 0)
r2post
event(post-redo) entry 2 (level 0)
event(redo-complete)
r4
event(redo) entry 4 (level 0)
r4post
event(post-redo) entry 4 (level 0)
event(redo-complete)
]]>),
log.join('\n')
);
}
function handlEvent_skip(aEvent) {
if (aEvent.entry.name == 'skip both')
aEvent.skip();
}
test_undoRedo_skip.setUp = function() {
window.addEventListener('UIOperationHistoryUndo:global', handlEvent_skip, false);
window.addEventListener('UIOperationHistoryRedo:global', handlEvent_skip, false);
}
test_undoRedo_skip.tearDown = function() {
window.removeEventListener('UIOperationHistoryUndo:global', handlEvent_skip, false);
window.removeEventListener('UIOperationHistoryRedo:global', handlEvent_skip, false);
}
function test_undoRedo_skip()
{
sv.addEntry({ name : 'skip redo',
label : 'skip redo',
onUndo : function(aParams) { log.push('u redo'); },
onRedo : function(aParams) { log.push('r redo'); aParams.skip(); } });
sv.addEntry({ name : 'skip undo',
label : 'skip undo',
onUndo : function(aParams) { log.push('u undo'); aParams.skip(); },
onRedo : function(aParams) { log.push('r undo'); } });
sv.addEntry({ name : 'skip both',
label : 'skip both',
onUndo : function(aParams) { log.push('u both'); },
onRedo : function(aParams) { log.push('r both'); } });
sv.addEntry({ name : 'normal',
label : 'normal',
onUndo : function(aParams) { log.push('u normal'); },
onRedo : function(aParams) { log.push('r normal'); } });
assertHistoryCount(3, 4);
sv.undo(); // u normal
log.push('----');
assertHistoryCount(2, 4);
sv.undo(); // u both, u undo, u redo
log.push('----');
assertHistoryCount(0, 4);
sv.redo(); // r redo, r undo
log.push('----');
assertHistoryCount(1, 4);
sv.redo(); // r both, r normal
assertHistoryCount(3, 4);
assert.equals(
toSimpleList(<![CDATA[
event(pre-undo) normal (level 0)
u normal
event(undo) normal (level 0)
event(undo-complete)
----
event(pre-undo) skip both (level 0)
u both
event(undo) skip both (level 0)
event(pre-undo) skip undo (level 0)
u undo
event(undo) skip undo (level 0)
event(pre-undo) skip redo (level 0)
u redo
event(undo) skip redo (level 0)
event(undo-complete)
----
r redo
event(redo) skip redo (level 0)
event(post-redo) skip redo (level 0)
r undo
event(redo) skip undo (level 0)
event(post-redo) skip undo (level 0)
event(redo-complete)
----
r both
event(redo) skip both (level 0)
event(post-redo) skip both (level 0)
r normal
event(redo) normal (level 0)
event(post-redo) normal (level 0)
event(redo-complete)
]]>),
log.join('\n')
);
}
function test_undoRedo_wait()
{
sv.addEntry({ name : 'normal',
label : 'normal' });
sv.addEntry({
name : 'delayed',
label : 'delayed',
onPreUndo : function(aParams) {
aParams.wait();
window.setTimeout(function() {
aParams.continue();
}, 300);
},
onRedo : function(aParams) {
aParams.wait();
window.setTimeout(function() {
aParams.continue();
}, 300);
}
});
assertHistoryCount(1, 2);
var info;
assertUndoingState(false, false);
info = sv.undo();
assertHistoryCount(0, 2);
assert.isFalse(info.done);
assertUndoingState(true, false);
log.push('--waiting');
yield 600;
assert.isTrue(info.done);
assertUndoingState(false, false);
log.push('----');
info = sv.redo();
assertHistoryCount(1, 2);
assert.isFalse(info.done);
assertUndoingState(false, true);
log.push('--waiting');
yield 600;
assert.isTrue(info.done);
assertUndoingState(false, false);
assert.equals(
toSimpleList(<![CDATA[
event(pre-undo) delayed (level 0)
--waiting
event(undo) delayed (level 0)
event(undo-complete)
----
event(redo) delayed (level 0)
--waiting
event(post-redo) delayed (level 0)
event(redo-complete)
]]>),
log.join('\n')
);
}
function test_doOperation()
{
var info = sv.doOperation(
function(aParams) {
log.push('parent operation (level '+aParams.level+')');
sv.doOperation(
function(aParams) {
log.push('child operation (level '+aParams.level+')');
sv.doOperation(
function(aParams) {
log.push('deep operation (level '+aParams.level+')');
},
{ name : 'deep',
label : 'deep' }
);
// If the operation returns false,
// it should not be registered to the history.
sv.doOperation(
function(aParams) {
log.push('canceled operation (level '+aParams.level+')');
return false;
},
{ name : 'canceled',
label : 'canceled' }
);
},
{ name : 'child',
label : 'child',
onUndo : function(aParams) {
log.push('--canceled');
return false;
},
onPostRedo : function(aParams) {
log.push('--canceled');
return false;
} }
);
},
{ name : 'parent',
label : 'parent' }
);
assert.isTrue(info.done);
var history = sv.getHistory();
assert.equals(1, history.entries.length, utils.inspect(history.entries));
assert.equals('parent', history.entries[0].label, utils.inspect(history.entries[0]));
log.push('----');
sv.undo();
log.push('----');
sv.redo();
assert.equals(
toSimpleList(<![CDATA[
parent operation (level 0)
child operation (level 1)
deep operation (level 2)
canceled operation (level 2)
----
event(pre-undo) parent (level 0)
event(pre-undo) child (level 1)
event(pre-undo) deep (level 2)
event(undo) deep (level 2)
--canceled
event(undo-complete)
----
event(redo) parent (level 0)
event(redo) child (level 1)
event(redo) deep (level 2)
event(post-redo) deep (level 2)
--canceled
event(redo-complete)
]]>),
log.join('\n')
);
}
function handlEvent_cancel(aEvent) {
if (aEvent.entry.name == 'child') {
aEvent.preventDefault();
log.push('--canceled');
}
}
test_doOperation_canceledByEventListener.setUp = function() {
window.addEventListener('UIOperationHistoryUndo:global', handlEvent_cancel, false);
window.addEventListener('UIOperationHistoryPostRedo:global', handlEvent_cancel, false);
}
test_doOperation_canceledByEventListener.tearDown = function() {
window.removeEventListener('UIOperationHistoryUndo:global', handlEvent_cancel, false);
window.removeEventListener('UIOperationHistoryPostRedo:global', handlEvent_cancel, false);
}
function test_doOperation_canceledByEventListener()
{
var info = sv.doOperation(
function(aParams) {
log.push('parent operation (level '+aParams.level+')');
sv.doOperation(
function(aParams) {
log.push('child operation (level '+aParams.level+')');
sv.doOperation(
function(aParams) {
log.push('deep operation (level '+aParams.level+')');
},
{ name : 'deep',
label : 'deep' }
);
},
{ name : 'child',
label : 'child' }
);
},
{ name : 'parent',
label : 'parent' }
);
assert.isTrue(info.done);
var history = sv.getHistory();
assert.equals(1, history.entries.length, utils.inspect(history.entries));
assert.equals('parent', history.entries[0].label, utils.inspect(history.entries[0]));
log.push('----');
sv.undo();
log.push('----');
sv.redo();
assert.equals(
toSimpleList(<![CDATA[
parent operation (level 0)
child operation (level 1)
deep operation (level 2)
----
event(pre-undo) parent (level 0)
event(pre-undo) child (level 1)
event(pre-undo) deep (level 2)
event(undo) deep (level 2)
event(undo) child (level 1)
--canceled
event(undo-complete)
----
event(redo) parent (level 0)
event(redo) child (level 1)
event(redo) deep (level 2)
event(post-redo) deep (level 2)
event(post-redo) child (level 1)
--canceled
event(redo-complete)
]]>),
log.join('\n')
);
}
function test_doOperation_wait()
{
var info;
info = sv.doOperation(
function(aParams) {
log.push('op delayed parent (level '+aParams.level+')');
aParams.wait();
var info = sv.doOperation(
function(aParams) {
log.push('op normal child (level '+aParams.level+')');
},
{ name : 'normal child',
label : 'normal child' }
);
window.setTimeout(function() {
aParams.continue();
}, 300);
assert.isTrue(info.done);
},
{ name : 'delayed parent',
label : 'delayed parent' }
);
assert.isFalse(info.done);
yield 600;
assert.isTrue(info.done);
info = sv.doOperation(
function(aParams) {
log.push('op normal parent (level '+aParams.level+')');
var info = sv.doOperation(
function(aParams) {
log.push('op delayed child (level '+aParams.level+')');
aParams.wait();
window.setTimeout(function() {
aParams.continue();
}, 300);
},
{ name : 'delayed child',
label : 'delayed child' }
);
assert.isFalse(info.done);
},
{ name : 'normal parent',
label : 'normal parent' }
);
assert.isTrue(info.done);
log.push('----');
sv.undo();
log.push('----');
sv.undo();
log.push('----');
sv.redo();
log.push('----');
sv.redo();
assert.equals(
toSimpleList(<![CDATA[
op delayed parent (level 0)
op normal child (level 1)
op normal parent (level 0)
op delayed child (level 1)
----
event(pre-undo) normal parent (level 0)
event(pre-undo) delayed child (level 1)
event(undo) delayed child (level 1)
event(undo) normal parent (level 0)
event(undo-complete)
----
event(pre-undo) delayed parent (level 0)
event(pre-undo) normal child (level 1)
event(undo) normal child (level 1)
event(undo) delayed parent (level 0)
event(undo-complete)
----
event(redo) delayed parent (level 0)
event(redo) normal child (level 1)
event(post-redo) normal child (level 1)
event(post-redo) delayed parent (level 0)
event(redo-complete)
----
event(redo) normal parent (level 0)
event(redo) delayed child (level 1)
event(post-redo) delayed child (level 1)
event(post-redo) normal parent (level 0)
event(redo-complete)
]]>),
log.join('\n')
);
}
test_fakeUndoRedo.setUp = windowSetUp;
test_fakeUndoRedo.tearDown = windowTearDown;
function test_fakeUndoRedo()
{
var parent = [];
var child = [];
sv.doOperation(
function(aParams) {
sv.doOperation(
function(aParams) {
},
win,
(child[0] = {
name : 'child0',
label : 'child0'
})
);
},
win,
(parent[0] = {
name : 'parent0',
label : 'parent0'
})
);
sv.doOperation(
function(aParams) {
sv.doOperation(
function(aParams) {
},
win,
(child[1] = {
name : 'child1',
label : 'child1'
})
);
},
win,
(parent[1] = {
name : 'parent1',
label : 'parent1'
})
);
sv.doOperation(
function(aParams) {
sv.doOperation(
function(aParams) {
},
win,
(child[2] = {
name : 'child2',
label : 'child2'
})
);
},
win,
(parent[2] = {
name : 'parent2',
label : 'parent2'
})
);
var history = sv.getHistory(win);
assert.equals(2, history.index);
function assertFakeUndoSuccess(aCurrent, aEntry, aExpected)
{
log = [];
history.index = aCurrent;
sv.fakeUndo(aEntry, win);
assert.equals(aExpected, history.index);
assert.equals(['event(undo-complete)'], log);
}
function assertFakeUndoFail(aCurrent, aEntry)
{
log = [];
history.index = aCurrent;
sv.fakeUndo(aEntry, win);
var current = Math.min(aCurrent, history.entries.length-1);
assert.equals(current, history.index);
assert.equals([], log);
}
assertFakeUndoFail(2, parent[0]);
assertFakeUndoSuccess(2, parent[1], 0);
assertFakeUndoSuccess(2, parent[2], 1);
assertFakeUndoFail(3, parent[0]);
assertFakeUndoFail(3, parent[1]);
assertFakeUndoSuccess(3, parent[2], 1);
assertFakeUndoFail(2, child[0]);
assertFakeUndoSuccess(2, child[1], 0);
assertFakeUndoSuccess(2, child[2], 1);
assertFakeUndoFail(3, child[0]);
assertFakeUndoFail(3, child[1]);
assertFakeUndoSuccess(3, child[2], 1);
function assertFakeRedoSuccess(aCurrent, aEntry, aExpected)
{
log = [];
history.index = aCurrent;
sv.fakeRedo(aEntry, win);
assert.equals(aExpected, history.index);
assert.equals(['event(redo-complete)'], log);
}
function assertFakeRedoFail(aCurrent, aEntry)
{
log = [];
history.index = aCurrent;
sv.fakeRedo(aEntry, win);
var current = Math.max(aCurrent, 0);
assert.equals(current, history.index);
assert.equals([], log);
}
assertFakeRedoSuccess(-1, parent[0], 1);
assertFakeRedoFail(-1, parent[1]);
assertFakeRedoFail(-1, parent[2]);
assertFakeRedoSuccess(0, parent[0], 1);
assertFakeRedoSuccess(0, parent[1], 2);
assertFakeRedoFail(0, parent[2]);
assertFakeRedoSuccess(-1, child[0], 1);
assertFakeRedoFail(-1, child[1]);
assertFakeRedoFail(-1, child[2]);
assertFakeRedoSuccess(0, child[0], 1);
assertFakeRedoSuccess(0, child[1], 2);
assertFakeRedoFail(0, child[2]);
}
function test_exceptions()
{
assert.raises('EXCEPTION FROM UNDOABLE OPERATION', function() {
sv.doOperation(
function(aParams) {
log.push('op success (level '+aParams.level+')');
sv.doOperation(
function(aParams) {
log.push('op fail (level '+aParams.level+')');
throw 'EXCEPTION FROM UNDOABLE OPERATION';
},
{ name : 'cannot redo',
label : 'cannot redo',
onUndo : function(aParams) {
log.push('u cannot redo');
},
onRedo : function(aParams) {
throw 'EXCEPTION FROM REDO PROCESS';
log.push('r cannot redo');
} }
);
},
{ name : 'cannot undo',
label : 'cannot undo',
onUndo : function(aParams) {
throw 'EXCEPTION FROM UNDO PROCESS';
log.push('u cannot undo');
},
onRedo : function(aParams) {
log.push('r cannot undo');
} }
);
});
log.push('----');
assert.raises('EXCEPTION FROM UNDO PROCESS', function() {
sv.undo();
});
assert.raises('EXCEPTION FROM REDO PROCESS', function() {
sv.redo();
});
assert.equals(
toSimpleList(<![CDATA[
op success (level 0)
op fail (level 1)
----
event(pre-undo) cannot undo (level 0)
event(pre-undo) cannot redo (level 1)
u cannot redo
event(undo) cannot redo (level 1)
r cannot undo
event(redo) cannot undo (level 0)
]]>),
log.join('\n')
);
}
/* tests for internal classes */
function test_UIHistory_init()
{
var history = new sv.UIHistory('test', null, null);
assert.equals([], history.entries);
assert.equals([], history.metaData);
assert.equals(-1, history.index);
assert.isFalse(history.inOperation);
}
var testMaxPrefKeyGlobal = 'extensions.UIOperationsHistoryManager@piro.sakura.ne.jp.test.max.global';
var testMaxPrefKeyWindow = 'extensions.UIOperationsHistoryManager@piro.sakura.ne.jp.test.max.window';
test_UIHistory_max_global.setUp = test_UIHistory_max_window.setUp = function() {
utils.clearPref(testMaxPrefKeyGlobal);
utils.clearPref(testMaxPrefKeyWindow);
assert.isNull(utils.getPref(testMaxPrefKeyGlobal));
assert.isNull(utils.getPref(testMaxPrefKeyWindow));
};
test_UIHistory_max_global.tearDown = test_UIHistory_max_window.tearDown = function() {
utils.clearPref(testMaxPrefKeyGlobal);
utils.clearPref(testMaxPrefKeyWindow);
};
function test_UIHistory_max_global()
{
var maxDefault = sv.UIHistory.prototype.MAX_ENTRIES;
var history;
history = new sv.UIHistory('test', null, null);
assert.equals(maxDefault, history.max);
assert.equals(testMaxPrefKeyGlobal, history.maxPref);
history.max = 10;
assert.equals(10, history.max);
assert.equals(10, utils.getPref(testMaxPrefKeyGlobal));
assert.isNull(utils.getPref(testMaxPrefKeyWindow));
history = new sv.UIHistory('test', null, null);
assert.equals(10, history.max);
history = new sv.UIHistory('test', window, 'test');
assert.equals(maxDefault, history.max);
}
function test_UIHistory_max_window()
{
var maxDefault = sv.UIHistory.prototype.MAX_ENTRIES;
var history
history = new sv.UIHistory('test', window, 'test');
assert.equals(maxDefault, history.max);
assert.equals(testMaxPrefKeyWindow, history.maxPref);
history.max = 10;
assert.equals(10, history.max);
assert.isNull(utils.getPref(testMaxPrefKeyGlobal));
assert.equals(10, utils.getPref(testMaxPrefKeyWindow));
history = new sv.UIHistory('test', null, null);
assert.equals(maxDefault, history.max);
history = new sv.UIHistory('test', window, 'test');
assert.equals(10, history.max);
}
function test_UIHistory_addEntry()
{
var history = new sv.UIHistory('test', null, null);
assert.equals([], history.entries);
assert.equals([], history.metaData);
assert.equals(-1, history.index);
assert.isFalse(history.inOperation);
history.addEntry(0);
history.addEntry(1);
history.addEntry(2);
assert.equals([0, 1, 2], history.entries);
assert.equals(3, history.metaData.length);
assert.equals([], history.metaData[0].children);
assert.equals([], history.metaData[1].children);
assert.equals([], history.metaData[2].children);
assert.equals(3, history.index);
history.inOperation = true;
history.addEntry(3);
history.addEntry(4);
history.addEntry(5);
assert.equals([0, 1, 2], history.entries);
assert.equals(3, history.metaData.length);
assert.equals([], history.metaData[0].children);
assert.equals([], history.metaData[1].children);
assert.equals([3, 4, 5], history.metaData[2].children);
assert.equals(3, history.index);
history.inOperation = false;
history.addEntry(6);
assert.equals([0, 1, 2, 6], history.entries);
assert.equals(4, history.metaData.length);
assert.equals(4, history.index);
}
function test_UIHistory_canUndoRedo()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry(0);
history.addEntry(1);
history.addEntry(2);
assert.isTrue(history.canUndo);
assert.isFalse(history.canRedo);
history.index = 4;
assert.isTrue(history.canUndo);
assert.isFalse(history.canRedo);
history.index = 10;
assert.isTrue(history.canUndo);
assert.isFalse(history.canRedo);
history.index = 0;
assert.isTrue(history.canUndo);
assert.isTrue(history.canRedo);
history.index = -1;
assert.isFalse(history.canUndo);
assert.isTrue(history.canRedo);
history.index = -10;
assert.isFalse(history.canUndo);
assert.isTrue(history.canRedo);
history.index = 1;
assert.isTrue(history.canUndo);
assert.isTrue(history.canRedo);
}
function test_UIHistory_currentLastEntry()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry('0');
history.addEntry('1');
history.addEntry('2');
assert.isNull(history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = 2;
assert.equals('2', history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = 4;
assert.isNull(history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = 10;
assert.isNull(history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = 0;
assert.equals('0', history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = -1;
assert.isNull(history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = -10;
assert.isNull(history.currentEntry);
assert.equals('2', history.lastEntry);
history.index = 1;
assert.equals('1', history.currentEntry);
assert.equals('2', history.lastEntry);
}
function test_UIHistory_currentLastMetaData()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry('0');
history.addEntry('1');
history.addEntry('2');
var metaData = history.metaData;
assert.isNull(history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = 2;
assert.strictlyEquals(metaData[2], history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = 4;
assert.isNull(history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = 10;
assert.isNull(history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = 0;
assert.strictlyEquals(metaData[0], history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = -1;
assert.isNull(history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = -10;
assert.isNull(history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
history.index = 1;
assert.strictlyEquals(metaData[1], history.currentMetaData);
assert.strictlyEquals(metaData[2], history.lastMetaData);
}
function test_UIHistory_currentLastEntries()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry('0');
history.inOperation = true;
history.addEntry('0.1');
history.addEntry('0.2');
history.inOperation = false;
history.addEntry('1');
history.inOperation = true;
history.addEntry('1.1');
history.addEntry('1.2');
history.inOperation = false;
history.addEntry('2');
history.inOperation = true;
history.addEntry('2.1');
history.addEntry('2.2');
history.inOperation = false;
assert.equals([], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = 2;
assert.equals(['2', '2.1', '2.2'], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = 4;
assert.equals([], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = 10;
assert.equals([], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = 0;
assert.equals(['0', '0.1', '0.2'], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = -1;
assert.equals([], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = -10;
assert.equals([], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
history.index = 1;
assert.equals(['1', '1.1', '1.2'], history.currentEntries);
assert.equals(['2', '2.1', '2.2'], history.lastEntries);
}
function test_UIHistory_namedEntry()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry({ name : '0' });
history.inOperation = true;
history.addEntry({ name : '1' });
history.addEntry({ name : '2' });
history.addEntry({ name : '3' });
history.inOperation = false;
assert.equals('0,1,2,3', history.metaData[history.safeIndex].names.join(','));
}
function test_UIHistoryProxy_index()
{
var history = new sv.UIHistory('test', null, null);
history.addEntry('0');
history.addEntry('1');
history.addEntry('2');
var proxy = new sv.UIHistoryProxy(history);
history.index = 0;
assert.equals(0, proxy.index);
history.index = -1;
assert.equals(0, proxy.index);
history.index = -10;
assert.equals(0, proxy.index);
history.index = 2;
assert.equals(2, proxy.index);
history.index = 3;
assert.equals(2, proxy.index);
history.index = 10;
assert.equals(2, proxy.index);
}
function test_UIHistoryMetaData_children()
{
var metaData = new sv.UIHistoryMetaData();
assert.equals([], metaData.children);
}
| テスト項目追加
git-svn-id: 8f7ef6d58c3e93671c5a6659438fbe5b913ea811@6108 599a83e7-65a4-db11-8015-0010dcdd6dc2
| operationHistory.test.js | テスト項目追加 | <ide><path>perationHistory.test.js
<ide>
<ide> log.push('----goToIndex back');
<ide> sv.goToIndex(0);
<add> log.push('----goToIndex same');
<add> sv.goToIndex(0);
<ide> log.push('----goToIndex forward');
<ide> sv.goToIndex(2);
<add> log.push('----goToIndex back');
<add> sv.goToIndex(-5);
<add> log.push('----goToIndex forward');
<add> sv.goToIndex(5);
<ide>
<ide> assert.equals(
<ide> toSimpleList(<![CDATA[
<ide> u2
<ide> event(undo) entry 2 (level 0)
<ide> event(undo-complete)
<add> ----goToIndex same
<ide> ----goToIndex forward
<add> r2
<add> event(redo) entry 2 (level 0)
<add> r2post
<add> event(post-redo) entry 2 (level 0)
<add> event(redo-complete)
<add> r4
<add> event(redo) entry 4 (level 0)
<add> r4post
<add> event(post-redo) entry 4 (level 0)
<add> event(redo-complete)
<add> ----goToIndex back
<add> u4pre
<add> event(pre-undo) entry 4 (level 0)
<add> u4
<add> event(undo) entry 4 (level 0)
<add> event(undo-complete)
<add> u2pre
<add> event(pre-undo) entry 2 (level 0)
<add> u2
<add> event(undo) entry 2 (level 0)
<add> event(undo-complete)
<add> u1pre
<add> event(pre-undo) entry 1 (level 0)
<add> u1
<add> event(undo) entry 1 (level 0)
<add> event(undo-complete)
<add> ----goToIndex forward
<add> r1
<add> event(redo) entry 1 (level 0)
<add> r1post
<add> event(post-redo) entry 1 (level 0)
<add> event(redo-complete)
<ide> r2
<ide> event(redo) entry 2 (level 0)
<ide> r2post |
|
JavaScript | mit | c9f9b478bab2cd8d0f44d5bd4c7f56b1ada9ec76 | 0 | Efiware/bootstrap-tokenfield,syscover/bootstrap-tokenfield,nazart/bootstrap-tokenfield,mean-cj/bootstrap-tokenfield,sliptree/bootstrap-tokenfield,vrkansagara/bootstrap-tokenfield,lifejuggler/bootstrap-tokenfield,Efiware/bootstrap-tokenfield,lifejuggler/bootstrap-tokenfield,sliptree/bootstrap-tokenfield,nazart/bootstrap-tokenfield,syscover/bootstrap-tokenfield,mean-cj/bootstrap-tokenfield,vrkansagara/bootstrap-tokenfield | /* ============================================================
* bootstrap-tokenfield.js v0.10.0
* ============================================================
*
* Copyright 2013 Sliptree
* ============================================================ */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
root.Tokenfield = factory(root.jQuery);
}
}(this, function ($) {
"use strict"; // jshint ;_;
/* TOKENFIELD PUBLIC CLASS DEFINITION
* ============================== */
var Tokenfield = function (element, options) {
var _self = this
this.$element = $(element)
this.direction = this.$element.css('direction') === 'ltr' ? 'left' : 'right'
// Extend options
this.options = $.extend({}, $.fn.tokenfield.defaults, { tokens: this.$element.val() }, options)
// Setup delimiters and trigger keys
this._delimiters = (typeof this.options.delimiter === 'string') ? [this.options.delimiter] : this.options.delimiter
this._triggerKeys = $.map(this._delimiters, function (delimiter) {
return delimiter.charCodeAt(0);
});
// Store original input width
var elRules = (typeof window.getMatchedCSSRules === 'function') ? window.getMatchedCSSRules( element ) : null
, elStyleWidth = element.style.width
, elCSSWidth
, elWidth = this.$element.width()
if (elRules) {
$.each( elRules, function (i, rule) {
if (rule.style.width) {
elCSSWidth = rule.style.width;
}
});
}
// Move original input out of the way
this.$element.css('position', 'absolute').css(this.direction, '-10000px').prop('tabindex', -1)
// Create a wrapper
this.$wrapper = $('<div class="tokenfield form-control" />')
if (this.$element.hasClass('input-lg')) this.$wrapper.addClass('input-lg')
if (this.$element.hasClass('input-sm')) this.$wrapper.addClass('input-sm')
if (this.direction === 'right') this.$wrapper.addClass('rtl')
// Create a new input
var id = this.$element.prop('id') || new Date().getTime() + '' + Math.floor((1 + Math.random()) * 100)
this.$input = $('<input type="text" class="token-input" autocomplete="off" />')
.appendTo( this.$wrapper )
.prop( 'placeholder', this.$element.prop('placeholder') )
.prop( 'id', id + '-tokenfield' )
// Re-route original input label to new input
var $label = $( 'label[for="' + this.$element.prop('id') + '"]' )
if ( $label.length ) {
$label.prop( 'for', this.$input.prop('id') )
}
// Set up a copy helper to handle copy & paste
this.$copyHelper = $('<input type="text" />').css('position', 'absolute').css(this.direction, '-10000px').prop('tabindex', -1).prependTo( this.$wrapper )
// Set wrapper width
if (elStyleWidth) {
this.$wrapper.css('width', elStyleWidth);
}
else if (elCSSWidth) {
this.$wrapper.css('width', elCSSWidth);
}
// If input is inside inline-form with no width set, set fixed width
else if (this.$element.parents('.form-inline').length) {
this.$wrapper.width( elWidth )
}
// Set tokenfield disabled, if original or fieldset input is disabled
if (this.$element.prop('disabled') || this.$element.parents('fieldset[disabled]').length) {
this.disable();
}
// Set up mirror for input auto-sizing
this.$mirror = $('<span style="position:absolute; top:-999px; left:0; white-space:pre;"/>');
this.$input.css('min-width', this.options.minWidth + 'px')
$.each([
'fontFamily',
'fontSize',
'fontWeight',
'fontStyle',
'letterSpacing',
'textTransform',
'wordSpacing',
'textIndent'
], function (i, val) {
_self.$mirror[0].style[val] = _self.$input.css(val);
});
this.$mirror.appendTo( 'body' )
// Insert tokenfield to HTML
this.$wrapper.insertBefore( this.$element )
this.$element.prependTo( this.$wrapper )
// Calculate inner input width
this.update()
// Create initial tokens, if any
this.setTokens(this.options.tokens, false, false)
// Start listening to events
this.listen()
// Initialize autocomplete, if necessary
if ( ! $.isEmptyObject( this.options.autocomplete ) ) {
var autocompleteOptions = $.extend({}, this.options.autocomplete, {
minLength: this.options.showAutocompleteOnFocus ? 0 : null,
position: { my: this.direction + " top", at: this.direction + " bottom", of: this.$wrapper }
})
this.$input.autocomplete( autocompleteOptions )
}
// Initialize typeahead, if necessary
if ( ! $.isEmptyObject( this.options.typeahead ) ) {
var typeaheadOptions = $.extend({}, this.options.typeahead, {})
this.$input.typeahead( typeaheadOptions )
this.typeahead = true
}
}
Tokenfield.prototype = {
constructor: Tokenfield
, createToken: function (attrs, triggerChange) {
if (typeof attrs === 'string') {
attrs = { value: attrs, label: attrs }
}
if (typeof triggerChange === 'undefined') {
triggerChange = true
}
var _self = this
, value = $.trim(attrs.value)
, label = attrs.label.length ? $.trim(attrs.label) : value
if (!value.length || !label.length || value.length < this.options.minLength) return
if (this.options.limit && this.getTokens().length >= this.options.limit) return
// Allow changing token data before creating it
var beforeCreateEvent = $.Event('beforeCreateToken')
beforeCreateEvent.token = {
value: value,
label: label
}
this.$element.trigger( beforeCreateEvent )
if (!beforeCreateEvent.token) return
value = beforeCreateEvent.token.value
label = beforeCreateEvent.token.label
// Check for duplicates
if (!this.options.allowDuplicates && $.grep(this.getTokens(), function (token) {
return token.value === value
}).length) {
// Allow listening to when duplicates get prevented
var duplicateEvent = $.Event('preventDuplicateToken')
duplicateEvent.token = {
value: value,
label: label
}
this.$element.trigger( duplicateEvent )
// Add duplicate warning class to existing token for 250ms
var duplicate = this.$wrapper.find( '.token[data-value="' + value + '"]' ).addClass('duplicate')
setTimeout(function() {
duplicate.removeClass('duplicate');
}, 250)
return false
}
var token = $('<div class="token" />')
.attr('data-value', value)
.append('<span class="token-label" />')
.append('<a href="#" class="close" tabindex="-1">×</a>')
// Insert token into HTML
if (this.$input.hasClass('tt-query')) {
this.$input.parent().before( token )
} else {
this.$input.before( token )
}
this.$input.css('width', this.options.minWidth + 'px')
var tokenLabel = token.find('.token-label')
, closeButton = token.find('.close')
// Determine maximum possible token label width
if (!this.maxTokenWidth) {
this.maxTokenWidth =
this.$wrapper.width() - closeButton.outerWidth() -
parseInt(closeButton.css('margin-left'), 10) -
parseInt(closeButton.css('margin-right'), 10) -
parseInt(token.css('border-left-width'), 10) -
parseInt(token.css('border-right-width'), 10) -
parseInt(token.css('padding-left'), 10) -
parseInt(token.css('padding-right'), 10)
parseInt(tokenLabel.css('border-left-width'), 10) -
parseInt(tokenLabel.css('border-right-width'), 10) -
parseInt(tokenLabel.css('padding-left'), 10) -
parseInt(tokenLabel.css('padding-right'), 10)
parseInt(tokenLabel.css('margin-left'), 10) -
parseInt(tokenLabel.css('margin-right'), 10)
}
tokenLabel
.text(label)
.css('max-width', this.maxTokenWidth)
// Listen to events
token
.on('mousedown', function (e) {
if (_self.disabled) return false;
_self.preventDeactivation = true
})
.on('click', function (e) {
if (_self.disabled) return false;
_self.preventDeactivation = false
if (e.ctrlKey || e.metaKey) {
e.preventDefault()
return _self.toggle( token )
}
_self.activate( token, e.shiftKey, e.shiftKey )
})
.on('dblclick', function (e) {
if (_self.disabled) return false;
_self.edit( token )
})
closeButton
.on('click', $.proxy(this.remove, this))
var afterCreateEvent = $.Event('afterCreateToken')
afterCreateEvent.token = beforeCreateEvent.token
afterCreateEvent.relatedTarget = token.get(0)
this.$element.trigger( afterCreateEvent )
var changeEvent = $.Event('change')
changeEvent.initiator = 'tokenfield'
if (triggerChange) {
this.$element.val( this.getTokensList() ).trigger( changeEvent )
}
this.update()
return this.$input.get(0)
}
, setTokens: function (tokens, add, triggerChange) {
if (!tokens) return
if (!add) this.$wrapper.find('.token').remove()
if (typeof triggerChange === 'undefined') {
triggerChange = true
}
if (typeof tokens === 'string') {
if (this._delimiters.length) {
tokens = tokens.split( new RegExp( '[' + this._delimiters.join('') + ']' ) )
} else {
tokens = [tokens];
}
}
var _self = this
$.each(tokens, function (i, token) {
_self.createToken(token, triggerChange)
})
return this.$element.get(0)
}
, getTokenData: function(token) {
var data = token.map(function() {
var $token = $(this);
return {
value: $token.attr('data-value') || $token.find('.token-label').text(),
label: $token.find('.token-label').text()
}
}).get();
if (data.length == 1) {
data = data[0];
}
return data;
}
, getTokens: function(active) {
var self = this
, tokens = []
, activeClass = active ? '.active' : '' // get active tokens only
this.$wrapper.find( '.token' + activeClass ).each( function() {
tokens.push( self.getTokenData( $(this) ) )
})
return tokens
}
, getTokensList: function(delimiter, beautify, active) {
delimiter = delimiter || this._delimiters[0]
beautify = ( typeof beautify !== 'undefined' && beautify !== null ) ? beautify : this.options.beautify
var separator = delimiter + ( beautify && delimiter !== ' ' ? ' ' : '')
return $.map( this.getTokens(active), function (token) {
return token.value
}).join(separator)
}
, getInput: function() {
return this.$input.val()
}
, listen: function () {
var _self = this
this.$element
.on('change', $.proxy(this.change, this))
this.$wrapper
.on('mousedown',$.proxy(this.focusInput, this))
this.$input
.on('focus', $.proxy(this.focus, this))
.on('blur', $.proxy(this.blur, this))
.on('paste', $.proxy(this.paste, this))
.on('keydown', $.proxy(this.keydown, this))
.on('keypress', $.proxy(this.keypress, this))
.on('keyup', $.proxy(this.keyup, this))
this.$copyHelper
.on('focus', $.proxy(this.focus, this))
.on('blur', $.proxy(this.blur, this))
.on('keydown', $.proxy(this.keydown, this))
.on('keyup', $.proxy(this.keyup, this))
// Secondary listeners for input width calculation
this.$input
.on('keypress', $.proxy(this.update, this))
.on('keyup', $.proxy(this.update, this))
this.$input
.on('autocompletecreate', function() {
// Set minimum autocomplete menu width
var $_menuElement = $(this).data('ui-autocomplete').menu.element
var minWidth = _self.$wrapper.outerWidth() -
parseInt( $_menuElement.css('border-left-width'), 10 ) -
parseInt( $_menuElement.css('border-right-width'), 10 )
$_menuElement.css( 'min-width', minWidth + 'px' )
})
.on('autocompleteselect', function (e, ui) {
if (_self.createToken( ui.item )) {
_self.$input.val('')
if (_self.$input.data( 'edit' )) {
_self.unedit(true)
}
}
return false
})
.on('typeahead:selected', function (e, datum, dataset) {
var valueKey = 'value'
// Get the actual valueKey for this dataset
$.each(_self.$input.data('ttView').datasets, function (i, set) {
if (set.name === dataset) {
valueKey = set.valueKey
}
})
// Create token
if (_self.createToken( datum[valueKey] )) {
_self.$input.typeahead('setQuery', '')
if (_self.$input.data( 'edit' )) {
_self.unedit(true)
}
}
})
.on('typeahead:autocompleted', function (e, datum, dataset) {
_self.createToken( _self.$input.val() )
_self.$input.typeahead('setQuery', '')
if (_self.$input.data( 'edit' )) {
_self.unedit(true)
}
})
// Listen to window resize
$(window).on('resize', $.proxy(this.update, this ))
}
, keydown: function (e) {
if (!this.focused) return
switch(e.keyCode) {
case 8: // backspace
if (!this.$input.is(document.activeElement)) break
this.lastInputValue = this.$input.val()
break
case 37: // left arrow
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length > 0) break
var prev = this.$input.hasClass('tt-query') ? this.$input.parent().prevAll('.token:first') : this.$input.prevAll('.token:first')
if (!prev.length) break
this.preventInputFocus = true
this.preventDeactivation = true
this.activate( prev )
e.preventDefault()
} else {
this.prev( e.shiftKey )
e.preventDefault()
}
break
case 38: // up arrow
if (!e.shiftKey) return
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length > 0) break
var prev = this.$input.hasClass('tt-query') ? this.$input.parent().prevAll('.token:last') : this.$input.prevAll('.token:last')
if (!prev.length) return
this.activate( prev )
}
var _self = this
this.firstActiveToken.nextAll('.token').each(function() {
_self.deactivate( $(this) )
})
this.activate( this.$wrapper.find('.token:first'), true, true )
e.preventDefault()
break
case 39: // right arrow
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length > 0) break
var next = this.$input.hasClass('tt-query') ? this.$input.parent().nextAll('.token:first') : this.$input.nextAll('.token:first')
if (!next.length) break
this.preventInputFocus = true
this.preventDeactivation = true
this.activate( next )
e.preventDefault()
} else {
this.next( e.shiftKey )
e.preventDefault()
}
break
case 40: // down arrow
if (!e.shiftKey) return
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length > 0) break
var next = this.$input.hasClass('tt-query') ? this.$input.parent().nextAll('.token:first') : this.$input.nextAll('.token:first')
if (!next.length) return
this.activate( next )
}
var _self = this
this.firstActiveToken.prevAll('.token').each(function() {
_self.deactivate( $(this) )
})
this.activate( this.$wrapper.find('.token:last'), true, true )
e.preventDefault()
break
case 65: // a (to handle ctrl + a)
if (this.$input.val().length > 0 || !(e.ctrlKey || e.metaKey)) break
this.activateAll()
e.preventDefault()
break
case 9: // tab
case 13: // enter
// We will handle creating tokens from autocomplete in autocomplete events
if (this.$input.data('ui-autocomplete') && this.$input.data('ui-autocomplete').menu.element.find("li:has(a.ui-state-focus)").length) break
// We will handle creating tokens from typeahead in typeahead events
if (this.$input.hasClass('tt-query') && this.$wrapper.find('.tt-is-under-cursor').length ) break
if (this.$input.hasClass('tt-query') && this.$wrapper.find('.tt-hint').val().length) break
// Create token
if (this.$input.is(document.activeElement) && this.$input.val().length || this.$input.data('edit')) {
return this.createTokensFromInput(e, this.$input.data('edit'));
}
// Edit token
if (e.keyCode === 13) {
if (!this.$copyHelper.is(document.activeElement) || this.$wrapper.find('.token.active').length !== 1) break
this.edit( this.$wrapper.find('.token.active') )
}
}
this.lastKeyDown = e.keyCode
}
, keypress: function(e) {
this.lastKeyPressCode = e.keyCode
this.lastKeyPressCharCode = e.charCode
// Comma
if ($.inArray( e.charCode, this._triggerKeys) !== -1 && this.$input.is(document.activeElement)) {
if (this.$input.val()) {
this.createTokensFromInput(e)
}
return false;
}
}
, keyup: function (e) {
this.preventInputFocus = false
if (!this.focused) return
switch(e.keyCode) {
case 8: // backspace
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length || this.lastInputValue.length && this.lastKeyDown === 8) break
this.preventDeactivation = true
var prev = this.$input.hasClass('tt-query') ? this.$input.parent().prevAll('.token:first') : this.$input.prevAll('.token:first')
if (!prev.length) break
this.activate( prev )
} else {
this.remove(e)
}
break
case 46: // delete
this.remove(e, 'next')
break
}
this.lastKeyUp = e.keyCode
}
, focus: function (e) {
this.focused = true
this.$wrapper.addClass('focus')
if (this.$input.is(document.activeElement)) {
this.$wrapper.find('.active').removeClass('active')
this.firstActiveToken = null
if (this.options.showAutocompleteOnFocus) {
this.search()
}
}
}
, blur: function (e) {
this.focused = false
this.$wrapper.removeClass('focus')
if (!this.preventDeactivation && !this.$element.is(document.activeElement)) {
this.$wrapper.find('.active').removeClass('active')
this.firstActiveToken = null
}
if (!this.preventCreateTokens && (this.$input.data('edit') && !this.$input.is(document.activeElement) || this.options.createTokensOnBlur )) {
this.createTokensFromInput(e)
}
this.preventDeactivation = false
this.preventCreateTokens = false
}
, paste: function (e) {
var _self = this
// Add tokens to existing ones
setTimeout(function () {
_self.createTokensFromInput(e)
}, 1)
}
, change: function (e) {
if ( e.initiator === 'tokenfield' ) return // Prevent loops
this.setTokens( this.$element.val() )
}
, createTokensFromInput: function (e, focus) {
if (this.$input.val().length < this.options.minLength)
return // No input, simply return
var tokensBefore = this.getTokensList()
this.setTokens( this.$input.val(), true )
if (tokensBefore == this.getTokensList() && this.$input.val().length)
return false // No tokens were added, do nothing (prevent form submit)
if (this.$input.hasClass('tt-query')) {
// Typeahead acts weird when simply setting input value to empty,
// so we set the query to empty instead
this.$input.typeahead('setQuery', '')
} else {
this.$input.val('')
}
if (this.$input.data( 'edit' )) {
this.unedit(focus)
}
return false // Prevent form being submitted
}
, next: function (add) {
if (add) {
var firstActive = this.$wrapper.find('.active:first')
, deactivate = firstActive && this.firstActiveToken ? firstActive.index() < this.firstActiveToken.index() : false
if (deactivate) return this.deactivate( firstActive )
}
var active = this.$wrapper.find('.active:last')
, next = active.nextAll('.token:first')
if (!next.length) {
this.$input.focus()
return
}
this.activate(next, add)
}
, prev: function (add) {
if (add) {
var lastActive = this.$wrapper.find('.active:last')
, deactivate = lastActive && this.firstActiveToken ? lastActive.index() > this.firstActiveToken.index() : false
if (deactivate) return this.deactivate( lastActive )
}
var active = this.$wrapper.find('.active:first')
, prev = active.prevAll('.token:first')
if (!prev.length) {
prev = this.$wrapper.find('.token:first')
}
if (!prev.length && !add) {
this.$input.focus()
return
}
this.activate( prev, add )
}
, activate: function (token, add, multi, remember) {
if (!token) return
if (this.$wrapper.find('.token.active').length === this.$wrapper.find('.token').length) return
if (typeof remember === 'undefined') var remember = true
if (multi) var add = true
this.$copyHelper.focus()
if (!add) {
this.$wrapper.find('.active').removeClass('active')
if (remember) {
this.firstActiveToken = token
} else {
delete this.firstActiveToken
}
}
if (multi && this.firstActiveToken) {
// Determine first active token and the current tokens indicies
// Account for the 1 hidden textarea by subtracting 1 from both
var i = this.firstActiveToken.index() - 2
, a = token.index() - 2
, _self = this
this.$wrapper.find('.token').slice( Math.min(i, a) + 1, Math.max(i, a) ).each( function() {
_self.activate( $(this), true )
})
}
token.addClass('active')
this.$copyHelper.val( this.getTokensList( null, null, true ) ).select()
}
, activateAll: function() {
var _self = this
this.$wrapper.find('.token').each( function (i) {
_self.activate($(this), i !== 0, false, false)
})
}
, deactivate: function(token) {
if (!token) return
token.removeClass('active')
this.$copyHelper.val( this.getTokensList( null, null, true ) ).select()
}
, toggle: function(token) {
if (!token) return
token.toggleClass('active')
this.$copyHelper.val( this.getTokensList( null, null, true ) ).select()
}
, edit: function (token) {
if (!token) return
var value = token.data('value')
, label = token.find('.token-label').text()
// Allow changing input value before editing
var beforeEditEvent = $.Event('beforeEditToken')
beforeEditEvent.token = {
value: value,
label: label
}
beforeEditEvent.relatedTarget = token.get(0)
this.$element.trigger( beforeEditEvent )
if (!beforeEditEvent.token) return
value = beforeEditEvent.token.value
label = beforeEditEvent.token.label
token.find('.token-label').text(value)
var tokenWidth = token.outerWidth()
var $_input = this.$input.hasClass('tt-query') ? this.$input.parent() : this.$input
token.replaceWith( $_input )
this.preventCreateTokens = true
this.$input.val( value )
.select()
.data( 'edit', true )
.width( tokenWidth )
}
, unedit: function (focus) {
var $_input = this.$input.hasClass('tt-query') ? this.$input.parent() : this.$input
$_input.appendTo( this.$wrapper )
this.$input.data('edit', false)
this.update()
// Because moving the input element around in DOM
// will cause it to lose focus, we provide an option
// to re-focus the input after appending it to the wrapper
if (focus) {
var _self = this
setTimeout(function () {
_self.$input.focus()
}, 1)
}
}
, remove: function (e, direction) {
if (this.$input.is(document.activeElement) || this.disabled) return
var token = (e.type === 'click') ? $(e.target).closest('.token') : this.$wrapper.find('.token.active')
if (e.type !== 'click') {
if (!direction) var direction = 'prev'
this[direction]()
// Was this the first token?
if (direction === 'prev') var firstToken = token.first().prevAll('.token:first').length === 0
}
// Prepare events
var removeEvent = $.Event('removeToken')
removeEvent.token = this.getTokenData( token )
var changeEvent = $.Event('change')
changeEvent.initiator = 'tokenfield'
// Remove token from DOM
token.remove()
// Trigger events
this.$element.val( this.getTokensList() ).trigger( removeEvent ).trigger( changeEvent )
// Focus, when necessary:
// When there are no more tokens, or if this was the first token
// and it was removed with backspace or it was clicked on
if (!this.$wrapper.find('.token').length || e.type === 'click' || firstToken) this.$input.focus()
// Adjust input width
this.$input.css('width', this.options.minWidth + 'px')
this.update()
e.preventDefault()
e.stopPropagation()
}
, update: function (e) {
var value = this.$input.val()
if (this.$input.data('edit')) {
if (!value) {
value = this.$input.prop("placeholder")
}
if (value === this.$mirror.text()) return
this.$mirror.text(value)
var mirrorWidth = this.$mirror.width() + 10;
if ( mirrorWidth > this.$wrapper.width() ) {
return this.$input.width( this.$wrapper.width() )
}
this.$input.width( mirrorWidth )
}
else {
this.$input.css( 'width', this.options.minWidth + 'px' )
if (this.direction === 'right') {
return this.$input.width( this.$input.offset().left + this.$input.outerWidth() - this.$wrapper.offset().left - parseInt(this.$wrapper.css('padding-left'), 10) - 1 )
}
this.$input.width( this.$wrapper.offset().left + this.$wrapper.width() + parseInt(this.$wrapper.css('padding-left'), 10) - this.$input.offset().left + 1 )
}
}
, focusInput: function (e) {
if ($(e.target).closest('.token').length || $(e.target).closest('.token-input').length) return
// Focus only after the current call stack has cleared,
// otherwise has no effect.
// Reason: mousedown is too early - input will lose focus
// after mousedown. However, since the input may be moved
// in DOM, there may be no click or mouseup event triggered.
var _self = this
setTimeout(function() {
_self.$input.focus()
}, 0)
}
, search: function () {
if ( this.$input.data('ui-autocomplete') ) {
this.$input.autocomplete('search')
}
}
, disable: function () {
this.disabled = true;
this.$input.prop('disabled', true);
this.$element.prop('disabled', true);
this.$wrapper.addClass('disabled');
}
, enable: function () {
this.disabled = false;
this.$input.prop('disabled', false);
this.$element.prop('disabled', false);
this.$wrapper.removeClass('disabled');
}
}
/* TOKENFIELD PLUGIN DEFINITION
* ======================== */
var old = $.fn.tokenfield
$.fn.tokenfield = function (option, param) {
var value
, args = []
Array.prototype.push.apply( args, arguments );
var elements = this.each(function () {
var $this = $(this)
, data = $this.data('bs.tokenfield')
, options = typeof option == 'object' && option
if (typeof option === 'string' && data && data[option]) {
args.shift()
value = data[option].apply(data, args)
} else {
if (!data) $this.data('bs.tokenfield', (data = new Tokenfield(this, options)))
}
})
return typeof value !== 'undefined' ? value : elements;
}
$.fn.tokenfield.defaults = {
minWidth: 60,
minLength: 0,
allowDuplicates: false,
limit: 0,
autocomplete: {},
typeahead: {},
showAutocompleteOnFocus: false,
createTokensOnBlur: false,
delimiter: ',',
beautify: true
}
$.fn.tokenfield.Constructor = Tokenfield
/* TOKENFIELD NO CONFLICT
* ================== */
$.fn.tokenfield.noConflict = function () {
$.fn.tokenfield = old
return this
}
return Tokenfield;
}));
| bootstrap-tokenfield/bootstrap-tokenfield.js | /* ============================================================
* bootstrap-tokenfield.js v0.10.0
* ============================================================
*
* Copyright 2013 Sliptree
* ============================================================ */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
root.Tokenfield = factory(root.jQuery);
}
}(this, function ($) {
"use strict"; // jshint ;_;
/* TOKENFIELD PUBLIC CLASS DEFINITION
* ============================== */
var Tokenfield = function (element, options) {
var _self = this
this.$element = $(element)
this.direction = this.$element.css('direction') === 'ltr' ? 'left' : 'right'
// Extend options
this.options = $.extend({}, $.fn.tokenfield.defaults, { tokens: this.$element.val() }, options)
// Setup delimiters and trigger keys
this._delimiters = (typeof this.options.delimiter === 'string') ? [this.options.delimiter] : this.options.delimiter
this._triggerKeys = $.map(this._delimiters, function (delimiter) {
return delimiter.charCodeAt(0);
});
// Store original input width
var elRules = (typeof window.getMatchedCSSRules === 'function') ? window.getMatchedCSSRules( element ) : null
, elStyleWidth = element.style.width
, elCSSWidth
, elWidth = this.$element.width()
if (elRules) {
$.each( elRules, function (i, rule) {
if (rule.style.width) {
elCSSWidth = rule.style.width;
}
});
}
// Move original input out of the way
this.$element.css('position', 'absolute').css(this.direction, '-10000px').prop('tabindex', -1)
// Create a wrapper
this.$wrapper = $('<div class="tokenfield form-control" />')
if (this.$element.hasClass('input-lg')) this.$wrapper.addClass('input-lg')
if (this.$element.hasClass('input-sm')) this.$wrapper.addClass('input-sm')
if (this.direction === 'right') this.$wrapper.addClass('rtl')
// Create a new input
var id = this.$element.prop('id') || new Date().getTime() + '' + Math.floor((1 + Math.random()) * 100)
this.$input = $('<input type="text" class="token-input" autocomplete="off" />')
.appendTo( this.$wrapper )
.prop( 'placeholder', this.$element.prop('placeholder') )
.prop( 'id', id + '-tokenfield' )
// Re-route original input label to new input
var $label = $( 'label[for="' + this.$element.prop('id') + '"]' )
if ( $label.length ) {
$label.prop( 'for', this.$input.prop('id') )
}
// Set up a copy helper to handle copy & paste
this.$copyHelper = $('<input type="text" />').css('position', 'absolute').css(this.direction, '-10000px').prop('tabindex', -1).prependTo( this.$wrapper )
// Set wrapper width
if (elStyleWidth) {
this.$wrapper.css('width', elStyleWidth);
}
else if (elCSSWidth) {
this.$wrapper.css('width', elCSSWidth);
}
// If input is inside inline-form with no width set, set fixed width
else if (this.$element.parents('.form-inline').length) {
this.$wrapper.width( elWidth )
}
// Set tokenfield disabled, if original or fieldset input is disabled
if (this.$element.prop('disabled') || this.$element.parents('fieldset[disabled]').length) {
this.disable();
}
// Set up mirror for input auto-sizing
this.$mirror = $('<span style="position:absolute; top:-999px; left:0; white-space:pre;"/>');
this.$input.css('min-width', this.options.minWidth + 'px')
$.each([
'fontFamily',
'fontSize',
'fontWeight',
'fontStyle',
'letterSpacing',
'textTransform',
'wordSpacing',
'textIndent'
], function (i, val) {
_self.$mirror[0].style[val] = _self.$input.css(val);
});
this.$mirror.appendTo( 'body' )
// Insert tokenfield to HTML
this.$wrapper.insertBefore( this.$element )
this.$element.prependTo( this.$wrapper )
// Calculate inner input width
this.update()
// Create initial tokens, if any
this.setTokens(this.options.tokens, false, false)
// Start listening to events
this.listen()
// Initialize autocomplete, if necessary
if ( ! $.isEmptyObject( this.options.autocomplete ) ) {
var autocompleteOptions = $.extend({}, this.options.autocomplete, {
minLength: this.options.showAutocompleteOnFocus ? 0 : null,
position: { my: this.direction + " top", at: this.direction + " bottom", of: this.$wrapper }
})
this.$input.autocomplete( autocompleteOptions )
}
// Initialize typeahead, if necessary
if ( ! $.isEmptyObject( this.options.typeahead ) ) {
var typeaheadOptions = $.extend({}, this.options.typeahead, {})
this.$input.typeahead( typeaheadOptions )
this.typeahead = true
}
}
Tokenfield.prototype = {
constructor: Tokenfield
, createToken: function (attrs, triggerChange) {
if (typeof attrs === 'string') {
attrs = { value: attrs, label: attrs }
}
if (typeof triggerChange === 'undefined') {
triggerChange = true
}
var _self = this
, value = $.trim(attrs.value)
, label = attrs.label.length ? $.trim(attrs.label) : value
if (!value.length || !label.length || value.length < this.options.minLength) return
// Allow changing token data before creating it
var beforeCreateEvent = $.Event('beforeCreateToken')
beforeCreateEvent.token = {
value: value,
label: label
}
this.$element.trigger( beforeCreateEvent )
if (!beforeCreateEvent.token) return
value = beforeCreateEvent.token.value
label = beforeCreateEvent.token.label
// Check for duplicates
if (!this.options.allowDuplicates && $.grep(this.getTokens(), function (token) {
return token.value === value
}).length) {
// Allow listening to when duplicates get prevented
var duplicateEvent = $.Event('preventDuplicateToken')
duplicateEvent.token = {
value: value,
label: label
}
this.$element.trigger( duplicateEvent )
// Add duplicate warning class to existing token for 250ms
var duplicate = this.$wrapper.find( '.token[data-value="' + value + '"]' ).addClass('duplicate')
setTimeout(function() {
duplicate.removeClass('duplicate');
}, 250)
return false
}
var token = $('<div class="token" />')
.attr('data-value', value)
.append('<span class="token-label" />')
.append('<a href="#" class="close" tabindex="-1">×</a>')
// Insert token into HTML
if (this.$input.hasClass('tt-query')) {
this.$input.parent().before( token )
} else {
this.$input.before( token )
}
this.$input.css('width', this.options.minWidth + 'px')
var tokenLabel = token.find('.token-label')
, closeButton = token.find('.close')
// Determine maximum possible token label width
if (!this.maxTokenWidth) {
this.maxTokenWidth =
this.$wrapper.width() - closeButton.outerWidth() -
parseInt(closeButton.css('margin-left'), 10) -
parseInt(closeButton.css('margin-right'), 10) -
parseInt(token.css('border-left-width'), 10) -
parseInt(token.css('border-right-width'), 10) -
parseInt(token.css('padding-left'), 10) -
parseInt(token.css('padding-right'), 10)
parseInt(tokenLabel.css('border-left-width'), 10) -
parseInt(tokenLabel.css('border-right-width'), 10) -
parseInt(tokenLabel.css('padding-left'), 10) -
parseInt(tokenLabel.css('padding-right'), 10)
parseInt(tokenLabel.css('margin-left'), 10) -
parseInt(tokenLabel.css('margin-right'), 10)
}
tokenLabel
.text(label)
.css('max-width', this.maxTokenWidth)
// Listen to events
token
.on('mousedown', function (e) {
if (_self.disabled) return false;
_self.preventDeactivation = true
})
.on('click', function (e) {
if (_self.disabled) return false;
_self.preventDeactivation = false
if (e.ctrlKey || e.metaKey) {
e.preventDefault()
return _self.toggle( token )
}
_self.activate( token, e.shiftKey, e.shiftKey )
})
.on('dblclick', function (e) {
if (_self.disabled) return false;
_self.edit( token )
})
closeButton
.on('click', $.proxy(this.remove, this))
var afterCreateEvent = $.Event('afterCreateToken')
afterCreateEvent.token = beforeCreateEvent.token
afterCreateEvent.relatedTarget = token.get(0)
this.$element.trigger( afterCreateEvent )
var changeEvent = $.Event('change')
changeEvent.initiator = 'tokenfield'
if (triggerChange) {
this.$element.val( this.getTokensList() ).trigger( changeEvent )
}
this.update()
return this.$input.get(0)
}
, setTokens: function (tokens, add, triggerChange) {
if (!tokens) return
if (!add) this.$wrapper.find('.token').remove()
if (typeof triggerChange === 'undefined') {
triggerChange = true
}
if (typeof tokens === 'string') {
if (this._delimiters.length) {
tokens = tokens.split( new RegExp( '[' + this._delimiters.join('') + ']' ) )
} else {
tokens = [tokens];
}
}
var _self = this
$.each(tokens, function (i, token) {
_self.createToken(token, triggerChange)
})
return this.$element.get(0)
}
, getTokenData: function(token) {
var data = token.map(function() {
var $token = $(this);
return {
value: $token.attr('data-value') || $token.find('.token-label').text(),
label: $token.find('.token-label').text()
}
}).get();
if (data.length == 1) {
data = data[0];
}
return data;
}
, getTokens: function(active) {
var self = this
, tokens = []
, activeClass = active ? '.active' : '' // get active tokens only
this.$wrapper.find( '.token' + activeClass ).each( function() {
tokens.push( self.getTokenData( $(this) ) )
})
return tokens
}
, getTokensList: function(delimiter, beautify, active) {
delimiter = delimiter || this._delimiters[0]
beautify = ( typeof beautify !== 'undefined' && beautify !== null ) ? beautify : this.options.beautify
var separator = delimiter + ( beautify && delimiter !== ' ' ? ' ' : '')
return $.map( this.getTokens(active), function (token) {
return token.value
}).join(separator)
}
, getInput: function() {
return this.$input.val()
}
, listen: function () {
var _self = this
this.$element
.on('change', $.proxy(this.change, this))
this.$wrapper
.on('mousedown',$.proxy(this.focusInput, this))
this.$input
.on('focus', $.proxy(this.focus, this))
.on('blur', $.proxy(this.blur, this))
.on('paste', $.proxy(this.paste, this))
.on('keydown', $.proxy(this.keydown, this))
.on('keypress', $.proxy(this.keypress, this))
.on('keyup', $.proxy(this.keyup, this))
this.$copyHelper
.on('focus', $.proxy(this.focus, this))
.on('blur', $.proxy(this.blur, this))
.on('keydown', $.proxy(this.keydown, this))
.on('keyup', $.proxy(this.keyup, this))
// Secondary listeners for input width calculation
this.$input
.on('keypress', $.proxy(this.update, this))
.on('keyup', $.proxy(this.update, this))
this.$input
.on('autocompletecreate', function() {
// Set minimum autocomplete menu width
var $_menuElement = $(this).data('ui-autocomplete').menu.element
var minWidth = _self.$wrapper.outerWidth() -
parseInt( $_menuElement.css('border-left-width'), 10 ) -
parseInt( $_menuElement.css('border-right-width'), 10 )
$_menuElement.css( 'min-width', minWidth + 'px' )
})
.on('autocompleteselect', function (e, ui) {
if (_self.createToken( ui.item )) {
_self.$input.val('')
if (_self.$input.data( 'edit' )) {
_self.unedit(true)
}
}
return false
})
.on('typeahead:selected', function (e, datum, dataset) {
var valueKey = 'value'
// Get the actual valueKey for this dataset
$.each(_self.$input.data('ttView').datasets, function (i, set) {
if (set.name === dataset) {
valueKey = set.valueKey
}
})
// Create token
if (_self.createToken( datum[valueKey] )) {
_self.$input.typeahead('setQuery', '')
if (_self.$input.data( 'edit' )) {
_self.unedit(true)
}
}
})
.on('typeahead:autocompleted', function (e, datum, dataset) {
_self.createToken( _self.$input.val() )
_self.$input.typeahead('setQuery', '')
if (_self.$input.data( 'edit' )) {
_self.unedit(true)
}
})
// Listen to window resize
$(window).on('resize', $.proxy(this.update, this ))
}
, keydown: function (e) {
if (!this.focused) return
switch(e.keyCode) {
case 8: // backspace
if (!this.$input.is(document.activeElement)) break
this.lastInputValue = this.$input.val()
break
case 37: // left arrow
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length > 0) break
var prev = this.$input.hasClass('tt-query') ? this.$input.parent().prevAll('.token:first') : this.$input.prevAll('.token:first')
if (!prev.length) break
this.preventInputFocus = true
this.preventDeactivation = true
this.activate( prev )
e.preventDefault()
} else {
this.prev( e.shiftKey )
e.preventDefault()
}
break
case 38: // up arrow
if (!e.shiftKey) return
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length > 0) break
var prev = this.$input.hasClass('tt-query') ? this.$input.parent().prevAll('.token:last') : this.$input.prevAll('.token:last')
if (!prev.length) return
this.activate( prev )
}
var _self = this
this.firstActiveToken.nextAll('.token').each(function() {
_self.deactivate( $(this) )
})
this.activate( this.$wrapper.find('.token:first'), true, true )
e.preventDefault()
break
case 39: // right arrow
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length > 0) break
var next = this.$input.hasClass('tt-query') ? this.$input.parent().nextAll('.token:first') : this.$input.nextAll('.token:first')
if (!next.length) break
this.preventInputFocus = true
this.preventDeactivation = true
this.activate( next )
e.preventDefault()
} else {
this.next( e.shiftKey )
e.preventDefault()
}
break
case 40: // down arrow
if (!e.shiftKey) return
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length > 0) break
var next = this.$input.hasClass('tt-query') ? this.$input.parent().nextAll('.token:first') : this.$input.nextAll('.token:first')
if (!next.length) return
this.activate( next )
}
var _self = this
this.firstActiveToken.prevAll('.token').each(function() {
_self.deactivate( $(this) )
})
this.activate( this.$wrapper.find('.token:last'), true, true )
e.preventDefault()
break
case 65: // a (to handle ctrl + a)
if (this.$input.val().length > 0 || !(e.ctrlKey || e.metaKey)) break
this.activateAll()
e.preventDefault()
break
case 9: // tab
case 13: // enter
// We will handle creating tokens from autocomplete in autocomplete events
if (this.$input.data('ui-autocomplete') && this.$input.data('ui-autocomplete').menu.element.find("li:has(a.ui-state-focus)").length) break
// We will handle creating tokens from typeahead in typeahead events
if (this.$input.hasClass('tt-query') && this.$wrapper.find('.tt-is-under-cursor').length ) break
if (this.$input.hasClass('tt-query') && this.$wrapper.find('.tt-hint').val().length) break
// Create token
if (this.$input.is(document.activeElement) && this.$input.val().length || this.$input.data('edit')) {
return this.createTokensFromInput(e, this.$input.data('edit'));
}
// Edit token
if (e.keyCode === 13) {
if (!this.$copyHelper.is(document.activeElement) || this.$wrapper.find('.token.active').length !== 1) break
this.edit( this.$wrapper.find('.token.active') )
}
}
this.lastKeyDown = e.keyCode
}
, keypress: function(e) {
this.lastKeyPressCode = e.keyCode
this.lastKeyPressCharCode = e.charCode
// Comma
if ($.inArray( e.charCode, this._triggerKeys) !== -1 && this.$input.is(document.activeElement)) {
if (this.$input.val()) {
this.createTokensFromInput(e)
}
return false;
}
}
, keyup: function (e) {
this.preventInputFocus = false
if (!this.focused) return
switch(e.keyCode) {
case 8: // backspace
if (this.$input.is(document.activeElement)) {
if (this.$input.val().length || this.lastInputValue.length && this.lastKeyDown === 8) break
this.preventDeactivation = true
var prev = this.$input.hasClass('tt-query') ? this.$input.parent().prevAll('.token:first') : this.$input.prevAll('.token:first')
if (!prev.length) break
this.activate( prev )
} else {
this.remove(e)
}
break
case 46: // delete
this.remove(e, 'next')
break
}
this.lastKeyUp = e.keyCode
}
, focus: function (e) {
this.focused = true
this.$wrapper.addClass('focus')
if (this.$input.is(document.activeElement)) {
this.$wrapper.find('.active').removeClass('active')
this.firstActiveToken = null
if (this.options.showAutocompleteOnFocus) {
this.search()
}
}
}
, blur: function (e) {
this.focused = false
this.$wrapper.removeClass('focus')
if (!this.preventDeactivation && !this.$element.is(document.activeElement)) {
this.$wrapper.find('.active').removeClass('active')
this.firstActiveToken = null
}
if (!this.preventCreateTokens && (this.$input.data('edit') && !this.$input.is(document.activeElement) || this.options.createTokensOnBlur )) {
this.createTokensFromInput(e)
}
this.preventDeactivation = false
this.preventCreateTokens = false
}
, paste: function (e) {
var _self = this
// Add tokens to existing ones
setTimeout(function () {
_self.createTokensFromInput(e)
}, 1)
}
, change: function (e) {
if ( e.initiator === 'tokenfield' ) return // Prevent loops
this.setTokens( this.$element.val() )
}
, createTokensFromInput: function (e, focus) {
if (this.$input.val().length < this.options.minLength)
return // No input, simply return
var tokensBefore = this.getTokensList()
this.setTokens( this.$input.val(), true )
if (tokensBefore == this.getTokensList() && this.$input.val().length)
return false // No tokens were added, do nothing (prevent form submit)
if (this.$input.hasClass('tt-query')) {
// Typeahead acts weird when simply setting input value to empty,
// so we set the query to empty instead
this.$input.typeahead('setQuery', '')
} else {
this.$input.val('')
}
if (this.$input.data( 'edit' )) {
this.unedit(focus)
}
return false // Prevent form being submitted
}
, next: function (add) {
if (add) {
var firstActive = this.$wrapper.find('.active:first')
, deactivate = firstActive && this.firstActiveToken ? firstActive.index() < this.firstActiveToken.index() : false
if (deactivate) return this.deactivate( firstActive )
}
var active = this.$wrapper.find('.active:last')
, next = active.nextAll('.token:first')
if (!next.length) {
this.$input.focus()
return
}
this.activate(next, add)
}
, prev: function (add) {
if (add) {
var lastActive = this.$wrapper.find('.active:last')
, deactivate = lastActive && this.firstActiveToken ? lastActive.index() > this.firstActiveToken.index() : false
if (deactivate) return this.deactivate( lastActive )
}
var active = this.$wrapper.find('.active:first')
, prev = active.prevAll('.token:first')
if (!prev.length) {
prev = this.$wrapper.find('.token:first')
}
if (!prev.length && !add) {
this.$input.focus()
return
}
this.activate( prev, add )
}
, activate: function (token, add, multi, remember) {
if (!token) return
if (this.$wrapper.find('.token.active').length === this.$wrapper.find('.token').length) return
if (typeof remember === 'undefined') var remember = true
if (multi) var add = true
this.$copyHelper.focus()
if (!add) {
this.$wrapper.find('.active').removeClass('active')
if (remember) {
this.firstActiveToken = token
} else {
delete this.firstActiveToken
}
}
if (multi && this.firstActiveToken) {
// Determine first active token and the current tokens indicies
// Account for the 1 hidden textarea by subtracting 1 from both
var i = this.firstActiveToken.index() - 2
, a = token.index() - 2
, _self = this
this.$wrapper.find('.token').slice( Math.min(i, a) + 1, Math.max(i, a) ).each( function() {
_self.activate( $(this), true )
})
}
token.addClass('active')
this.$copyHelper.val( this.getTokensList( null, null, true ) ).select()
}
, activateAll: function() {
var _self = this
this.$wrapper.find('.token').each( function (i) {
_self.activate($(this), i !== 0, false, false)
})
}
, deactivate: function(token) {
if (!token) return
token.removeClass('active')
this.$copyHelper.val( this.getTokensList( null, null, true ) ).select()
}
, toggle: function(token) {
if (!token) return
token.toggleClass('active')
this.$copyHelper.val( this.getTokensList( null, null, true ) ).select()
}
, edit: function (token) {
if (!token) return
var value = token.data('value')
, label = token.find('.token-label').text()
// Allow changing input value before editing
var beforeEditEvent = $.Event('beforeEditToken')
beforeEditEvent.token = {
value: value,
label: label
}
beforeEditEvent.relatedTarget = token.get(0)
this.$element.trigger( beforeEditEvent )
if (!beforeEditEvent.token) return
value = beforeEditEvent.token.value
label = beforeEditEvent.token.label
token.find('.token-label').text(value)
var tokenWidth = token.outerWidth()
var $_input = this.$input.hasClass('tt-query') ? this.$input.parent() : this.$input
token.replaceWith( $_input )
this.preventCreateTokens = true
this.$input.val( value )
.select()
.data( 'edit', true )
.width( tokenWidth )
}
, unedit: function (focus) {
var $_input = this.$input.hasClass('tt-query') ? this.$input.parent() : this.$input
$_input.appendTo( this.$wrapper )
this.$input.data('edit', false)
this.update()
// Because moving the input element around in DOM
// will cause it to lose focus, we provide an option
// to re-focus the input after appending it to the wrapper
if (focus) {
var _self = this
setTimeout(function () {
_self.$input.focus()
}, 1)
}
}
, remove: function (e, direction) {
if (this.$input.is(document.activeElement) || this.disabled) return
var token = (e.type === 'click') ? $(e.target).closest('.token') : this.$wrapper.find('.token.active')
if (e.type !== 'click') {
if (!direction) var direction = 'prev'
this[direction]()
// Was this the first token?
if (direction === 'prev') var firstToken = token.first().prevAll('.token:first').length === 0
}
// Prepare events
var removeEvent = $.Event('removeToken')
removeEvent.token = this.getTokenData( token )
var changeEvent = $.Event('change')
changeEvent.initiator = 'tokenfield'
// Remove token from DOM
token.remove()
// Trigger events
this.$element.val( this.getTokensList() ).trigger( removeEvent ).trigger( changeEvent )
// Focus, when necessary:
// When there are no more tokens, or if this was the first token
// and it was removed with backspace or it was clicked on
if (!this.$wrapper.find('.token').length || e.type === 'click' || firstToken) this.$input.focus()
// Adjust input width
this.$input.css('width', this.options.minWidth + 'px')
this.update()
e.preventDefault()
e.stopPropagation()
}
, update: function (e) {
var value = this.$input.val()
if (this.$input.data('edit')) {
if (!value) {
value = this.$input.prop("placeholder")
}
if (value === this.$mirror.text()) return
this.$mirror.text(value)
var mirrorWidth = this.$mirror.width() + 10;
if ( mirrorWidth > this.$wrapper.width() ) {
return this.$input.width( this.$wrapper.width() )
}
this.$input.width( mirrorWidth )
}
else {
this.$input.css( 'width', this.options.minWidth + 'px' )
if (this.direction === 'right') {
return this.$input.width( this.$input.offset().left + this.$input.outerWidth() - this.$wrapper.offset().left - parseInt(this.$wrapper.css('padding-left'), 10) - 1 )
}
this.$input.width( this.$wrapper.offset().left + this.$wrapper.width() + parseInt(this.$wrapper.css('padding-left'), 10) - this.$input.offset().left + 1 )
}
}
, focusInput: function (e) {
if ($(e.target).closest('.token').length || $(e.target).closest('.token-input').length) return
// Focus only after the current call stack has cleared,
// otherwise has no effect.
// Reason: mousedown is too early - input will lose focus
// after mousedown. However, since the input may be moved
// in DOM, there may be no click or mouseup event triggered.
var _self = this
setTimeout(function() {
_self.$input.focus()
}, 0)
}
, search: function () {
if ( this.$input.data('ui-autocomplete') ) {
this.$input.autocomplete('search')
}
}
, disable: function () {
this.disabled = true;
this.$input.prop('disabled', true);
this.$element.prop('disabled', true);
this.$wrapper.addClass('disabled');
}
, enable: function () {
this.disabled = false;
this.$input.prop('disabled', false);
this.$element.prop('disabled', false);
this.$wrapper.removeClass('disabled');
}
}
/* TOKENFIELD PLUGIN DEFINITION
* ======================== */
var old = $.fn.tokenfield
$.fn.tokenfield = function (option, param) {
var value
, args = []
Array.prototype.push.apply( args, arguments );
var elements = this.each(function () {
var $this = $(this)
, data = $this.data('bs.tokenfield')
, options = typeof option == 'object' && option
if (typeof option === 'string' && data && data[option]) {
args.shift()
value = data[option].apply(data, args)
} else {
if (!data) $this.data('bs.tokenfield', (data = new Tokenfield(this, options)))
}
})
return typeof value !== 'undefined' ? value : elements;
}
$.fn.tokenfield.defaults = {
minWidth: 60,
minLength: 0,
allowDuplicates: false,
autocomplete: {},
typeahead: {},
showAutocompleteOnFocus: false,
createTokensOnBlur: false,
delimiter: ',',
beautify: true
}
$.fn.tokenfield.Constructor = Tokenfield
/* TOKENFIELD NO CONFLICT
* ================== */
$.fn.tokenfield.noConflict = function () {
$.fn.tokenfield = old
return this
}
return Tokenfield;
}));
| Add limit option. Closes #52
| bootstrap-tokenfield/bootstrap-tokenfield.js | Add limit option. Closes #52 | <ide><path>ootstrap-tokenfield/bootstrap-tokenfield.js
<ide> , label = attrs.label.length ? $.trim(attrs.label) : value
<ide>
<ide> if (!value.length || !label.length || value.length < this.options.minLength) return
<add>
<add> if (this.options.limit && this.getTokens().length >= this.options.limit) return
<ide>
<ide> // Allow changing token data before creating it
<ide> var beforeCreateEvent = $.Event('beforeCreateToken')
<ide> minWidth: 60,
<ide> minLength: 0,
<ide> allowDuplicates: false,
<add> limit: 0,
<ide> autocomplete: {},
<ide> typeahead: {},
<ide> showAutocompleteOnFocus: false, |
|
JavaScript | mit | e04e94a25d8fb2633bf6fd9f12044bf5df013c0f | 0 | medea/medea,medea/medea | var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var async = require('async');
var crc32 = require('buffer-crc32');
var constants = require('./constants');
var utils = require('./utils');
var DataFile = require('./data_file');
var DataFileParser = require('./data_file_parser');
var KeyDirEntry = require('./keydir_entry');
var headerOffsets = constants.headerOffsets;
var sizes = constants.sizes;
var Compactor = module.exports = function (db) {
EventEmitter.call(this);
this.db = db;
this.activeMerge = null;
this.delKeyDir = null;
this.bytesToBeWritten = 0;
this.gettingNewActiveFile = false;
}
require('util').inherits(Compactor, EventEmitter);
/*
* 1. Get readable files.
* 2. Match data file entries with keydir entries.
* 3. If older than keydir version or if tombstoned, delete.
* 4. Write new key to file system, update keydir.
* 5. Delete old files.
*/
Compactor.prototype.compact = function (cb) {
var self = this;
var fileReferences = Object.keys(this.db.fileReferences).map(Number);
var files = this.db.readableFiles
.filter(function (file) {
return fileReferences.indexOf(file.timestamp) === -1 &&
file.timestamp !== self.db.active.timestamp;
})
.sort(function(a, b) {
if (a.timestamp < b.timestamp) {
return 1;
} else if (a.timestamp > b.timestamp) {
return - 1;
}
return 0;
});
if (!files.length) {
return cb();
}
DataFile.create(this.db.dirname, function (err, file) {
if (err) {
return cb(err);
}
self.activeMerge = file;
self.db.readableFiles.push(self.activeMerge)
self._compactFiles(files, function(err) {
if (err) {
cb(err);
return;
}
self.db.sync(self.activeMerge, function(err) {
if (err) {
if (cb) cb(err);
return;
}
if (cb) cb();
});
});
});
}
Compactor.prototype._handleEntries = function (entries, cb) {
var self = this;
async.forEachSeries(
entries,
function (entry, done) {
self._handleEntry(entry, done);
},
cb
);
}
Compactor.prototype._handleEntry = function (entry, cb) {
var self = this;
var outOfDate = self._outOfDate([self.db.keydir, self.delKeyDir], false, entry);
if (outOfDate) {
// Use setImmediate to avoid "Maximum call stack size exceeded" if we're running
// compaction on multiple outdated entries
return setImmediate(cb);
}
if (!utils.isTombstone(entry.value)) {
var newEntry = new KeyDirEntry();
newEntry.valuePosition = entry.valuePosition;
newEntry.valueSize = entry.valueSize;
newEntry.fileId = entry.fileId;
newEntry.timestamp = entry.timestamp;
self.delKeyDir[entry.key] = newEntry;
delete self.db.keydir[entry.key];
self._innerMergeWrite(entry, cb);
} else {
if (self.delKeyDir[entry.key]) {
delete self.delKeyDir[entry.key];
}
self._innerMergeWrite(entry, cb);
}
};
Compactor.prototype._compactFiles = function (files, cb) {
var self = this;
async.forEachSeries(
files,
function (file, done) {
self._compactFile(file, done);
},
cb
);
}
Compactor.prototype._compactFile = function(file, cb) {
var self = this;
var parser = new DataFileParser(file);
var entries = [];
this.delKeyDir = [];
parser.on('error', function(err) {
cb(err);
});
parser.on('entry', function(entry) {
entries.push(entry);
});
parser.on('end', function() {
self._handleEntries(entries, function (err) {
if (err) {
return cb(err);
}
var index = self.db.readableFiles.indexOf(file);
self.db.readableFiles.splice(index, 1)
fs.unlink(file.filename, function (err) {
if (err) {
return cb(err);
}
fs.unlink(file.filename.replace('.data', '.hint'), cb);
});
});
});
parser.parse(cb);
};
Compactor.prototype._outOfDate = function(keydirs, everFound, fileEntry) {
var self = this;
if (!keydirs.length) {
return (!everFound);
}
var keydir = keydirs[0];
var keyDirEntry = keydir[fileEntry.key];
if (!keyDirEntry) {
keydirs.shift();
return self._outOfDate(keydirs, everFound, fileEntry);
}
if (keyDirEntry.timestamp === fileEntry.timestamp) {
if (keyDirEntry.fileId > fileEntry.fileId) {
return true;
} else if (keyDirEntry.fileId === fileEntry.fileId) {
if (keyDirEntry.offset > fileEntry.offset) {
return true;
} else {
keydirs.shift();
return self._outOfDate(keydirs, true, fileEntry);
}
} else {
keydirs.shift();
return self._outOfDate(keydirs, true, fileEntry);
}
} else if (keyDirEntry.timestamp < fileEntry.timestamp) {
keydirs.shift();
return self._outOfDate(keydirs, true, fileEntry);
}
return true;
};
Compactor.prototype._getActiveMerge = function (bytesToBeWritten, cb) {
var self = this;
if (this.bytesToBeWritten + bytesToBeWritten < this.db.maxFileSize) {
this.bytesToBeWritten += bytesToBeWritten;
cb(null, this.activeMerge);
} else {
this.once('newActiveMergeFile', function () {
self._getActiveMerge(bytesToBeWritten, cb);
});
if (!this.gettingNewActiveFile) {
this.gettingNewActiveFile = true;
self._wrapWriteFile(function () {
self.gettingNewActiveFile = false;
self.emit('newActiveMergeFile');
});
}
}
}
Compactor.prototype._wrapWriteFile = function(cb) {
var self = this;
var oldFile = this.activeMerge;
DataFile.create(this.db.dirname, function (err, file) {
if (err) {
return cb(err);
}
self.activeMerge = file;
self.db.readableFiles.push(file);
self.bytesToBeWritten = 0;
oldFile.closeForWriting(cb);
});
};
Compactor.prototype._innerMergeWrite = function(dataEntry, cb) {
var self = this;
var buf = dataEntry.buffer;
this._getActiveMerge(buf.length, function (err, file) {
/**
* [crc][timestamp][keysz][valuesz][key][value]
*/
var key = dataEntry.key;
var value = dataEntry.value;
var lineBuffer = dataEntry.buffer;
file.write(lineBuffer, function(err) {
if (err) {
if (cb) cb(err);
return;
}
var oldOffset = file.offset;
file.offset += lineBuffer.length;
var totalSz = key.length + value.length + sizes.header;
var hintBufs = new Buffer(sizes.timestamp + sizes.keysize + sizes.offset + sizes.totalsize + key.length)
//timestamp
lineBuffer.copy(hintBufs, 0, headerOffsets.timestamp, headerOffsets.timestamp + sizes.timestamp);
//keysize
lineBuffer.copy(hintBufs, sizes.timestamp, headerOffsets.keysize, headerOffsets.keysize + sizes.keysize);
//total size
hintBufs.writeUInt32BE(totalSz, sizes.timestamp + sizes.keysize);
//offset
hintBufs.writeDoubleBE(oldOffset, sizes.timestamp + sizes.keysize + sizes.totalsize);
//key
key.copy(hintBufs, sizes.timestamp + sizes.keysize + sizes.totalsize + sizes.offset);
file.writeHintFile(hintBufs, function(err) {
if (err) {
if (cb) cb(err);
return;
}
file.hintCrc = crc32(hintBufs, file.hintCrc);
file.hintOffset += hintBufs.length;
var entry = new KeyDirEntry();
entry.fileId = file.timestamp;
entry.valueSize = value.length;
entry.valuePosition = oldOffset + sizes.header + key.length;
entry.timestamp = dataEntry.timestamp;
fs.fsync(file.fd, function(err) {
if (err) {
if (cb) return cb(err);
}
self.db.keydir[key] = entry;
if (cb) cb();
});
});
});
});
}; | compactor.js | var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var async = require('async');
var crc32 = require('buffer-crc32');
var constants = require('./constants');
var utils = require('./utils');
var DataFile = require('./data_file');
var DataFileParser = require('./data_file_parser');
var KeyDirEntry = require('./keydir_entry');
var headerOffsets = constants.headerOffsets;
var sizes = constants.sizes;
var Compactor = module.exports = function (db) {
EventEmitter.call(this);
this.db = db;
this.activeMerge = null;
this.delKeyDir = null;
this.bytesToBeWritten = 0;
this.gettingNewActiveFile = false;
}
require('util').inherits(Compactor, EventEmitter);
/*
* 1. Get readable files.
* 2. Match data file entries with keydir entries.
* 3. If older than keydir version or if tombstoned, delete.
* 4. Write new key to file system, update keydir.
* 5. Delete old files.
*/
Compactor.prototype.compact = function (cb) {
var self = this;
var fileReferences = Object.keys(this.db.fileReferences).map(Number);
var files = this.db.readableFiles
.filter(function (file) {
return fileReferences.indexOf(file.timestamp) === -1 &&
file.timestamp !== self.db.active.timestamp;
})
.sort(function(a, b) {
if (a.timestamp < b.timestamp) {
return 1;
} else if (a.timestamp > b.timestamp) {
return - 1;
}
return 0;
});
if (!files.length) {
return cb();
}
DataFile.create(this.db.dirname, function (err, file) {
if (err) {
return cb(err);
}
self.activeMerge = file;
self.db.readableFiles.push(self.activeMerge)
self._compactFiles(files, function(err) {
if (err) {
cb(err);
return;
}
var dataFileNames = files.map(function(f) {
return f.filename;
});
var hintFileNames = files.map(function(f) {
return f.filename.replace('.data', '.hint');
});
self.db.sync(self.activeMerge, function(err) {
if (err) {
if (cb) cb(err);
return;
}
self._unlink(dataFileNames.concat(hintFileNames), function(err) {
if (err) {
if (cb) cb(err);
return;
}
if (cb) cb();
});
});
});
});
}
Compactor.prototype._unlink = function(filenames, cb) {
async.forEach(filenames, fs.unlink, cb);
}
Compactor.prototype._handleEntries = function (entries, cb) {
var self = this;
async.forEachSeries(
entries,
function (entry, done) {
self._handleEntry(entry, done);
},
cb
);
}
Compactor.prototype._handleEntry = function (entry, cb) {
var self = this;
var outOfDate = self._outOfDate([self.db.keydir, self.delKeyDir], false, entry);
if (outOfDate) {
// Use setImmediate to avoid "Maximum call stack size exceeded" if we're running
// compaction on multiple outdated entries
return setImmediate(cb);
}
if (!utils.isTombstone(entry.value)) {
var newEntry = new KeyDirEntry();
newEntry.valuePosition = entry.valuePosition;
newEntry.valueSize = entry.valueSize;
newEntry.fileId = entry.fileId;
newEntry.timestamp = entry.timestamp;
self.delKeyDir[entry.key] = newEntry;
delete self.db.keydir[entry.key];
self._innerMergeWrite(entry, cb);
} else {
if (self.delKeyDir[entry.key]) {
delete self.delKeyDir[entry.key];
}
self._innerMergeWrite(entry, cb);
}
};
Compactor.prototype._compactFiles = function (files, cb) {
var self = this;
async.forEachSeries(
files,
function (file, done) {
self._compactFile(file, done);
},
cb
);
}
Compactor.prototype._compactFile = function(file, cb) {
var self = this;
var parser = new DataFileParser(file);
var entries = [];
this.delKeyDir = [];
parser.on('error', function(err) {
cb(err);
});
parser.on('entry', function(entry) {
entries.push(entry);
});
parser.on('end', function() {
self._handleEntries(entries, function (err) {
if (err) {
return cb(err);
}
var index = self.db.readableFiles.indexOf(file);
self.db.readableFiles.splice(index, 1)
cb(null)
});
});
parser.parse(cb);
};
Compactor.prototype._outOfDate = function(keydirs, everFound, fileEntry) {
var self = this;
if (!keydirs.length) {
return (!everFound);
}
var keydir = keydirs[0];
var keyDirEntry = keydir[fileEntry.key];
if (!keyDirEntry) {
keydirs.shift();
return self._outOfDate(keydirs, everFound, fileEntry);
}
if (keyDirEntry.timestamp === fileEntry.timestamp) {
if (keyDirEntry.fileId > fileEntry.fileId) {
return true;
} else if (keyDirEntry.fileId === fileEntry.fileId) {
if (keyDirEntry.offset > fileEntry.offset) {
return true;
} else {
keydirs.shift();
return self._outOfDate(keydirs, true, fileEntry);
}
} else {
keydirs.shift();
return self._outOfDate(keydirs, true, fileEntry);
}
} else if (keyDirEntry.timestamp < fileEntry.timestamp) {
keydirs.shift();
return self._outOfDate(keydirs, true, fileEntry);
}
return true;
};
Compactor.prototype._getActiveMerge = function (bytesToBeWritten, cb) {
var self = this;
if (this.bytesToBeWritten + bytesToBeWritten < this.db.maxFileSize) {
this.bytesToBeWritten += bytesToBeWritten;
cb(null, this.activeMerge);
} else {
this.once('newActiveMergeFile', function () {
self._getActiveMerge(bytesToBeWritten, cb);
});
if (!this.gettingNewActiveFile) {
this.gettingNewActiveFile = true;
self._wrapWriteFile(function () {
self.gettingNewActiveFile = false;
self.emit('newActiveMergeFile');
});
}
}
}
Compactor.prototype._wrapWriteFile = function(cb) {
var self = this;
var oldFile = this.activeMerge;
DataFile.create(this.db.dirname, function (err, file) {
if (err) {
return cb(err);
}
self.activeMerge = file;
self.db.readableFiles.push(file);
self.bytesToBeWritten = 0;
oldFile.closeForWriting(cb);
});
};
Compactor.prototype._innerMergeWrite = function(dataEntry, cb) {
var self = this;
var buf = dataEntry.buffer;
this._getActiveMerge(buf.length, function (err, file) {
/**
* [crc][timestamp][keysz][valuesz][key][value]
*/
var key = dataEntry.key;
var value = dataEntry.value;
var lineBuffer = dataEntry.buffer;
file.write(lineBuffer, function(err) {
if (err) {
if (cb) cb(err);
return;
}
var oldOffset = file.offset;
file.offset += lineBuffer.length;
var totalSz = key.length + value.length + sizes.header;
var hintBufs = new Buffer(sizes.timestamp + sizes.keysize + sizes.offset + sizes.totalsize + key.length)
//timestamp
lineBuffer.copy(hintBufs, 0, headerOffsets.timestamp, headerOffsets.timestamp + sizes.timestamp);
//keysize
lineBuffer.copy(hintBufs, sizes.timestamp, headerOffsets.keysize, headerOffsets.keysize + sizes.keysize);
//total size
hintBufs.writeUInt32BE(totalSz, sizes.timestamp + sizes.keysize);
//offset
hintBufs.writeDoubleBE(oldOffset, sizes.timestamp + sizes.keysize + sizes.totalsize);
//key
key.copy(hintBufs, sizes.timestamp + sizes.keysize + sizes.totalsize + sizes.offset);
file.writeHintFile(hintBufs, function(err) {
if (err) {
if (cb) cb(err);
return;
}
file.hintCrc = crc32(hintBufs, file.hintCrc);
file.hintOffset += hintBufs.length;
var entry = new KeyDirEntry();
entry.fileId = file.timestamp;
entry.valueSize = value.length;
entry.valuePosition = oldOffset + sizes.header + key.length;
entry.timestamp = dataEntry.timestamp;
fs.fsync(file.fd, function(err) {
if (err) {
if (cb) return cb(err);
}
self.db.keydir[key] = entry;
if (cb) cb();
});
});
});
});
}; | compactor: unlink a file directly when it's been compacted
| compactor.js | compactor: unlink a file directly when it's been compacted | <ide><path>ompactor.js
<ide> return;
<ide> }
<ide>
<del> var dataFileNames = files.map(function(f) {
<del> return f.filename;
<del> });
<del>
<del> var hintFileNames = files.map(function(f) {
<del> return f.filename.replace('.data', '.hint');
<del> });
<del>
<ide> self.db.sync(self.activeMerge, function(err) {
<ide> if (err) {
<ide> if (cb) cb(err);
<ide> return;
<ide> }
<ide>
<del> self._unlink(dataFileNames.concat(hintFileNames), function(err) {
<del> if (err) {
<del> if (cb) cb(err);
<del> return;
<del> }
<del>
<del> if (cb) cb();
<del> });
<add> if (cb) cb();
<ide> });
<ide> });
<ide> });
<del>}
<del>
<del>Compactor.prototype._unlink = function(filenames, cb) {
<del> async.forEach(filenames, fs.unlink, cb);
<ide> }
<ide>
<ide> Compactor.prototype._handleEntries = function (entries, cb) {
<ide>
<ide> var index = self.db.readableFiles.indexOf(file);
<ide> self.db.readableFiles.splice(index, 1)
<del> cb(null)
<add>
<add> fs.unlink(file.filename, function (err) {
<add> if (err) {
<add> return cb(err);
<add> }
<add>
<add> fs.unlink(file.filename.replace('.data', '.hint'), cb);
<add> });
<ide> });
<ide> });
<ide> |
|
Java | apache-2.0 | 27b4a41609fa9903dd9af8e8c9cf350918033662 | 0 | alphafoobar/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,semonte/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,robovm/robovm-studio,izonder/intellij-community,kdwink/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,FHannes/intellij-community,diorcety/intellij-community,allotria/intellij-community,ahb0327/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ibinti/intellij-community,hurricup/intellij-community,signed/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,slisson/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,samthor/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,blademainer/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,allotria/intellij-community,holmes/intellij-community,semonte/intellij-community,retomerz/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,semonte/intellij-community,fitermay/intellij-community,signed/intellij-community,caot/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,ibinti/intellij-community,samthor/intellij-community,caot/intellij-community,vladmm/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,hurricup/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,supersven/intellij-community,allotria/intellij-community,apixandru/intellij-community,signed/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,samthor/intellij-community,slisson/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,holmes/intellij-community,diorcety/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,samthor/intellij-community,semonte/intellij-community,kool79/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,fitermay/intellij-community,ryano144/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,caot/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,holmes/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,samthor/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ryano144/intellij-community,supersven/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,allotria/intellij-community,ibinti/intellij-community,retomerz/intellij-community,diorcety/intellij-community,vladmm/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,xfournet/intellij-community,adedayo/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,holmes/intellij-community,slisson/intellij-community,retomerz/intellij-community,diorcety/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,allotria/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,signed/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,dslomov/intellij-community,diorcety/intellij-community,ibinti/intellij-community,robovm/robovm-studio,semonte/intellij-community,signed/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,kool79/intellij-community,apixandru/intellij-community,da1z/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,samthor/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,samthor/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,kool79/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,dslomov/intellij-community,signed/intellij-community,kool79/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,semonte/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,amith01994/intellij-community,vladmm/intellij-community,holmes/intellij-community,fnouama/intellij-community,allotria/intellij-community,ryano144/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,signed/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,holmes/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,youdonghai/intellij-community,izonder/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,fitermay/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,jagguli/intellij-community,vladmm/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,caot/intellij-community,blademainer/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,petteyg/intellij-community,adedayo/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,fitermay/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,signed/intellij-community,allotria/intellij-community,retomerz/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,supersven/intellij-community,adedayo/intellij-community,da1z/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,semonte/intellij-community,diorcety/intellij-community,kool79/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,nicolargo/intellij-community,supersven/intellij-community,da1z/intellij-community,holmes/intellij-community,apixandru/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,signed/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,da1z/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,caot/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,hurricup/intellij-community,supersven/intellij-community,wreckJ/intellij-community,supersven/intellij-community,fnouama/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,amith01994/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,da1z/intellij-community,orekyuu/intellij-community,kool79/intellij-community,FHannes/intellij-community,holmes/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,slisson/intellij-community,clumsy/intellij-community,FHannes/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,da1z/intellij-community,caot/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,ibinti/intellij-community,ryano144/intellij-community,kool79/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,kool79/intellij-community,supersven/intellij-community,petteyg/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,izonder/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,tmpgit/intellij-community,allotria/intellij-community,petteyg/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,FHannes/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,ibinti/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,signed/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,slisson/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,asedunov/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ryano144/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,hurricup/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,signed/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,caot/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,samthor/intellij-community,akosyakov/intellij-community,slisson/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,allotria/intellij-community,signed/intellij-community,izonder/intellij-community,jagguli/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,blademainer/intellij-community,retomerz/intellij-community,semonte/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,ibinti/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ryano144/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,semonte/intellij-community,clumsy/intellij-community,kool79/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui.laf.darcula.ui;
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.ui.Gray;
import javax.swing.border.Border;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.UIResource;
import javax.swing.text.JTextComponent;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaTextBorder implements Border, UIResource {
@Override
public Insets getBorderInsets(Component c) {
if (DarculaTextFieldUI.isSearchField(c)) {
return new InsetsUIResource(5, 4 + 16 + 3, 5, 7 + 16);
} else {
return new InsetsUIResource(5, 7, 5, 7);
}
}
@Override
public boolean isBorderOpaque() {
return false;
}
@Override
public void paintBorder(Component c, Graphics g2, int x, int y, int width, int height) {
if (DarculaTextFieldUI.isSearchField(c)) return;
Graphics2D g = ((Graphics2D)g2);
final GraphicsConfig config = new GraphicsConfig(g);
g.translate(x, y);
if (c.hasFocus()) {
DarculaUIUtil.paintFocusRing(g, 2, 2, width-4, height-4);
} else {
boolean editable = !(c instanceof JTextComponent) || (((JTextComponent)c).isEditable());
g.setColor(c.isEnabled() && editable ? Gray._100 : new Color(0x535353));
g.drawRect(1, 1, width - 2, height - 2);
}
g.translate(-x, -y);
config.restore();
}
}
| platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui.laf.darcula.ui;
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.ui.Gray;
import javax.swing.border.Border;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.UIResource;
import javax.swing.text.JTextComponent;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaTextBorder implements Border, UIResource {
@Override
public Insets getBorderInsets(Component c) {
if (DarculaTextFieldUI.isSearchField(c)) {
return new InsetsUIResource(5, 7 + 16 + 3, 5, 7 + 16);
} else {
return new InsetsUIResource(5, 7, 5, 7);
}
}
@Override
public boolean isBorderOpaque() {
return false;
}
@Override
public void paintBorder(Component c, Graphics g2, int x, int y, int width, int height) {
if (DarculaTextFieldUI.isSearchField(c)) return;
Graphics2D g = ((Graphics2D)g2);
final GraphicsConfig config = new GraphicsConfig(g);
g.translate(x, y);
if (c.hasFocus()) {
DarculaUIUtil.paintFocusRing(g, 2, 2, width-4, height-4);
} else {
boolean editable = !(c instanceof JTextComponent) || (((JTextComponent)c).isEditable());
g.setColor(c.isEnabled() && editable ? Gray._100 : new Color(0x535353));
g.drawRect(1, 1, width - 2, height - 2);
}
g.translate(-x, -y);
config.restore();
}
}
| decrease space between icon and text
| platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java | decrease space between icon and text | <ide><path>latform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java
<ide> @Override
<ide> public Insets getBorderInsets(Component c) {
<ide> if (DarculaTextFieldUI.isSearchField(c)) {
<del> return new InsetsUIResource(5, 7 + 16 + 3, 5, 7 + 16);
<add> return new InsetsUIResource(5, 4 + 16 + 3, 5, 7 + 16);
<ide> } else {
<ide> return new InsetsUIResource(5, 7, 5, 7);
<ide> } |
|
Java | bsd-3-clause | 67639b3c22a30ba65cb14a2d5bb296b373ca4cfe | 0 | motech/MOTECH-Mobile,motech/MOTECH-Mobile | package org.motechproject.mobile.web.ivr.intellivr;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.motechproject.omp.manager.intellivr.AutoCreate;
import org.motechproject.omp.manager.intellivr.ErrorCodeType;
import org.motechproject.omp.manager.intellivr.ResponseType;
import org.motechproject.omp.manager.intellivr.StatusType;
import org.motechproject.omp.manager.intellivr.RequestType.Vxml;
public class IntellIVRController extends AbstractController implements ResourceLoaderAware {
private ResourceLoader resourceLoader;
private DocumentBuilder parser;
private Validator validator;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
public void init() {
Resource schemaResource = resourceLoader.getResource("classpath:intellivr-in.xsd");
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
try {
Schema schema = factory.newSchema(schemaResource.getFile());
parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
validator = schema.newValidator();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
JAXBContext jaxbc = JAXBContext.newInstance("org.motechproject.omp.manager.intellivr");
marshaller = jaxbc.createMarshaller();
unmarshaller = jaxbc.createUnmarshaller();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String content = getContent(request);
Object output = null;
if ( !contentIsValid(content) ) {
AutoCreate ac = new AutoCreate();
ResponseType rt = new ResponseType();
rt.setStatus(StatusType.ERROR);
rt.setErrorCode(ErrorCodeType.MOTECH_MALFORMED_XML);
rt.setErrorString("Malformed XML content");
ac.setResponse(rt);
output = ac;
} else {
AutoCreate ac = new AutoCreate();
ResponseType rt = new ResponseType();
rt.setStatus(StatusType.OK);
rt.setLanguage("ENGLISH");
rt.setPrivate("PRIVATE");
rt.setReportUrl("http://130.111.123.83:8080/motech-mobile-webapp/intellivr");
rt.setTree("TestTree");
Vxml vxml = new Vxml();
rt.setVxml(vxml);
ac.setResponse(rt);
output = ac;
}
if ( output == null ) {
AutoCreate ac = new AutoCreate();
ResponseType rt = new ResponseType();
rt.setStatus(StatusType.ERROR);
rt.setErrorCode(ErrorCodeType.MOTECH_UNKNOWN_ERROR);
rt.setErrorString("An unknown error has occured");
ac.setResponse(rt);
output = ac;
}
PrintWriter out = response.getWriter();
try {
response.setContentType("text/xml");
marshaller.marshal(output, out);
} catch (JAXBException e) {
e.printStackTrace();
out.println("<test>jaxb error</test>");
}
return null;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
private String getContent(HttpServletRequest request) throws Exception {
InputStream in = request.getInputStream();
int length = request.getContentLength();
byte[] buffer = new byte[length];
in.read(buffer, 0, length);
return new String(buffer);
}
private boolean contentIsValid(String content) {
try {
Document doc = parser.parse(new ByteArrayInputStream(content.getBytes()));
validator.validate(new DOMSource(doc));
return true;
} catch (SAXException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
| motech-mobile-webapp/src/main/java/org/motechproject/mobile/web/ivr/intellivr/IntellIVRController.java | package org.motechproject.mobile.web.ivr.intellivr;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.motechproject.omp.manager.intellivr.AutoCreate;
import org.motechproject.omp.manager.intellivr.ErrorCodeType;
import org.motechproject.omp.manager.intellivr.ResponseType;
import org.motechproject.omp.manager.intellivr.StatusType;
import org.motechproject.omp.manager.intellivr.RequestType.Vxml;
public class IntellIVRController extends AbstractController implements ResourceLoaderAware {
private ResourceLoader resourceLoader;
private DocumentBuilder parser;
private Validator validator;
public void init() {
Resource schemaResource = resourceLoader.getResource("classpath:intellivr-in.xsd");
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
try {
Schema schema = factory.newSchema(schemaResource.getFile());
parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
validator = schema.newValidator();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String content = getContent(request);
Object output = null;
if ( !contentIsValid(content) ) {
AutoCreate ac = new AutoCreate();
ResponseType rt = new ResponseType();
rt.setStatus(StatusType.ERROR);
rt.setErrorCode(ErrorCodeType.MOTECH_MALFORMED_XML);
rt.setErrorString("Malformed XML content");
ac.setResponse(rt);
output = ac;
} else {
AutoCreate ac = new AutoCreate();
ResponseType rt = new ResponseType();
rt.setStatus(StatusType.OK);
rt.setLanguage("ENGLISH");
rt.setPrivate("PRIVATE");
rt.setReportUrl("http://130.111.123.83:8080/motech-mobile-webapp/intellivr");
rt.setTree("TestTree");
Vxml vxml = new Vxml();
rt.setVxml(vxml);
ac.setResponse(rt);
output = ac;
}
if ( output == null ) {
AutoCreate ac = new AutoCreate();
ResponseType rt = new ResponseType();
rt.setStatus(StatusType.ERROR);
rt.setErrorCode(ErrorCodeType.MOTECH_UNKNOWN_ERROR);
rt.setErrorString("An unknown error has occured");
ac.setResponse(rt);
output = ac;
}
PrintWriter out = response.getWriter();
try {
response.setContentType("text/xml");
JAXBContext jac = JAXBContext.newInstance("org.motechproject.omp.manager.intellivr");
Marshaller m = jac.createMarshaller();
m.marshal(output, out);
} catch (JAXBException e) {
e.printStackTrace();
out.println("<test>jaxb error</test>");
}
return null;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
private String getContent(HttpServletRequest request) throws Exception {
InputStream in = request.getInputStream();
int length = request.getContentLength();
byte[] buffer = new byte[length];
in.read(buffer, 0, length);
return new String(buffer);
}
private boolean contentIsValid(String content) {
try {
Document doc = parser.parse(new ByteArrayInputStream(content.getBytes()));
validator.validate(new DOMSource(doc));
return true;
} catch (SAXException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
| IntellIVRController.java - added initialization of a Marshaller and Unmarshaller to the init method.
| motech-mobile-webapp/src/main/java/org/motechproject/mobile/web/ivr/intellivr/IntellIVRController.java | IntellIVRController.java - added initialization of a Marshaller and Unmarshaller to the init method. | <ide><path>otech-mobile-webapp/src/main/java/org/motechproject/mobile/web/ivr/intellivr/IntellIVRController.java
<ide> import javax.xml.bind.JAXBContext;
<ide> import javax.xml.bind.JAXBException;
<ide> import javax.xml.bind.Marshaller;
<add>import javax.xml.bind.Unmarshaller;
<ide> import javax.xml.parsers.DocumentBuilder;
<ide> import javax.xml.parsers.DocumentBuilderFactory;
<ide> import javax.xml.parsers.FactoryConfigurationError;
<ide> private ResourceLoader resourceLoader;
<ide> private DocumentBuilder parser;
<ide> private Validator validator;
<add> private Marshaller marshaller;
<add> private Unmarshaller unmarshaller;
<ide>
<del> public void init() {
<add> public void init() {
<ide> Resource schemaResource = resourceLoader.getResource("classpath:intellivr-in.xsd");
<ide> SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
<ide> try {
<ide> // TODO Auto-generated catch block
<ide> e.printStackTrace();
<ide> } catch (FactoryConfigurationError e) {
<add> // TODO Auto-generated catch block
<add> e.printStackTrace();
<add> }
<add> try {
<add> JAXBContext jaxbc = JAXBContext.newInstance("org.motechproject.omp.manager.intellivr");
<add> marshaller = jaxbc.createMarshaller();
<add> unmarshaller = jaxbc.createUnmarshaller();
<add> } catch (JAXBException e) {
<ide> // TODO Auto-generated catch block
<ide> e.printStackTrace();
<ide> }
<ide>
<ide> try {
<ide> response.setContentType("text/xml");
<del> JAXBContext jac = JAXBContext.newInstance("org.motechproject.omp.manager.intellivr");
<del> Marshaller m = jac.createMarshaller();
<del> m.marshal(output, out);
<add> marshaller.marshal(output, out);
<ide> } catch (JAXBException e) {
<ide> e.printStackTrace();
<ide> out.println("<test>jaxb error</test>"); |
|
Java | mit | error: pathspec 'src/GuessClass.java' did not match any file(s) known to git
| 3fd494c760368841f8281a85efefc690bfe4e4fe | 1 | perryprog/GuessGame | /**
* Created by Perry on 6/11/15.
*/
import java.util.Random;// my imports
import java.util.Scanner;
public class GuessClass {
private static void makeFalse() {
for (int i = 0; i < 10; i++) {
hasTyped[i] = false;
}
}
final private static String[] messagesHigher = { // 2 arrays, one if it's lower, one if it's higher
"No way, it is higher then that!",
"Really? It is higher then that!",
"Nope! It is higher then that!"};
final private static String[] messagesLower = {
"No way, it is lower then that!",
"Really? It is lower then that!",
"Nope! It is lower then that!"};
final private static String[] hardMessage = {
"No way!",
"Really?",
"Nope!"};
private static Boolean[] hasTyped = new Boolean[10];
public static void main(String[] args) {
while (true) {
int target = 0;// the number you will try to get to
int current_guess = 0;// the number you have just typed
int rand_message = 0;// for the random message you see
int times_guessed = 0;// the number of times you guessed
boolean higher = false;// for if the target is higher then what you guessed
long start = 0;// timer
long stop = 0;// timer
long total_mill = 0;// timer
long total_sec = 0;// timer
String start_string = "null";// for typing start at the beginning
String difficulty = "null";// if your mode is hard
Scanner user_input = new Scanner(System.in);// configuring imports
Random rn = new Random();
makeFalse();
target = rn.nextInt(10) + 1;// the random target
while (true) {
System.out.println("Please type hard for hard or easy for easy");
difficulty = user_input.next();
if (difficulty.equals("hard") || difficulty.equals("easy")) {
break;
}
}
while (true) {
System.out.println("Please type \"start\" to begin!");
start_string = user_input.next();
if (start_string.equals("start")) {
break;
}
}
System.out.print("I am thinking of a number 1 through 10... Can you guess it?");// first message you see
System.out.println();// new line
current_guess = user_input.nextInt();// sets your guess to what you type
if (current_guess >= 1 && current_guess <= 10) {
start = System.currentTimeMillis();// "starts" the timer
while (current_guess != target) { // loops until you guess right - skips it if you guess the right number the first timer
rand_message = rn.nextInt(messagesHigher.length); // gets the next random message
higher = current_guess < target; // sets higher to true if target is higher
if (hasTyped[current_guess]) { // looks if you are insane (I'm not kidding)
System.out.println("The definition of insanity is doing the same thing, but expecting a different result.");
}
if (difficulty.equals("easy")) {
if (higher) {
System.out.println(messagesHigher[rand_message]);
} else {
System.out.println(messagesLower[rand_message]);
}
}
else {
System.out.println(hardMessage[rand_message]);
}
hasTyped[current_guess] = true;
current_guess = user_input.nextInt();// lets you type the next guess
}
if (current_guess >= 1 && current_guess <= 10) {
System.out.println();
}
times_guessed++;// one up to how many guesses you have
stop = System.currentTimeMillis();// "stops" the timer
total_mill = stop - start;// figures out the total time it took to run
total_sec = total_mill / 1000;// does above, in seconds
if (times_guessed + 1 == 1) {// if you had 1 guess you get a special message
System.out.println("Nice! You got it! That took you " + total_mill + " milliseconds, or " + total_sec + " seconds! Also, you guessed on your first try!");// first try message
} else {
times_guessed++;
System.out.println("Nice! You got it! That took you " + total_mill + " milliseconds, or " + total_sec + " seconds! Also, you guessed " + times_guessed + " times!");// +1 try else message
}
}
else {
System.out.println("Please only use numbers 1 through 10!");
}
}
}
} | src/GuessClass.java | Here's the program!
| src/GuessClass.java | Here's the program! | <ide><path>rc/GuessClass.java
<add>/**
<add> * Created by Perry on 6/11/15.
<add> */
<add>
<add>import java.util.Random;// my imports
<add>import java.util.Scanner;
<add>
<add>public class GuessClass {
<add>
<add> private static void makeFalse() {
<add>
<add> for (int i = 0; i < 10; i++) {
<add>
<add> hasTyped[i] = false;
<add>
<add> }
<add> }
<add>
<add> final private static String[] messagesHigher = { // 2 arrays, one if it's lower, one if it's higher
<add> "No way, it is higher then that!",
<add> "Really? It is higher then that!",
<add> "Nope! It is higher then that!"};
<add>
<add> final private static String[] messagesLower = {
<add> "No way, it is lower then that!",
<add> "Really? It is lower then that!",
<add> "Nope! It is lower then that!"};
<add>
<add> final private static String[] hardMessage = {
<add> "No way!",
<add> "Really?",
<add> "Nope!"};
<add>
<add> private static Boolean[] hasTyped = new Boolean[10];
<add>
<add>
<add>
<add> public static void main(String[] args) {
<add>
<add> while (true) {
<add>
<add> int target = 0;// the number you will try to get to
<add> int current_guess = 0;// the number you have just typed
<add> int rand_message = 0;// for the random message you see
<add> int times_guessed = 0;// the number of times you guessed
<add>
<add> boolean higher = false;// for if the target is higher then what you guessed
<add>
<add> long start = 0;// timer
<add> long stop = 0;// timer
<add> long total_mill = 0;// timer
<add> long total_sec = 0;// timer
<add>
<add> String start_string = "null";// for typing start at the beginning
<add> String difficulty = "null";// if your mode is hard
<add>
<add> Scanner user_input = new Scanner(System.in);// configuring imports
<add> Random rn = new Random();
<add>
<add> makeFalse();
<add>
<add> target = rn.nextInt(10) + 1;// the random target
<add>
<add>
<add> while (true) {
<add>
<add> System.out.println("Please type hard for hard or easy for easy");
<add> difficulty = user_input.next();
<add> if (difficulty.equals("hard") || difficulty.equals("easy")) {
<add> break;
<add> }
<add>
<add> }
<add> while (true) {
<add> System.out.println("Please type \"start\" to begin!");
<add> start_string = user_input.next();
<add> if (start_string.equals("start")) {
<add> break;
<add> }
<add> }
<add>
<add> System.out.print("I am thinking of a number 1 through 10... Can you guess it?");// first message you see
<add> System.out.println();// new line
<add>
<add> current_guess = user_input.nextInt();// sets your guess to what you type
<add>
<add>
<add> if (current_guess >= 1 && current_guess <= 10) {
<add>
<add> start = System.currentTimeMillis();// "starts" the timer
<add>
<add> while (current_guess != target) { // loops until you guess right - skips it if you guess the right number the first timer
<add>
<add> rand_message = rn.nextInt(messagesHigher.length); // gets the next random message
<add>
<add> higher = current_guess < target; // sets higher to true if target is higher
<add>
<add> if (hasTyped[current_guess]) { // looks if you are insane (I'm not kidding)
<add> System.out.println("The definition of insanity is doing the same thing, but expecting a different result.");
<add> }
<add> if (difficulty.equals("easy")) {
<add> if (higher) {
<add>
<add> System.out.println(messagesHigher[rand_message]);
<add>
<add> } else {
<add>
<add> System.out.println(messagesLower[rand_message]);
<add>
<add> }
<add> }
<add> else {
<add> System.out.println(hardMessage[rand_message]);
<add> }
<add> hasTyped[current_guess] = true;
<add> current_guess = user_input.nextInt();// lets you type the next guess
<add>
<add>
<add> }
<add> if (current_guess >= 1 && current_guess <= 10) {
<add> System.out.println();
<add> }
<add>
<add> times_guessed++;// one up to how many guesses you have
<add>
<add> stop = System.currentTimeMillis();// "stops" the timer
<add>
<add> total_mill = stop - start;// figures out the total time it took to run
<add> total_sec = total_mill / 1000;// does above, in seconds
<add>
<add>
<add> if (times_guessed + 1 == 1) {// if you had 1 guess you get a special message
<add>
<add> System.out.println("Nice! You got it! That took you " + total_mill + " milliseconds, or " + total_sec + " seconds! Also, you guessed on your first try!");// first try message
<add>
<add> } else {
<add>
<add> times_guessed++;
<add>
<add> System.out.println("Nice! You got it! That took you " + total_mill + " milliseconds, or " + total_sec + " seconds! Also, you guessed " + times_guessed + " times!");// +1 try else message
<add>
<add> }
<add>
<add> }
<add>
<add> else {
<add> System.out.println("Please only use numbers 1 through 10!");
<add> }
<add>
<add> }
<add>
<add> }
<add>
<add>} |
|
Java | mit | 0f402bd9e921e1854d2beaa809de73482a38567f | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.project.status.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.service.ApplicationService;
import org.innovateuk.ifs.commons.exception.ForbiddenActionException;
import org.innovateuk.ifs.commons.security.PermissionRule;
import org.innovateuk.ifs.commons.security.PermissionRules;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.project.ProjectService;
import org.innovateuk.ifs.project.resource.*;
import org.innovateuk.ifs.project.status.resource.ProjectTeamStatusResource;
import org.innovateuk.ifs.sections.SectionAccess;
import org.innovateuk.ifs.status.StatusService;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.service.OrganisationRestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import static org.innovateuk.ifs.sections.SectionAccess.ACCESSIBLE;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst;
import static org.innovateuk.ifs.util.SecurityRuleUtil.isMonitoringOfficer;
/**
* Permission checker around the access to various sections within the Project Setup process
*/
@PermissionRules
@Component
public class SetupSectionsPermissionRules {
private static final Log LOG = LogFactory.getLog(SetupSectionsPermissionRules.class);
@Autowired
private ProjectService projectService;
@Autowired
private ApplicationService applicationService;
@Autowired
private CompetitionRestService competitionRestService;
@Autowired
private StatusService statusService;
@Autowired
private OrganisationRestService organisationRestService;
private SetupSectionPartnerAccessorSupplier accessorSupplier = new SetupSectionPartnerAccessorSupplier();
@PermissionRule(value = "ACCESS_PROJECT_SETUP_STATUS", description = "A partner can access the Project Setup Status page when the project is in a correct state to do so")
public boolean partnerCanAccessProjectSetupStatus(ProjectCompositeId projectCompositeId, UserResource user) {
return isProjectInViewableState(projectCompositeId.id());
}
@PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so")
public boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user) {
return isProjectInViewableState(projectCompositeId.id());
}
@PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required")
public boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessProjectDetailsSection);
}
@PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " +
"page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated")
public boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessFinanceContactPage);
}
@PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " +
"page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned")
public boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user) {
boolean partnerProjectLocationRequired = isPartnerProjectLocationRequired(projectCompositeId);
return doSectionCheck(projectCompositeId.id(), user,
(setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canAccessPartnerProjectLocationPage(organisation, partnerProjectLocationRequired));
}
private boolean isPartnerProjectLocationRequired(ProjectCompositeId projectCompositeId) {
ProjectResource project = projectService.getById(projectCompositeId.id());
ApplicationResource applicationResource = applicationService.getById(project.getApplication());
CompetitionResource competition = competitionRestService.getCompetitionById(applicationResource.getCompetition()).getSuccess();
return competition.isLocationPerPartner();
}
@PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " +
"page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated")
public boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user) {
return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::leadCanAccessProjectManagerPage);
}
private boolean isMonitoringOfficerOnProject(long projectId, long userId) {
return Optional.ofNullable(projectService.getById(projectId))
.map(ProjectResource::getMonitoringOfficerUser)
.map(monitoringOfficerId -> monitoringOfficerId.equals(userId))
.orElse(false);
}
@PermissionRule(value = "ACCESS_PROJECT_START_DATE_PAGE", description = "A lead can access the Project Start Date " +
"page when their Companies House data is complete or not required, and the Spend Profile has not yet been generated")
public boolean leadCanAccessProjectStartDatePage(ProjectCompositeId projectCompositeId, UserResource user) {
return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::leadCanAccessProjectStartDatePage);
}
@PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " +
"page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated")
public boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user) {
return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::leadCanAccessProjectAddressPage);
}
@PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " +
"section when their Companies House details are complete or not required, and the Project Details have been submitted")
public boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user) {
boolean partnerProjectLocationRequired = isPartnerProjectLocationRequired(projectCompositeId);
return doSectionCheck(projectCompositeId.id(), user,
(setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canAccessMonitoringOfficerSection(organisation, partnerProjectLocationRequired));
}
@PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " +
"section when their Companies House details are complete or not required, and they have a Finance Contact " +
"available for their Organisation")
public boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user) {
return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessBankDetailsSection);
}
@PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " +
" when their Companies House details are complete or not required, and the Project Details have been submitted")
public boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user) {
return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessFinanceChecksSection);
}
@PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " +
"section when their Companies House details are complete or not required, the Project Details have been submitted, " +
"and the Organisation's Bank Details have been approved or queried")
public boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessSpendProfileSection);
}
@PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " +
"section when their Companies House details are complete or not required, the Project Details have been submitted, " +
"and the Organisation's Bank Details have been approved or queried")
public boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user) {
return isProjectManager(projectCompositeId.id(), user) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessSpendProfileSection);
}
@PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " +
"section when their Companies House details are complete or not required, the Project Details have been submitted, " +
"and the Organisation's Bank Details have been approved or queried")
public boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessSpendProfileSection);
}
@PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " +
"section when their Companies House details are complete or not required, the Project Details have been submitted, " +
"and the Organisation's Bank Details have been approved or not required")
public boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) {
return doSectionCheck(projectOrganisationCompositeId.getProjectId(), user, (setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canEditSpendProfileSection(organisation, projectOrganisationCompositeId.getOrganisationId()));
}
@PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " +
"section if their Companies House information is unnecessary or complete")
public boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessDocumentsSection);
}
@PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section")
public boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user) {
return isProjectManager(projectCompositeId.id(), user);
}
private boolean isProjectManager(Long projectId, UserResource user) {
return projectService.isProjectManager(user.getId(), projectId);
}
@PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " +
"section when all other sections are complete and a Grant Offer Letter has been generated by the internal team")
public boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection);
}
@PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document")
public boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection) &&
projectService.isUserLeadPartner(projectCompositeId.id(), user.getId());
}
@PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete")
public boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user) {
List<ProjectUserResource> projectLeadPartners = projectService.getLeadPartners(projectCompositeId.id());
Optional<ProjectUserResource> returnedProjectUser = simpleFindFirst(projectLeadPartners, projectUserResource -> projectUserResource.getUser().equals(user.getId()));
return returnedProjectUser.isPresent();
}
@PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete")
public boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) {
OrganisationResource organisation = organisationRestService.getByUserAndProjectId(user.getId(), projectOrganisationCompositeId.getProjectId()).getSuccess();
return !organisation.getId().equals(projectOrganisationCompositeId.getOrganisationId());
}
private boolean doSectionCheck(long projectId, UserResource user, BiFunction<SetupSectionAccessibilityHelper, OrganisationResource, SectionAccess> sectionCheckFn) {
try {
if (!isProjectInViewableState(projectId)) {
return false;
}
boolean isMonitoringOfficer = isMonitoringOfficer(user);
long organisationId = isMonitoringOfficer ?
projectService.getLeadOrganisation(projectId).getId() : projectService.getOrganisationIdFromUser(projectId, user);
ProjectTeamStatusResource teamStatus = isMonitoringOfficer ?
getProjectTeamStatusForMonitoringOfficer(projectId) : statusService.getProjectTeamStatus(projectId, Optional.of(user.getId()));
ProjectPartnerStatusResource partnerStatusForUser = teamStatus.getPartnerStatusForOrganisation(organisationId).get();
SetupSectionAccessibilityHelper sectionAccessor = accessorSupplier.apply(teamStatus);
OrganisationResource organisation = new OrganisationResource();
organisation.setId(partnerStatusForUser.getOrganisationId());
organisation.setOrganisationType(partnerStatusForUser.getOrganisationType().getId());
return sectionCheckFn.apply(sectionAccessor, organisation) == ACCESSIBLE;
} catch (ForbiddenActionException e) {
LOG.error("User " + user.getId() + " is not a Partner on an Organisation for Project " + projectId + ". Denying access to Project Setup", e);
return false;
}
}
private ProjectTeamStatusResource getProjectTeamStatusForMonitoringOfficer(long projectId) {
ProjectUserResource leadProjectUser = projectService.getLeadPartners(projectId).stream().findFirst().get();
return statusService.getProjectTeamStatus(projectId, Optional.of(leadProjectUser.getUser()));
}
private boolean isProjectInViewableState(long projectId) {
return !isProjectWithdrawn(projectId);
}
private boolean isProjectWithdrawn(long projectId) {
ProjectResource project = projectService.getById(projectId);
return ProjectState.WITHDRAWN.equals(project.getProjectState());
}
public class SetupSectionPartnerAccessorSupplier implements Function<ProjectTeamStatusResource, SetupSectionAccessibilityHelper> {
@Override
public SetupSectionAccessibilityHelper apply(ProjectTeamStatusResource teamStatus) {
return new SetupSectionAccessibilityHelper(teamStatus);
}
}
}
| ifs-web-service/ifs-project-setup-service/src/main/java/org/innovateuk/ifs/project/status/security/SetupSectionsPermissionRules.java | package org.innovateuk.ifs.project.status.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.service.ApplicationService;
import org.innovateuk.ifs.commons.exception.ForbiddenActionException;
import org.innovateuk.ifs.commons.security.PermissionRule;
import org.innovateuk.ifs.commons.security.PermissionRules;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.project.ProjectService;
import org.innovateuk.ifs.project.resource.*;
import org.innovateuk.ifs.project.status.resource.ProjectTeamStatusResource;
import org.innovateuk.ifs.sections.SectionAccess;
import org.innovateuk.ifs.status.StatusService;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.service.OrganisationRestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import static org.innovateuk.ifs.sections.SectionAccess.ACCESSIBLE;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst;
import static org.innovateuk.ifs.util.SecurityRuleUtil.isMonitoringOfficer;
/**
* Permission checker around the access to various sections within the Project Setup process
*/
@PermissionRules
@Component
public class SetupSectionsPermissionRules {
private static final Log LOG = LogFactory.getLog(SetupSectionsPermissionRules.class);
@Autowired
private ProjectService projectService;
@Autowired
private ApplicationService applicationService;
@Autowired
private CompetitionRestService competitionRestService;
@Autowired
private StatusService statusService;
@Autowired
private OrganisationRestService organisationRestService;
private SetupSectionPartnerAccessorSupplier accessorSupplier = new SetupSectionPartnerAccessorSupplier();
@PermissionRule(value = "ACCESS_PROJECT_SETUP_STATUS", description = "A partner can access the Project Setup Status page when the project is in a correct state to do so")
public boolean partnerCanAccessProjectSetupStatus(ProjectCompositeId projectCompositeId, UserResource user) {
return isProjectInViewableState(projectCompositeId.id());
}
@PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so")
public boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user) {
return isProjectInViewableState(projectCompositeId.id());
}
@PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required")
public boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessProjectDetailsSection);
}
@PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " +
"page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated")
public boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessFinanceContactPage);
}
@PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " +
"page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned")
public boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user) {
boolean partnerProjectLocationRequired = isPartnerProjectLocationRequired(projectCompositeId);
return doSectionCheck(projectCompositeId.id(), user,
(setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canAccessPartnerProjectLocationPage(organisation, partnerProjectLocationRequired));
}
private boolean isPartnerProjectLocationRequired(ProjectCompositeId projectCompositeId) {
ProjectResource project = projectService.getById(projectCompositeId.id());
ApplicationResource applicationResource = applicationService.getById(project.getApplication());
CompetitionResource competition = competitionRestService.getCompetitionById(applicationResource.getCompetition()).getSuccess();
return competition.isLocationPerPartner();
}
@PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " +
"page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated")
public boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user) {
return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::leadCanAccessProjectManagerPage);
}
private boolean isMonitoringOfficerOnProject(long projectId, long userId) {
ProjectResource project = projectService.getById(projectId);
if (null == project) return false;
if (null == project.getMonitoringOfficerUser()) return false;
return project.getMonitoringOfficerUser().equals(userId);
}
@PermissionRule(value = "ACCESS_PROJECT_START_DATE_PAGE", description = "A lead can access the Project Start Date " +
"page when their Companies House data is complete or not required, and the Spend Profile has not yet been generated")
public boolean leadCanAccessProjectStartDatePage(ProjectCompositeId projectCompositeId, UserResource user) {
return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::leadCanAccessProjectStartDatePage);
}
@PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " +
"page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated")
public boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user) {
return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::leadCanAccessProjectAddressPage);
}
@PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " +
"section when their Companies House details are complete or not required, and the Project Details have been submitted")
public boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user) {
boolean partnerProjectLocationRequired = isPartnerProjectLocationRequired(projectCompositeId);
return doSectionCheck(projectCompositeId.id(), user,
(setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canAccessMonitoringOfficerSection(organisation, partnerProjectLocationRequired));
}
@PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " +
"section when their Companies House details are complete or not required, and they have a Finance Contact " +
"available for their Organisation")
public boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user) {
return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessBankDetailsSection);
}
@PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " +
" when their Companies House details are complete or not required, and the Project Details have been submitted")
public boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user) {
return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessFinanceChecksSection);
}
@PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " +
"section when their Companies House details are complete or not required, the Project Details have been submitted, " +
"and the Organisation's Bank Details have been approved or queried")
public boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessSpendProfileSection);
}
@PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " +
"section when their Companies House details are complete or not required, the Project Details have been submitted, " +
"and the Organisation's Bank Details have been approved or queried")
public boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user) {
return isProjectManager(projectCompositeId.id(), user) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessSpendProfileSection);
}
@PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " +
"section when their Companies House details are complete or not required, the Project Details have been submitted, " +
"and the Organisation's Bank Details have been approved or queried")
public boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessSpendProfileSection);
}
@PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " +
"section when their Companies House details are complete or not required, the Project Details have been submitted, " +
"and the Organisation's Bank Details have been approved or not required")
public boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) {
return doSectionCheck(projectOrganisationCompositeId.getProjectId(), user, (setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canEditSpendProfileSection(organisation, projectOrganisationCompositeId.getOrganisationId()));
}
@PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " +
"section if their Companies House information is unnecessary or complete")
public boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessDocumentsSection);
}
@PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section")
public boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user) {
return isProjectManager(projectCompositeId.id(), user);
}
private boolean isProjectManager(Long projectId, UserResource user) {
return projectService.isProjectManager(user.getId(), projectId);
}
@PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " +
"section when all other sections are complete and a Grant Offer Letter has been generated by the internal team")
public boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection);
}
@PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document")
public boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user) {
return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection) &&
projectService.isUserLeadPartner(projectCompositeId.id(), user.getId());
}
@PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete")
public boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user) {
List<ProjectUserResource> projectLeadPartners = projectService.getLeadPartners(projectCompositeId.id());
Optional<ProjectUserResource> returnedProjectUser = simpleFindFirst(projectLeadPartners, projectUserResource -> projectUserResource.getUser().equals(user.getId()));
return returnedProjectUser.isPresent();
}
@PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete")
public boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) {
OrganisationResource organisation = organisationRestService.getByUserAndProjectId(user.getId(), projectOrganisationCompositeId.getProjectId()).getSuccess();
return !organisation.getId().equals(projectOrganisationCompositeId.getOrganisationId());
}
private boolean doSectionCheck(long projectId, UserResource user, BiFunction<SetupSectionAccessibilityHelper, OrganisationResource, SectionAccess> sectionCheckFn) {
try {
if (!isProjectInViewableState(projectId)) {
return false;
}
boolean isMonitoringOfficer = isMonitoringOfficer(user);
long organisationId = isMonitoringOfficer ?
projectService.getLeadOrganisation(projectId).getId() : projectService.getOrganisationIdFromUser(projectId, user);
ProjectTeamStatusResource teamStatus = isMonitoringOfficer ?
getProjectTeamStatusForMonitoringOfficer(projectId) : statusService.getProjectTeamStatus(projectId, Optional.of(user.getId()));
ProjectPartnerStatusResource partnerStatusForUser = teamStatus.getPartnerStatusForOrganisation(organisationId).get();
SetupSectionAccessibilityHelper sectionAccessor = accessorSupplier.apply(teamStatus);
OrganisationResource organisation = new OrganisationResource();
organisation.setId(partnerStatusForUser.getOrganisationId());
organisation.setOrganisationType(partnerStatusForUser.getOrganisationType().getId());
return sectionCheckFn.apply(sectionAccessor, organisation) == ACCESSIBLE;
} catch (ForbiddenActionException e) {
LOG.error("User " + user.getId() + " is not a Partner on an Organisation for Project " + projectId + ". Denying access to Project Setup", e);
return false;
}
}
private ProjectTeamStatusResource getProjectTeamStatusForMonitoringOfficer(long projectId) {
ProjectUserResource leadProjectUser = projectService.getLeadPartners(projectId).stream().findFirst().get();
return statusService.getProjectTeamStatus(projectId, Optional.of(leadProjectUser.getUser()));
}
private boolean isProjectInViewableState(long projectId) {
return !isProjectWithdrawn(projectId);
}
private boolean isProjectWithdrawn(long projectId) {
ProjectResource project = projectService.getById(projectId);
return ProjectState.WITHDRAWN.equals(project.getProjectState());
}
public class SetupSectionPartnerAccessorSupplier implements Function<ProjectTeamStatusResource, SetupSectionAccessibilityHelper> {
@Override
public SetupSectionAccessibilityHelper apply(ProjectTeamStatusResource teamStatus) {
return new SetupSectionAccessibilityHelper(teamStatus);
}
}
}
| IFS-5611 change rules
| ifs-web-service/ifs-project-setup-service/src/main/java/org/innovateuk/ifs/project/status/security/SetupSectionsPermissionRules.java | IFS-5611 change rules | <ide><path>fs-web-service/ifs-project-setup-service/src/main/java/org/innovateuk/ifs/project/status/security/SetupSectionsPermissionRules.java
<ide> }
<ide>
<ide> private boolean isMonitoringOfficerOnProject(long projectId, long userId) {
<del> ProjectResource project = projectService.getById(projectId);
<del> if (null == project) return false;
<del> if (null == project.getMonitoringOfficerUser()) return false;
<del> return project.getMonitoringOfficerUser().equals(userId);
<add> return Optional.ofNullable(projectService.getById(projectId))
<add> .map(ProjectResource::getMonitoringOfficerUser)
<add> .map(monitoringOfficerId -> monitoringOfficerId.equals(userId))
<add> .orElse(false);
<ide> }
<ide>
<ide> @PermissionRule(value = "ACCESS_PROJECT_START_DATE_PAGE", description = "A lead can access the Project Start Date " + |
|
Java | mit | 9e5a25dad862a15faf02710367c5538a71120fc7 | 0 | CruGlobal/android-gto-support,CruGlobal/android-gto-support,GlobalTechnology/android-gto-support | package org.ccci.gto.android.common.db;
import android.text.TextUtils;
import android.util.Pair;
import org.ccci.gto.android.common.db.Contract.RootTable;
import org.ccci.gto.android.common.testing.CommonMocks;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.AnyOf.anyOf;
import static org.junit.Assert.assertThat;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Pair.class, TextUtils.class})
public class QueryTest {
private TestDao getDao() {
return TestDao.mock();
}
@Before
public void setup() throws Exception {
CommonMocks.mockPair();
CommonMocks.mockTextUtils();
}
@Test
public void testHavingSql() {
Expression having = RootTable.FIELD_TEST.count().eq(1);
Query<RootTable> query = Query.select(RootTable.class).groupBy(RootTable.FIELD_TEST).having(having);
Pair<String, String[]> sqlPair = query.buildSqlHaving(getDao());
assertThat(sqlPair.first, is("(COUNT (root.test) == 1)"));
}
@Test
public void verifyLimitSql() {
final Query<RootTable> query = Query.select(RootTable.class);
assertThat(query.limit(null).buildSqlLimit(), nullValue());
assertThat(query.limit(null).offset(10).buildSqlLimit(), nullValue());
assertThat(query.limit(5).offset(null).buildSqlLimit(), is("5"));
assertThat(query.limit(5).offset(15).buildSqlLimit(), anyOf(is("5 OFFSET 15"), is("15,5")));
}
}
| gto-support-db/src/test/java/org/ccci/gto/android/common/db/QueryTest.java | package org.ccci.gto.android.common.db;
import android.text.TextUtils;
import android.util.Pair;
import org.ccci.gto.android.common.db.Contract.RootTable;
import org.ccci.gto.android.common.testing.CommonMocks;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.AnyOf.anyOf;
import static org.junit.Assert.assertThat;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Pair.class, TextUtils.class})
public class QueryTest {
private TestDao getDao() {
return TestDao.mock();
}
@Before
public void setup() throws Exception {
CommonMocks.mockPair();
CommonMocks.mockTextUtils();
}
@Test
public void testHavingSql() {
Expression having = RootTable.FIELD_TEST.count().eq(1);
Query query = Query.select(RootTable.class).groupBy(RootTable.FIELD_TEST).having(having);
Pair<String, String[]> sqlPair = query.buildSqlHaving(getDao());
assertThat(sqlPair.first, is("(COUNT (root.test) == 1)"));
}
@Test
public void verifyLimitSql() {
final Query<RootTable> query = Query.select(RootTable.class);
assertThat(query.limit(null).buildSqlLimit(), nullValue());
assertThat(query.limit(null).offset(10).buildSqlLimit(), nullValue());
assertThat(query.limit(5).offset(null).buildSqlLimit(), is("5"));
assertThat(query.limit(5).offset(15).buildSqlLimit(), anyOf(is("5 OFFSET 15"), is("15,5")));
}
}
| add generic to fix lint warning
| gto-support-db/src/test/java/org/ccci/gto/android/common/db/QueryTest.java | add generic to fix lint warning | <ide><path>to-support-db/src/test/java/org/ccci/gto/android/common/db/QueryTest.java
<ide> @Test
<ide> public void testHavingSql() {
<ide> Expression having = RootTable.FIELD_TEST.count().eq(1);
<del> Query query = Query.select(RootTable.class).groupBy(RootTable.FIELD_TEST).having(having);
<add> Query<RootTable> query = Query.select(RootTable.class).groupBy(RootTable.FIELD_TEST).having(having);
<ide> Pair<String, String[]> sqlPair = query.buildSqlHaving(getDao());
<ide> assertThat(sqlPair.first, is("(COUNT (root.test) == 1)"));
<ide> } |
|
Java | apache-2.0 | 67a58208020c1c72ca2c0c0aa56faa5ebc2ed474 | 0 | jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient | package org.sagebionetworks.web.client.widget.user;
import java.util.Map;
import org.sagebionetworks.repo.model.UserProfile;
import org.sagebionetworks.schema.adapter.AdapterFactory;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.web.client.DisplayUtils;
import org.sagebionetworks.web.client.GlobalApplicationState;
import org.sagebionetworks.web.client.SynapseClientAsync;
import org.sagebionetworks.web.client.SynapseJSNIUtils;
import org.sagebionetworks.web.client.cache.ClientCache;
import org.sagebionetworks.web.client.place.Profile;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.widget.SynapseWidgetPresenter;
import org.sagebionetworks.web.client.widget.WidgetRendererPresenter;
import org.sagebionetworks.web.shared.WebConstants;
import org.sagebionetworks.web.shared.WidgetConstants;
import org.sagebionetworks.web.shared.WikiPageKey;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class UserBadge implements UserBadgeView.Presenter, SynapseWidgetPresenter, WidgetRendererPresenter {
private UserBadgeView view;
SynapseClientAsync synapseClient;
private Integer maxNameLength;
UserProfile profile;
ClickHandler customClickHandler;
GlobalApplicationState globalApplicationState;
SynapseJSNIUtils synapseJSNIUtils;
boolean isShowCompany;
String description;
boolean useCachedImage;
private AdapterFactory adapterFactory;
private ClientCache clientCache;
@Inject
public UserBadge(UserBadgeView view,
SynapseClientAsync synapseClient,
GlobalApplicationState globalApplicationState,
SynapseJSNIUtils synapseJSNIUtils,
AdapterFactory adapterFactory,
ClientCache clientCache) {
this.view = view;
this.synapseClient = synapseClient;
this.globalApplicationState = globalApplicationState;
this.synapseJSNIUtils = synapseJSNIUtils;
this.adapterFactory = adapterFactory;
this.clientCache = clientCache;
view.setPresenter(this);
view.setSize(BadgeSize.SMALL);
clearState();
}
public void setMaxNameLength(Integer maxLength) {
this.maxNameLength = maxLength;
}
/**
* Simple configure, with user profile
* @param profile
*/
public void configure(UserProfile profile) {
if (profile == null) {
view.showLoadError("Missing profile");
return;
}
this.profile = profile;
String displayName = DisplayUtils.getDisplayName(profile);
String shortDisplayName = maxNameLength == null ? displayName : DisplayUtils.stubStrPartialWord(displayName, maxNameLength);
view.setDisplayName(displayName, shortDisplayName);
if (description != null) {
view.showDescription(description);
} else if (isShowCompany) {
view.showDescription(profile.getCompany());
}
useCachedImage = true;
configurePicture();
}
public void configure(UserProfile profile, String description) {
this.description = description;
configure(profile);
}
public void setSize(BadgeSize size) {
view.setSize(size);
}
public void configurePicture() {
if (profile != null && profile.getProfilePicureFileHandleId() != null) {
String url = DisplayUtils.createUserProfileAttachmentUrl(synapseJSNIUtils.getBaseProfileAttachmentUrl(), profile.getOwnerId(), profile.getProfilePicureFileHandleId(), true);
if (!useCachedImage) {
url += DisplayUtils.getParamForNoCaching();
}
view.showCustomUserPicture(url);
} else {
view.showAnonymousUserPicture();
}
}
/**
* Wiki configure
*/
@Override
public void configure(WikiPageKey wikiKey, Map<String, String> widgetDescriptor, Callback widgetRefreshRequired, Long wikiVersionInView) {
//get the user id from the descriptor, and pass to the other configure
configure(widgetDescriptor.get(WidgetConstants.USERBADGE_WIDGET_ID_KEY));
}
/**
* Simple configure, without UserProfile
* @param principalId
*/
public void configure(final String principalId) {
//get user profile and configure
view.clear();
if (principalId != null && principalId.trim().length() > 0) {
view.showLoading();
getUserProfile(principalId, adapterFactory, synapseClient, clientCache, new AsyncCallback<UserProfile>() {
@Override
public void onSuccess(UserProfile result) {
configure(result);
}
@Override
public void onFailure(Throwable caught) {
view.showLoadError(principalId);
}
});
} else {
view.showLoadError("Missing user ID");
}
}
public void configure(String principalId, boolean isShowCompany) {
this.isShowCompany = isShowCompany;
configure(principalId);
}
public void configure(String principalId, String description) {
this.description = description;
configure(principalId);
}
/**
* When the username is clicked, call this clickhandler instead of the default behavior
* @param clickHandler
*/
public void setCustomClickHandler(ClickHandler clickHandler) {
customClickHandler = clickHandler;
}
@Override
public void badgeClicked(ClickEvent event) {
if (customClickHandler == null)
globalApplicationState.getPlaceChanger().goTo(new Profile(profile.getOwnerId()));
else
customClickHandler.onClick(event);
}
public static void getUserProfile(final String principalId, final AdapterFactory adapterFactory, SynapseClientAsync synapseClient, final ClientCache clientCache, final AsyncCallback<UserProfile> callback) {
String profileString = clientCache.get(principalId + WebConstants.USER_PROFILE_SUFFIX);
if (profileString != null) {
try {
UserProfile profile = new UserProfile(adapterFactory.createNew(profileString));
callback.onSuccess(profile);
return;
} catch (JSONObjectAdapterException e) {
//if any problems occur, try to get the user profile from with a rpc
}
}
synapseClient.getUserProfile(principalId, new AsyncCallback<UserProfile>() {
@Override
public void onSuccess(UserProfile result) {
JSONObjectAdapter adapter = adapterFactory.createNew();
try {
result.writeToJSONObject(adapter);
clientCache.put(principalId + WebConstants.USER_PROFILE_SUFFIX, adapter.toJSONString());
callback.onSuccess(result);
} catch (JSONObjectAdapterException e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable caught) {
callback.onFailure(caught);
}
});
}
public void clearState() {
profile = null;
description = null;
customClickHandler = null;
isShowCompany = false;
maxNameLength = null;
view.clear();
}
@Override
public Widget asWidget() {
return view.asWidget();
}
@Override
public void onImageLoadError() {
if (useCachedImage) {
//try not caching the image on load
useCachedImage = false;
configurePicture();
}
}
}
| src/main/java/org/sagebionetworks/web/client/widget/user/UserBadge.java | package org.sagebionetworks.web.client.widget.user;
import java.util.Map;
import org.sagebionetworks.repo.model.UserProfile;
import org.sagebionetworks.schema.adapter.AdapterFactory;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.web.client.DisplayUtils;
import org.sagebionetworks.web.client.GlobalApplicationState;
import org.sagebionetworks.web.client.SynapseClientAsync;
import org.sagebionetworks.web.client.SynapseJSNIUtils;
import org.sagebionetworks.web.client.cache.ClientCache;
import org.sagebionetworks.web.client.place.Profile;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.widget.SynapseWidgetPresenter;
import org.sagebionetworks.web.client.widget.WidgetRendererPresenter;
import org.sagebionetworks.web.shared.WebConstants;
import org.sagebionetworks.web.shared.WidgetConstants;
import org.sagebionetworks.web.shared.WikiPageKey;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class UserBadge implements UserBadgeView.Presenter, SynapseWidgetPresenter, WidgetRendererPresenter {
private UserBadgeView view;
SynapseClientAsync synapseClient;
private Integer maxNameLength;
UserProfile profile;
ClickHandler customClickHandler;
GlobalApplicationState globalApplicationState;
SynapseJSNIUtils synapseJSNIUtils;
boolean isShowCompany;
String description;
boolean useCachedImage;
@Inject
public UserBadge(UserBadgeView view,
SynapseClientAsync synapseClient,
GlobalApplicationState globalApplicationState,
SynapseJSNIUtils synapseJSNIUtils) {
this.view = view;
this.synapseClient = synapseClient;
this.globalApplicationState = globalApplicationState;
this.synapseJSNIUtils = synapseJSNIUtils;
view.setPresenter(this);
view.setSize(BadgeSize.SMALL);
clearState();
}
public void setMaxNameLength(Integer maxLength) {
this.maxNameLength = maxLength;
}
/**
* Simple configure, with user profile
* @param profile
*/
public void configure(UserProfile profile) {
if (profile == null) {
view.showLoadError("Missing profile");
return;
}
this.profile = profile;
String displayName = DisplayUtils.getDisplayName(profile);
String shortDisplayName = maxNameLength == null ? displayName : DisplayUtils.stubStrPartialWord(displayName, maxNameLength);
view.setDisplayName(displayName, shortDisplayName);
if (description != null) {
view.showDescription(description);
} else if (isShowCompany) {
view.showDescription(profile.getCompany());
}
useCachedImage = true;
configurePicture();
}
public void configure(UserProfile profile, String description) {
this.description = description;
configure(profile);
}
public void setSize(BadgeSize size) {
view.setSize(size);
}
public void configurePicture() {
if (profile != null && profile.getProfilePicureFileHandleId() != null) {
String url = DisplayUtils.createUserProfileAttachmentUrl(synapseJSNIUtils.getBaseProfileAttachmentUrl(), profile.getOwnerId(), profile.getProfilePicureFileHandleId(), true);
if (!useCachedImage) {
url += DisplayUtils.getParamForNoCaching();
}
view.showCustomUserPicture(url);
} else {
view.showAnonymousUserPicture();
}
}
/**
* Wiki configure
*/
@Override
public void configure(WikiPageKey wikiKey, Map<String, String> widgetDescriptor, Callback widgetRefreshRequired, Long wikiVersionInView) {
//get the user id from the descriptor, and pass to the other configure
configure(widgetDescriptor.get(WidgetConstants.USERBADGE_WIDGET_ID_KEY));
}
/**
* Simple configure, without UserProfile
* @param principalId
*/
public void configure(final String principalId) {
//get user profile and configure
view.clear();
if (principalId != null && principalId.trim().length() > 0) {
view.showLoading();
synapseClient.getUserProfile(principalId, new AsyncCallback<UserProfile>() {
@Override
public void onSuccess(UserProfile result) {
configure(result);
}
@Override
public void onFailure(Throwable caught) {
view.showLoadError(principalId);
}
});
} else {
view.showLoadError("Missing user ID");
}
}
public void configure(String principalId, boolean isShowCompany) {
this.isShowCompany = isShowCompany;
configure(principalId);
}
public void configure(String principalId, String description) {
this.description = description;
configure(principalId);
}
/**
* When the username is clicked, call this clickhandler instead of the default behavior
* @param clickHandler
*/
public void setCustomClickHandler(ClickHandler clickHandler) {
customClickHandler = clickHandler;
}
@Override
public void badgeClicked(ClickEvent event) {
if (customClickHandler == null)
globalApplicationState.getPlaceChanger().goTo(new Profile(profile.getOwnerId()));
else
customClickHandler.onClick(event);
}
public static void getUserProfile(final String principalId, final AdapterFactory adapterFactory, SynapseClientAsync synapseClient, final ClientCache clientCache, final AsyncCallback<UserProfile> callback) {
String profileString = clientCache.get(principalId + WebConstants.USER_PROFILE_SUFFIX);
if (profileString != null) {
parseProfile(profileString, adapterFactory, callback);
} else {
synapseClient.getUserProfile(principalId, new AsyncCallback<UserProfile>() {
@Override
public void onSuccess(UserProfile result) {
JSONObjectAdapter adapter = adapterFactory.createNew();
try {
result.writeToJSONObject(adapter);
clientCache.put(principalId + WebConstants.USER_PROFILE_SUFFIX, adapter.toJSONString());
callback.onSuccess(result);
} catch (JSONObjectAdapterException e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable caught) {
callback.onFailure(caught);
}
});
}
}
public static void parseProfile(String profileString, AdapterFactory adapterFactory, AsyncCallback<UserProfile> callback) {
try {
UserProfile profile = new UserProfile(adapterFactory.createNew(profileString));
callback.onSuccess(profile);
} catch (JSONObjectAdapterException e) {
callback.onFailure(e);
}
}
public void clearState() {
profile = null;
description = null;
customClickHandler = null;
isShowCompany = false;
maxNameLength = null;
view.clear();
}
@Override
public Widget asWidget() {
return view.asWidget();
}
@Override
public void onImageLoadError() {
if (useCachedImage) {
//try not caching the image on load
useCachedImage = false;
configurePicture();
}
}
}
| make user badge attempt to use local web storage for profile (if expiration is set in cache). if it fails to get from cache, go ahead with the rpc and set it in the cache
| src/main/java/org/sagebionetworks/web/client/widget/user/UserBadge.java | make user badge attempt to use local web storage for profile (if expiration is set in cache). if it fails to get from cache, go ahead with the rpc and set it in the cache | <ide><path>rc/main/java/org/sagebionetworks/web/client/widget/user/UserBadge.java
<ide> boolean isShowCompany;
<ide> String description;
<ide> boolean useCachedImage;
<add> private AdapterFactory adapterFactory;
<add> private ClientCache clientCache;
<ide>
<ide> @Inject
<ide> public UserBadge(UserBadgeView view,
<ide> SynapseClientAsync synapseClient,
<ide> GlobalApplicationState globalApplicationState,
<del> SynapseJSNIUtils synapseJSNIUtils) {
<add> SynapseJSNIUtils synapseJSNIUtils,
<add> AdapterFactory adapterFactory,
<add> ClientCache clientCache) {
<ide> this.view = view;
<ide> this.synapseClient = synapseClient;
<ide> this.globalApplicationState = globalApplicationState;
<ide> this.synapseJSNIUtils = synapseJSNIUtils;
<add> this.adapterFactory = adapterFactory;
<add> this.clientCache = clientCache;
<add>
<ide> view.setPresenter(this);
<ide> view.setSize(BadgeSize.SMALL);
<ide> clearState();
<ide> * @param principalId
<ide> */
<ide> public void configure(final String principalId) {
<add>
<ide> //get user profile and configure
<ide> view.clear();
<ide> if (principalId != null && principalId.trim().length() > 0) {
<ide> view.showLoading();
<ide>
<del> synapseClient.getUserProfile(principalId, new AsyncCallback<UserProfile>() {
<add> getUserProfile(principalId, adapterFactory, synapseClient, clientCache, new AsyncCallback<UserProfile>() {
<ide> @Override
<ide> public void onSuccess(UserProfile result) {
<ide> configure(result);
<ide> public static void getUserProfile(final String principalId, final AdapterFactory adapterFactory, SynapseClientAsync synapseClient, final ClientCache clientCache, final AsyncCallback<UserProfile> callback) {
<ide> String profileString = clientCache.get(principalId + WebConstants.USER_PROFILE_SUFFIX);
<ide> if (profileString != null) {
<del> parseProfile(profileString, adapterFactory, callback);
<del> } else {
<add> try {
<add> UserProfile profile = new UserProfile(adapterFactory.createNew(profileString));
<add> callback.onSuccess(profile);
<add> return;
<add> } catch (JSONObjectAdapterException e) {
<add> //if any problems occur, try to get the user profile from with a rpc
<add> }
<add> }
<add>
<ide> synapseClient.getUserProfile(principalId, new AsyncCallback<UserProfile>() {
<ide> @Override
<ide> public void onSuccess(UserProfile result) {
<ide> callback.onFailure(caught);
<ide> }
<ide> });
<del> }
<del> }
<del>
<del> public static void parseProfile(String profileString, AdapterFactory adapterFactory, AsyncCallback<UserProfile> callback) {
<del> try {
<del> UserProfile profile = new UserProfile(adapterFactory.createNew(profileString));
<del> callback.onSuccess(profile);
<del> } catch (JSONObjectAdapterException e) {
<del> callback.onFailure(e);
<del> }
<del>
<add>
<ide> }
<ide>
<ide> public void clearState() { |
|
Java | apache-2.0 | 9740b64ae320da8d3f5d8a2befc8eb77355d82de | 0 | ANDLABS-Git/studio-lounge-droid,lounge-io/back-up | /*
* Copyright (C) 2012 http://andlabs.eu
*
* 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 eu.andlabs.studiolounge;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import eu.andlabs.studiolounge.gcp.Lounge.LobbyListener;
public class LobbyFragment extends Fragment implements LobbyListener {
private ArrayList<Player> mPlayers = new ArrayList<Player>();
private ListView lobbyList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View lobby = inflater.inflate(R.layout.lobby, container, false);
((ListView) lobby.findViewById(R.id.list))
.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return mPlayers.size();
}
@Override
public View getView(int position, View view,
ViewGroup parent) {
if (view == null)
view = inflater.inflate(R.layout.lobby_list_entry,
null);
final TextView playerLabel = (TextView) view
.findViewById(R.id.playername);
playerLabel.setText(mPlayers.get(position)
.getPlayername());
if (mPlayers.get(position).getHostedGame() != null) {
((Button) view.findViewById(R.id.joinbtn))
.setText(mPlayers.get(position).getHostedGame());
((Button) view.findViewById(R.id.joinbtn))
.setVisibility(View.VISIBLE);
((Button) view.findViewById(R.id.joinbtn))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((LoungeMainActivity) getActivity()).mLounge
.joinGame(playerLabel
.getText()
.toString());
}
});
}
return view;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public Object getItem(int position) {
return null;
}
});
((LoungeMainActivity) getActivity()).mLounge.register(this);
lobbyList = (ListView) lobby.findViewById(R.id.list);
return lobby;
}
@Override
public void onPlayerLoggedIn(String player) {
Toast.makeText(getActivity(), player + " joined", 3000).show();
mPlayers.add(new Player(player));
((BaseAdapter) lobbyList.getAdapter()).notifyDataSetChanged();
}
@Override
public void onPlayerLeft(String player) {
Toast.makeText(getActivity(), player + " left", 3000).show();
}
@Override
public void onNewHostedGame(String player, String hostedGame) {
Log.i("io.socket", player);
for (Player p : mPlayers) {
if (p.getPlayername().equals(player)) {
p.setHostedGame(hostedGame);
((BaseAdapter) lobbyList.getAdapter()).notifyDataSetChanged();
}
}
}
@Override
public void onPlayerJoined(String player) {
Toast.makeText(getActivity(), player + " wants to join your game", Toast.LENGTH_LONG).show();
}
}
| src/eu/andlabs/studiolounge/LobbyFragment.java | /*
* Copyright (C) 2012 http://andlabs.eu
*
* 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 eu.andlabs.studiolounge;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import eu.andlabs.studiolounge.gcp.Lounge.LobbyListener;
public class LobbyFragment extends Fragment implements LobbyListener {
private ArrayList<Player> mPlayers = new ArrayList<Player>();
private ListView lobbyList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View lobby = inflater.inflate(R.layout.lobby, container, false);
((ListView) lobby.findViewById(R.id.list))
.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return mPlayers.size();
}
@Override
public View getView(int position, View view,
ViewGroup parent) {
if (view == null)
view = inflater.inflate(R.layout.lobby_list_entry,
null);
final TextView playerLabel = (TextView) view
.findViewById(R.id.playername);
playerLabel.setText(mPlayers.get(position)
.getPlayername());
if (mPlayers.get(position).getHostedGame() != null) {
((Button) view.findViewById(R.id.joinbtn))
.setVisibility(View.VISIBLE);
((Button) view.findViewById(R.id.joinbtn))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((LoungeMainActivity) getActivity()).mLounge
.joinGame(playerLabel
.getText()
.toString());
}
});
}
return view;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public Object getItem(int position) {
return null;
}
});
((LoungeMainActivity) getActivity()).mLounge.register(this);
lobbyList = (ListView) lobby.findViewById(R.id.list);
return lobby;
}
@Override
public void onPlayerLoggedIn(String player) {
Toast.makeText(getActivity(), player + " joined", 3000).show();
mPlayers.add(new Player(player));
((BaseAdapter) lobbyList.getAdapter()).notifyDataSetChanged();
}
@Override
public void onPlayerLeft(String player) {
Toast.makeText(getActivity(), player + " left", 3000).show();
}
@Override
public void onNewHostedGame(String player, String hostedGame) {
Log.i("io.socket", player);
for (Player p : mPlayers) {
if (p.getPlayername().equals(player)) {
p.setHostedGame(hostedGame);
((BaseAdapter) lobbyList.getAdapter()).notifyDataSetChanged();
}
}
}
@Override
public void onPlayerJoined(String player) {
Toast.makeText(getActivity(), player + " wants to join your game", Toast.LENGTH_LONG).show();
}
}
| show Game Name in Join Button
| src/eu/andlabs/studiolounge/LobbyFragment.java | show Game Name in Join Button | <ide><path>rc/eu/andlabs/studiolounge/LobbyFragment.java
<ide> .getPlayername());
<ide> if (mPlayers.get(position).getHostedGame() != null) {
<ide> ((Button) view.findViewById(R.id.joinbtn))
<add> .setText(mPlayers.get(position).getHostedGame());
<add> ((Button) view.findViewById(R.id.joinbtn))
<ide> .setVisibility(View.VISIBLE);
<ide> ((Button) view.findViewById(R.id.joinbtn))
<ide> .setOnClickListener(new OnClickListener() { |
|
Java | apache-2.0 | 0ed3d42ee6bfcd708cb29c7f92f1008a62b257f7 | 0 | rdoeffinger/Dictionary,rdoeffinger/Dictionary,rdoeffinger/Dictionary | // Copyright 2011 Google Inc. All Rights Reserved.
// Some Parts Copyright 2013 Dominik Köppl
// 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.hughes.android.dictionary;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.support.v7.widget.Toolbar;
import android.text.ClipboardManager;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.dictionary.engine.Dictionary;
import com.hughes.android.dictionary.engine.EntrySource;
import com.hughes.android.dictionary.engine.HtmlEntry;
import com.hughes.android.dictionary.engine.Index;
import com.hughes.android.dictionary.engine.Index.IndexEntry;
import com.hughes.android.dictionary.engine.Language.LanguageResources;
import com.hughes.android.dictionary.engine.PairEntry;
import com.hughes.android.dictionary.engine.PairEntry.Pair;
import com.hughes.android.dictionary.engine.RowBase;
import com.hughes.android.dictionary.engine.TokenRow;
import com.hughes.android.dictionary.engine.TransliteratorManager;
import com.hughes.android.util.IntentLauncher;
import com.hughes.android.util.NonLinkClickableSpan;
import com.hughes.util.StringUtil;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DictionaryActivity extends ActionBarActivity {
static final String LOG = "QuickDic";
DictionaryApplication application;
File dictFile = null;
FileChannel dictRaf = null;
String dictFileTitleName = null;
Dictionary dictionary = null;
int indexIndex = 0;
Index index = null;
List<RowBase> rowsToShow = null; // if not null, just show these rows.
final Random rand = new Random();
final Handler uiHandler = new Handler();
private final ExecutorService searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "searchExecutor");
}
});
private SearchOperation currentSearchOperation = null;
TextToSpeech textToSpeech;
volatile boolean ttsReady;
Typeface typeface;
DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
int textColorFg = Color.BLACK;
int fontSizeSp;
private ListView listView;
private ListView getListView() {
if (listView == null) {
listView = (ListView)findViewById(android.R.id.list);
}
return listView;
}
private void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
private ListAdapter getListAdapter() {
return getListView().getAdapter();
}
SearchView searchView;
ImageButton languageButton;
SearchView.OnQueryTextListener onQueryTextListener;
MenuItem nextWordMenuItem, previousWordMenuItem, randomWordMenuItem;
// Never null.
private File wordList = null;
private boolean saveOnlyFirstSubentry = false;
private boolean clickOpensContextMenu = false;
// Visible for testing.
ListAdapter indexAdapter = null;
/**
* For some languages, loading the transliterators used in this search takes
* a long time, so we fire it up on a different thread, and don't invoke it
* from the main thread until it's already finished once.
*/
private volatile boolean indexPrepFinished = false;
public DictionaryActivity() {
}
public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
final String searchToken) {
final Intent intent = new Intent(c, DictionaryActivity.class);
intent.putExtra(C.DICT_FILE, dictFile.getPath());
intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
intent.putExtra(C.SEARCH_TOKEN, searchToken);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
outState.putString(C.INDEX_SHORT_NAME, index.shortName);
outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
}
private int getMatchLen(String search, Index.IndexEntry e) {
if (e == null) return 0;
for (int i = 0; i < search.length(); ++i) {
String a = search.substring(0, i + 1);
String b = e.token.substring(0, i + 1);
if (!a.equalsIgnoreCase(b))
return i;
}
return search.length();
}
private void dictionaryOpenFail(Exception e) {
Log.e(LOG, "Unable to load dictionary.", e);
if (dictRaf != null) {
indexAdapter = null;
setListAdapter(null);
try {
dictRaf.close();
} catch (IOException e1) {
Log.e(LOG, "Unable to close dictRaf.", e1);
}
dictRaf = null;
}
Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
Toast.LENGTH_LONG).show();
startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
finish();
}
@Override
public void onCreate(Bundle savedInstanceState) {
DictionaryApplication.INSTANCE.init(getApplicationContext());
application = DictionaryApplication.INSTANCE;
// This needs to be before super.onCreate, otherwise ActionbarSherlock
// doesn't makes the background of the actionbar white when you're
// in the dark theme.
setTheme(application.getSelectedTheme().themeId);
Log.d(LOG, "onCreate:" + this);
super.onCreate(savedInstanceState);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Don't auto-launch if this fails.
prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
setContentView(R.layout.dictionary_activity);
theme = application.getSelectedTheme();
textColorFg = getResources().getColor(theme.tokenRowFgColor);
if (dictRaf != null) {
try {
dictRaf.close();
} catch (IOException e) {
Log.e(LOG, "Failed to close dictionary", e);
}
dictRaf = null;
}
final Intent intent = getIntent();
String intentAction = intent.getAction();
/**
* @author Dominik Köppl Querying the Intent
* com.hughes.action.ACTION_SEARCH_DICT is the advanced query
* Arguments: SearchManager.QUERY -> the phrase to search from
* -> language in which the phrase is written to -> to which
* language shall be translated
*/
if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT")) {
String query = intent.getStringExtra(SearchManager.QUERY);
String from = intent.getStringExtra("from");
if (from != null)
from = from.toLowerCase(Locale.US);
String to = intent.getStringExtra("to");
if (to != null)
to = to.toLowerCase(Locale.US);
if (query != null) {
getIntent().putExtra(C.SEARCH_TOKEN, query);
}
if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null)) {
Log.d(LOG, "DictSearch: from: " + from + " to " + to);
List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
for (DictionaryInfo info : dicts) {
boolean hasFrom = from == null;
boolean hasTo = to == null;
for (IndexInfo index : info.indexInfos) {
if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
hasFrom = true;
if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
hasTo = true;
}
if (hasFrom && hasTo) {
if (from != null) {
int which_index = 0;
for (; which_index < info.indexInfos.size(); ++which_index) {
if (info.indexInfos.get(which_index).shortName.toLowerCase(
Locale.US).equals(from))
break;
}
intent.putExtra(C.INDEX_SHORT_NAME,
info.indexInfos.get(which_index).shortName);
}
intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
.toString());
break;
}
}
}
}
/**
* @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
* simple query Arguments follow from android standard (see
* documentation)
*/
if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH)) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (query != null)
getIntent().putExtra(C.SEARCH_TOKEN, query);
}
if (intentAction != null && intentAction.equals(Intent.ACTION_SEND)) {
String query = intent.getStringExtra(Intent.EXTRA_TEXT);
if (query != null)
getIntent().putExtra(C.SEARCH_TOKEN, query);
}
/*
* This processes text on M+ devices where QuickDic shows up in the context menu.
*/
if (intentAction != null && intentAction.equals(Intent.ACTION_PROCESS_TEXT)) {
String query = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
if (query != null) {
getIntent().putExtra(C.SEARCH_TOKEN, query);
}
}
// Support opening dictionary file directly
if (intentAction != null && intentAction.equals(Intent.ACTION_VIEW)) {
Uri uri = intent.getData();
intent.putExtra(C.DICT_FILE, uri.toString());
dictFileTitleName = uri.getLastPathSegment();
try {
dictRaf = getContentResolver().openAssetFileDescriptor(uri, "r").createInputStream().getChannel();
} catch (Exception e) {
dictionaryOpenFail(e);
return;
}
}
/**
* @author Dominik Köppl If no dictionary is chosen, use the default
* dictionary specified in the preferences If this step does
* fail (no default dictionary specified), show a toast and
* abort.
*/
if (intent.getStringExtra(C.DICT_FILE) == null) {
String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
if (dictfile != null)
intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
}
String dictFilename = intent.getStringExtra(C.DICT_FILE);
if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null) {
final List<DictionaryInfo> dics = application.getDictionariesOnDevice(null);
final String search = intent.getStringExtra(C.SEARCH_TOKEN);
String bestFname = null;
String bestIndex = null;
int bestMatchLen = 2; // ignore shorter matches
AtomicBoolean dummy = new AtomicBoolean();
for (int i = 0; dictFilename == null && i < dics.size(); ++i) {
try {
Log.d(LOG, "Checking dictionary " + dics.get(i).uncompressedFilename);
final File dictfile = application.getPath(dics.get(i).uncompressedFilename);
Dictionary dic = new Dictionary(new RandomAccessFile(dictfile, "r").getChannel());
for (int j = 0; j < dic.indices.size(); ++j) {
Index idx = dic.indices.get(j);
Log.d(LOG, "Checking index " + idx.shortName);
if (idx.findExact(search) != null) {
Log.d(LOG, "Found exact match");
dictFilename = dictfile.toString();
intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
break;
}
int matchLen = getMatchLen(search, idx.findInsertionPoint(search, dummy));
Log.d(LOG, "Found partial match length " + matchLen);
if (matchLen > bestMatchLen) {
bestFname = dictfile.toString();
bestIndex = idx.shortName;
bestMatchLen = matchLen;
}
}
} catch (Exception e) {}
}
if (dictFilename == null && bestFname != null) {
dictFilename = bestFname;
intent.putExtra(C.INDEX_SHORT_NAME, bestIndex);
}
}
if (dictFilename == null) {
Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
finish();
return;
}
if (dictRaf == null && dictFilename != null)
dictFile = new File(dictFilename);
ttsReady = false;
textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
@Override
public void onInit(int status) {
ttsReady = true;
updateTTSLanguage(indexIndex);
}
});
try {
if (dictRaf == null) {
dictFileTitleName = application.getDictionaryName(dictFile.getName());
dictRaf = new RandomAccessFile(dictFile, "r").getChannel();
}
this.setTitle("QuickDic: " + dictFileTitleName);
dictionary = new Dictionary(dictRaf);
} catch (Exception e) {
dictionaryOpenFail(e);
return;
}
String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
}
indexIndex = 0;
for (int i = 0; i < dictionary.indices.size(); ++i) {
if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
indexIndex = i;
break;
}
}
Log.d(LOG, "Loading index " + indexIndex);
index = dictionary.indices.get(indexIndex);
getListView().setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
getListView().setEmptyView(findViewById(android.R.id.empty));
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
onListItemClick(getListView(), view, row, id);
}
});
setListAdapter(new IndexAdapter(index));
// Pre-load the Transliterator (will spawn its own thread)
TransliteratorManager.init(new TransliteratorManager.Callback() {
@Override
public void onTransliteratorReady() {
uiHandler.post(new Runnable() {
@Override
public void run() {
onSearchTextChange(searchView.getQuery().toString());
}
});
}
}, DictionaryApplication.threadBackground);
// Pre-load the collators.
new Thread(new Runnable() {
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
final long startMillis = System.currentTimeMillis();
try {
for (final Index index : dictionary.indices) {
final String searchToken = index.sortedIndexEntries.get(0).token;
final IndexEntry entry = index.findExact(searchToken);
if (entry == null || !searchToken.equals(entry.token)) {
Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
}
}
indexPrepFinished = true;
} catch (Exception e) {
Log.w(LOG,
"Exception while prepping. This can happen if dictionary is closed while search is happening.");
}
Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
}
}).start();
String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
if ("SYSTEM".equals(fontName)) {
typeface = Typeface.DEFAULT;
} else if ("SERIF".equals(fontName)) {
typeface = Typeface.SERIF;
} else if ("SANS_SERIF".equals(fontName)) {
typeface = Typeface.SANS_SERIF;
} else if ("MONOSPACE".equals(fontName)) {
typeface = Typeface.MONOSPACE;
} else {
if ("FreeSerif.ttf.jpg".equals(fontName)) {
fontName = "FreeSerif.otf.jpg";
}
try {
typeface = Typeface.createFromAsset(getAssets(), fontName);
} catch (Exception e) {
Log.w(LOG, "Exception trying to use typeface, using default.", e);
Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
Toast.LENGTH_LONG).show();
}
}
if (typeface == null) {
Log.w(LOG, "Unable to create typeface, using default.");
typeface = Typeface.DEFAULT;
}
final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
try {
fontSizeSp = Integer.parseInt(fontSize.trim());
} catch (NumberFormatException e) {
fontSizeSp = 14;
}
// ContextMenu.
registerForContextMenu(getListView());
// Cache some prefs.
wordList = application.getWordListFile();
saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
false);
clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
!getPackageManager().hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN));
Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
onCreateSetupActionBarAndSearchView();
View floatSwapButton = findViewById(R.id.floatSwapButton);
floatSwapButton.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
onLanguageButtonLongClick(v.getContext());
return true;
}
});
// Set the search text from the intent, then the saved state.
String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
if (savedInstanceState != null) {
text = savedInstanceState.getString(C.SEARCH_TOKEN);
}
if (text == null) {
text = "";
}
setSearchText(text, true);
Log.d(LOG, "Trying to restore searchText=" + text);
setDictionaryPrefs(this, dictFile, index.shortName);
updateLangButton();
searchView.requestFocus();
// http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
// getListView().setCacheColorHint(0);
}
private void onCreateSetupActionBarAndSearchView() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(false);
final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
customSearchView.setLayoutParams(layoutParams);
languageButton = new ImageButton(customSearchView.getContext());
languageButton.setId(R.id.languageButton);
languageButton.setScaleType(ScaleType.FIT_CENTER);
languageButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onLanguageButtonLongClick(v.getContext());
}
});
languageButton.setAdjustViewBounds(true);
LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
customSearchView.addView(languageButton, lpb);
searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setId(R.id.searchView);
// Get rid of search icon, it takes up too much space.
// There is still text saying "search" in the search field.
searchView.setIconifiedByDefault(true);
searchView.setIconified(false);
searchView.setQueryHint(getString(R.string.searchText));
searchView.setSubmitButtonEnabled(false);
searchView.setInputType(InputType.TYPE_CLASS_TEXT);
searchView.setImeOptions(
EditorInfo.IME_ACTION_DONE |
EditorInfo.IME_FLAG_NO_EXTRACT_UI |
// EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
// 11
EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
onQueryTextListener = new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
hideKeyboard();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
onSearchTextChange(searchView.getQuery().toString());
return true;
}
};
searchView.setOnQueryTextListener(onQueryTextListener);
searchView.setFocusable(true);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
FrameLayout.LayoutParams.WRAP_CONTENT, 1);
customSearchView.addView(searchView, lp);
actionBar.setCustomView(customSearchView);
actionBar.setDisplayShowCustomEnabled(true);
// Avoid wasting space on large left inset
Toolbar tb = (Toolbar)customSearchView.getParent();
tb.setContentInsetsRelative(0, 0);
getListView().setNextFocusLeftId(R.id.searchView);
findViewById(R.id.floatSwapButton).setNextFocusRightId(R.id.languageButton);
languageButton.setNextFocusLeftId(R.id.floatSwapButton);
}
@Override
protected void onResume() {
Log.d(LOG, "onResume");
super.onResume();
if (PreferenceActivity.prefsMightHaveChanged) {
PreferenceActivity.prefsMightHaveChanged = false;
finish();
startActivity(getIntent());
}
showKeyboard();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
/**
* Invoked when MyWebView returns, since the user might have clicked some
* hypertext in the MyWebView.
*/
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
}
}
private static void setDictionaryPrefs(final Context context, final File dictFile,
final String indexShortName) {
final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
context).edit();
if (dictFile != null) {
prefs.putString(C.DICT_FILE, dictFile.getPath());
prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
}
prefs.remove(C.SEARCH_TOKEN); // Don't need to save search token.
prefs.commit();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (dictRaf == null) {
return;
}
final SearchOperation searchOperation = currentSearchOperation;
currentSearchOperation = null;
// Before we close the RAF, we have to wind the current search down.
if (searchOperation != null) {
Log.d(LOG, "Interrupting search to shut down.");
currentSearchOperation = null;
searchOperation.interrupted.set(true);
}
searchExecutor.shutdownNow();
textToSpeech.shutdown();
textToSpeech = null;
indexAdapter = null;
setListAdapter(null);
try {
Log.d(LOG, "Closing RAF.");
dictRaf.close();
} catch (IOException e) {
Log.e(LOG, "Failed to close dictionary", e);
}
dictRaf = null;
}
// --------------------------------------------------------------------------
// Buttons
// --------------------------------------------------------------------------
private void showKeyboard() {
// For some reason, this doesn't always work the first time.
// One way to replicate the problem:
// Press the "task switch" button repeatedly to pause and resume
for (int delay = 1; delay <= 101; delay += 100) {
searchView.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(LOG, "Trying to show soft keyboard.");
final boolean searchTextHadFocus = searchView.hasFocus();
searchView.requestFocusFromTouch();
final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
if (!searchTextHadFocus) {
defocusSearchText();
}
}
}, delay);
}
}
private void hideKeyboard() {
Log.d(LOG, "Hide soft keyboard.");
searchView.clearFocus();
InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
}
void updateLangButton() {
final int flagId = IsoUtils.INSTANCE.getFlagIdForIsoCode(index.shortName);
if (flagId != 0) {
languageButton.setImageResource(flagId);
} else {
if (indexIndex % 2 == 0) {
languageButton.setImageResource(android.R.drawable.ic_media_next);
} else {
languageButton.setImageResource(android.R.drawable.ic_media_previous);
}
}
updateTTSLanguage(indexIndex);
}
private void updateTTSLanguage(int i) {
if (!ttsReady || index == null || textToSpeech == null) {
Log.d(LOG, "Can't updateTTSLanguage.");
return;
}
final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
Log.d(LOG, "Setting TTS locale to: " + locale);
try {
final int ttsResult = textToSpeech.setLanguage(locale);
if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
}
} catch (Exception e) {
Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
}
}
public void onSearchButtonClick(View dummy) {
if (!searchView.hasFocus()) {
searchView.requestFocus();
}
if (searchView.getQuery().toString().length() > 0) {
searchView.setQuery("", false);
}
showKeyboard();
searchView.setIconified(false);
}
public void onLanguageButtonClick(View dummy) {
if (dictionary.indices.size() == 1) {
// No need to work to switch indices.
return;
}
if (currentSearchOperation != null) {
currentSearchOperation.interrupted.set(true);
currentSearchOperation = null;
}
setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
searchView.getQuery().toString(), false);
}
void onLanguageButtonLongClick(final Context context) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.select_dictionary_dialog);
dialog.setTitle(R.string.selectDictionary);
final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
ListView listView = (ListView) dialog.findViewById(android.R.id.list);
final Button button = new Button(listView.getContext());
final String name = getString(R.string.dictionaryManager);
button.setText(name);
final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
@Override
protected void onGo() {
dialog.dismiss();
DictionaryActivity.this.finish();
}
};
button.setOnClickListener(intentLauncher);
listView.addHeaderView(button);
listView.setItemsCanFocus(true);
listView.setAdapter(new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final DictionaryInfo dictionaryInfo = getItem(position);
final LinearLayout result = new LinearLayout(parent.getContext());
for (int i = 0; dictionaryInfo.indexInfos != null && i < dictionaryInfo.indexInfos.size(); ++i) {
final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
final View button = IsoUtils.INSTANCE.createButton(parent.getContext(),
dictionaryInfo, indexInfo, application.languageButtonPixels);
final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
getLaunchIntent(getApplicationContext(),
application.getPath(dictionaryInfo.uncompressedFilename),
indexInfo.shortName, searchView.getQuery().toString())) {
@Override
protected void onGo() {
dialog.dismiss();
DictionaryActivity.this.finish();
}
};
button.setOnClickListener(intentLauncher);
if (i == indexIndex && dictFile != null &&
dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
button.setPressed(true);
}
result.addView(button);
}
final TextView nameView = new TextView(parent.getContext());
final String name = application
.getDictionaryName(dictionaryInfo.uncompressedFilename);
nameView.setText(name);
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.width = 0;
layoutParams.weight = 1.0f;
nameView.setLayoutParams(layoutParams);
nameView.setGravity(Gravity.CENTER_VERTICAL);
result.addView(nameView);
return result;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public DictionaryInfo getItem(int position) {
return installedDicts.get(position);
}
@Override
public int getCount() {
return installedDicts.size();
}
});
dialog.show();
}
void onUpDownButton(final boolean up) {
if (isFiltered()) {
return;
}
final int firstVisibleRow = getListView().getFirstVisiblePosition();
final RowBase row = index.rows.get(firstVisibleRow);
final TokenRow tokenRow = row.getTokenRow(true);
final int destIndexEntry;
if (up) {
if (row != tokenRow) {
destIndexEntry = tokenRow.referenceIndex;
} else {
destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
}
} else {
// Down
destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
}
final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
setSearchText(dest.token, false);
jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
defocusSearchText();
}
void onRandomWordButton() {
int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
setSearchText(dest.token, false);
jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
defocusSearchText();
}
// --------------------------------------------------------------------------
// Options Menu
// --------------------------------------------------------------------------
final Random random = new Random();
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
if (PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
// Next word.
nextWordMenuItem = menu.add(getString(R.string.nextWord))
.setIcon(R.drawable.arrow_down_float);
MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
onUpDownButton(false);
return true;
}
});
// Previous word.
previousWordMenuItem = menu.add(getString(R.string.previousWord))
.setIcon(R.drawable.arrow_up_float);
MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
onUpDownButton(true);
return true;
}
});
}
randomWordMenuItem = menu.add(getString(R.string.randomWord));
randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
onRandomWordButton();
return true;
}
});
application.onCreateGlobalOptionsMenu(this, menu);
{
final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem menuItem) {
startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
finish();
return false;
}
});
}
{
final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem menuItem) {
final Context context = getListView().getContext();
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.about_dictionary_dialog);
final TextView textView = (TextView) dialog.findViewById(R.id.text);
dialog.setTitle(dictFileTitleName);
final StringBuilder builder = new StringBuilder();
final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
if (dictionaryInfo != null) {
try {
dictionaryInfo.uncompressedBytes = dictRaf.size();
} catch (IOException e) {
}
builder.append(dictionaryInfo.dictInfo).append("\n\n");
if (dictFile != null) {
builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
.append("\n");
}
builder.append(
getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
.append("\n");
builder.append(
getString(R.string.dictionaryCreationTime,
dictionaryInfo.creationMillis)).append("\n");
for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
builder.append("\n");
builder.append(getString(R.string.indexName, indexInfo.shortName))
.append("\n");
builder.append(
getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
.append("\n");
}
builder.append("\n");
builder.append(getString(R.string.sources)).append("\n");
for (final EntrySource source : dictionary.sources) {
builder.append(
getString(R.string.sourceInfo, source.getName(),
source.getNumEntries())).append("\n");
}
}
textView.setText(builder.toString());
dialog.show();
final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.getWindow().setAttributes(layoutParams);
return false;
}
});
}
return true;
}
// --------------------------------------------------------------------------
// Context Menu + clicks
// --------------------------------------------------------------------------
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
final AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
if (clickOpensContextMenu && (row instanceof HtmlEntry.Row ||
(row instanceof TokenRow && ((TokenRow)row).getIndexEntry().htmlEntries.size() > 0))) {
final List<HtmlEntry> html = row instanceof TokenRow ? ((TokenRow)row).getIndexEntry().htmlEntries : Collections.singletonList(((HtmlEntry.Row)row).getEntry());
final String highlight = row instanceof HtmlEntry.Row ? ((HtmlEntry.Row)row).getTokenRow(true).getToken() : null;
final MenuItem open = menu.add("Open");
open.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
showHtml(html, highlight);
return false;
}
});
}
final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
wordList.getName()));
addToWordlist
.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(android.view.MenuItem item) {
onAppendToWordList(row);
return false;
}
});
final android.view.MenuItem share = menu.add("Share");
share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(android.view.MenuItem item) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
.getToken());
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
row.getRawText(saveOnlyFirstSubentry));
startActivity(shareIntent);
return false;
}
});
final android.view.MenuItem copy = menu.add(android.R.string.copy);
copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(android.view.MenuItem item) {
onCopy(row);
return false;
}
});
if (selectedSpannableText != null) {
final String selectedText = selectedSpannableText;
final android.view.MenuItem searchForSelection = menu.add(getString(
R.string.searchForSelection,
selectedSpannableText));
searchForSelection
.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(android.view.MenuItem item) {
jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
return false;
}
});
// Rats, this won't be shown:
//searchForSelection.setIcon(R.drawable.abs__ic_search);
}
if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
final android.view.MenuItem speak = menu.add(R.string.speak);
final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
new HashMap<String, String>());
return false;
}
});
}
if (row instanceof PairEntry.Row && ttsReady) {
final List<Pair> pairs = ((PairEntry.Row)row).getEntry().pairs;
final MenuItem speakLeft = menu.add(R.string.speak_left);
speakLeft.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
int idx = index.swapPairEntries ? 1 : 0;
updateTTSLanguage(idx);
String text = "";
for (Pair p : pairs) text += p.get(idx);
text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
new HashMap<String, String>());
return false;
}
});
final MenuItem speakRight = menu.add(R.string.speak_right);
speakRight.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
int idx = index.swapPairEntries ? 0 : 1;
updateTTSLanguage(idx);
String text = "";
for (Pair p : pairs) text += p.get(idx);
text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
new HashMap<String, String>());
return false;
}
});
}
}
private void jumpToTextFromHyperLink(
final String selectedText, final int defaultIndexToUse) {
int indexToUse = -1;
int numFound = 0;
for (int i = 0; i < dictionary.indices.size(); ++i) {
final Index index = dictionary.indices.get(i);
if (indexPrepFinished) {
System.out.println("Doing index lookup: on " + selectedText);
final IndexEntry indexEntry = index.findExact(selectedText);
if (indexEntry != null) {
final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
.getTokenRow(false);
if (tokenRow != null && tokenRow.hasMainEntry) {
indexToUse = i;
++numFound;
}
}
} else {
Log.w(LOG, "Skipping findExact on index " + index.shortName);
}
}
if (numFound != 1 || indexToUse == -1) {
indexToUse = defaultIndexToUse;
}
// Without this extra delay, the call to jumpToRow that this
// invokes doesn't always actually have any effect.
final int actualIndexToUse = indexToUse;
getListView().postDelayed(new Runnable() {
@Override
public void run() {
setIndexAndSearchText(actualIndexToUse, selectedText, true);
}
}, 100);
}
/**
* Called when user clicks outside of search text, so that they can start
* typing again immediately.
*/
void defocusSearchText() {
// Log.d(LOG, "defocusSearchText");
// Request focus so that if we start typing again, it clears the text
// input.
getListView().requestFocus();
// Visual indication that a new keystroke will clear the search text.
// Doesn't seem to work unless searchText has focus.
// searchView.selectAll();
}
protected void onListItemClick(ListView l, View v, int rowIdx, long id) {
defocusSearchText();
if (clickOpensContextMenu && dictRaf != null) {
openContextMenu(v);
} else {
final RowBase row = (RowBase)getListAdapter().getItem(rowIdx);
if (!(row instanceof PairEntry.Row)) {
v.performClick();
}
}
}
@SuppressLint("SimpleDateFormat")
void onAppendToWordList(final RowBase row) {
defocusSearchText();
final StringBuilder rawText = new StringBuilder();
rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
rawText.append(index.longName).append("\t");
rawText.append(row.getTokenRow(true).getToken()).append("\t");
rawText.append(row.getRawText(saveOnlyFirstSubentry));
Log.d(LOG, "Writing : " + rawText);
try {
wordList.getParentFile().mkdirs();
final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
out.println(rawText.toString());
out.close();
} catch (Exception e) {
Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
Toast.makeText(this,
getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
Toast.LENGTH_LONG).show();
}
return;
}
@SuppressWarnings("deprecation")
void onCopy(final RowBase row) {
defocusSearchText();
Log.d(LOG, "Copy, row=" + row);
final StringBuilder result = new StringBuilder();
result.append(row.getRawText(false));
final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(result.toString());
Log.d(LOG, "Copied: " + result);
}
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
if (event.getUnicodeChar() != 0) {
if (!searchView.hasFocus()) {
setSearchText("" + (char) event.getUnicodeChar(), true);
searchView.requestFocus();
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Log.d(LOG, "Clearing dictionary prefs.");
// Pretend that we just autolaunched so that we won't do it again.
// DictionaryManagerActivity.lastAutoLaunchMillis =
// System.currentTimeMillis();
}
if (keyCode == KeyEvent.KEYCODE_ENTER) {
Log.d(LOG, "Trying to hide soft keyboard.");
final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View focus = getCurrentFocus();
if (focus != null) {
inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
Log.d(LOG, "Changing index to: " + newIndex);
if (newIndex == -1) {
Log.e(LOG, "Invalid index.");
newIndex = 0;
}
if (newIndex != indexIndex) {
indexIndex = newIndex;
index = dictionary.indices.get(indexIndex);
indexAdapter = new IndexAdapter(index);
setListAdapter(indexAdapter);
Log.d(LOG, "changingIndex, newLang=" + index.longName);
setDictionaryPrefs(this, dictFile, index.shortName);
updateLangButton();
}
setSearchText(newSearchText, true, hideKeyboard);
}
private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
// Disable the listener, because sometimes it doesn't work.
searchView.setOnQueryTextListener(null);
searchView.setQuery(text, false);
moveCursorToRight();
searchView.setOnQueryTextListener(onQueryTextListener);
if (triggerSearch) {
onSearchTextChange(text);
}
// We don't want to show virtual keyboard when we're changing searchView text programatically:
if (hideKeyboard) {
hideKeyboard();
}
}
private void setSearchText(final String text, final boolean triggerSearch) {
setSearchText(text, triggerSearch, true);
}
// private long cursorDelayMillis = 100;
private void moveCursorToRight() {
// if (searchText.getLayout() != null) {
// cursorDelayMillis = 100;
// // Surprising, but this can crash when you rotate...
// Selection.moveToRightEdge(searchView.getQuery(),
// searchText.getLayout());
// } else {
// uiHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// moveCursorToRight();
// }
// }, cursorDelayMillis);
// cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
// }
}
// --------------------------------------------------------------------------
// SearchOperation
// --------------------------------------------------------------------------
private void searchFinished(final SearchOperation searchOperation) {
if (searchOperation.interrupted.get()) {
Log.d(LOG, "Search operation was interrupted: " + searchOperation);
return;
}
if (searchOperation != this.currentSearchOperation) {
Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
return;
}
final Index.IndexEntry searchResult = searchOperation.searchResult;
Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
currentSearchOperation = null;
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (currentSearchOperation == null) {
if (searchResult != null) {
if (isFiltered()) {
clearFiltered();
}
jumpToRow(searchResult.startRow);
} else if (searchOperation.multiWordSearchResult != null) {
// Multi-row search....
setFiltered(searchOperation);
} else {
throw new IllegalStateException("This should never happen.");
}
} else {
Log.d(LOG, "More coming, waiting for currentSearchOperation.");
}
}
}, 20);
}
private final void jumpToRow(final int row) {
Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
// getListView().requestFocusFromTouch();
getListView().setSelectionFromTop(row, 0);
getListView().setSelected(true);
}
static final Pattern WHITESPACE = Pattern.compile("\\s+");
final class SearchOperation implements Runnable {
final AtomicBoolean interrupted = new AtomicBoolean(false);
final String searchText;
List<String> searchTokens; // filled in for multiWord.
final Index index;
long searchStartMillis;
Index.IndexEntry searchResult;
List<RowBase> multiWordSearchResult;
boolean done = false;
SearchOperation(final String searchText, final Index index) {
this.searchText = StringUtil.normalizeWhitespace(searchText);
this.index = index;
}
public String toString() {
return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
}
@Override
public void run() {
try {
searchStartMillis = System.currentTimeMillis();
final String[] searchTokenArray = WHITESPACE.split(searchText);
if (searchTokenArray.length == 1) {
searchResult = index.findInsertionPoint(searchText, interrupted);
} else {
searchTokens = Arrays.asList(searchTokenArray);
multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
interrupted);
}
Log.d(LOG,
"searchText=" + searchText + ", searchDuration="
+ (System.currentTimeMillis() - searchStartMillis)
+ ", interrupted=" + interrupted.get());
if (!interrupted.get()) {
uiHandler.post(new Runnable() {
@Override
public void run() {
searchFinished(SearchOperation.this);
}
});
} else {
Log.d(LOG, "interrupted, skipping searchFinished.");
}
} catch (Exception e) {
Log.e(LOG, "Failure during search (can happen during Activity close.");
} finally {
synchronized (this) {
done = true;
this.notifyAll();
}
}
}
}
// --------------------------------------------------------------------------
// IndexAdapter
// --------------------------------------------------------------------------
private void showHtml(final List<HtmlEntry> htmlEntries, final String htmlTextToHighlight) {
String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
// Log.d(LOG, "html=" + html);
startActivityForResult(
HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
"<html><head><meta name=\"viewport\" content=\"width=device-width\"></head><body>%s</body></html>", html),
htmlTextToHighlight, false),
0);
}
static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
final class IndexAdapter extends BaseAdapter {
private static final float PADDING_DEFAULT_DP = 8;
private static final float PADDING_LARGE_DP = 16;
final Index index;
final List<RowBase> rows;
final Set<String> toHighlight;
private int mPaddingDefault;
private int mPaddingLarge;
IndexAdapter(final Index index) {
this.index = index;
rows = index.rows;
this.toHighlight = null;
getMetrics();
}
IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
this.index = index;
this.rows = rows;
this.toHighlight = new LinkedHashSet<String>(toHighlight);
getMetrics();
}
private void getMetrics() {
float scale = 1;
// Get the screen's density scale
// The previous method getResources().getDisplayMetrics()
// used to occasionally trigger a null pointer exception,
// so try this instead.
// As it still crashes, add a fallback
try {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
scale = dm.density;
} catch (NullPointerException e)
{}
// Convert the dps to pixels, based on density scale
mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
}
@Override
public int getCount() {
return rows.size();
}
@Override
public RowBase getItem(int position) {
return rows.get(position);
}
@Override
public long getItemId(int position) {
return getItem(position).index();
}
@Override
public int getViewTypeCount() {
return 5;
}
@Override
public int getItemViewType(int position) {
final RowBase row = getItem(position);
if (row instanceof PairEntry.Row) {
final PairEntry entry = ((PairEntry.Row)row).getEntry();
final int rowCount = entry.pairs.size();
return rowCount > 1 ? 1 : 0;
} else if (row instanceof TokenRow) {
final IndexEntry indexEntry = ((TokenRow)row).getIndexEntry();
return indexEntry.htmlEntries.isEmpty() ? 2 : 3;
} else if (row instanceof HtmlEntry.Row) {
return 4;
} else {
throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final RowBase row = getItem(position);
if (row instanceof PairEntry.Row) {
return getView(position, (PairEntry.Row) row, parent, (TableLayout)convertView);
} else if (row instanceof TokenRow) {
return getView((TokenRow) row, parent, (TextView)convertView);
} else if (row instanceof HtmlEntry.Row) {
return getView((HtmlEntry.Row) row, parent, (TextView)convertView);
} else {
throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
}
}
private void addBoldSpans(String token, String col1Text, Spannable col1Spannable) {
int startPos = 0;
while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
+ token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
startPos += token.length();
}
}
private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
TableLayout result) {
final Context context = parent.getContext();
final PairEntry entry = row.getEntry();
final int rowCount = entry.pairs.size();
if (result == null) {
result = new TableLayout(context);
result.setStretchAllColumns(true);
// Because we have a Button inside a ListView row:
// http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
result.setClickable(true);
result.setFocusable(false);
result.setLongClickable(true);
// result.setBackgroundResource(android.R.drawable.menuitem_background);
result.setBackgroundResource(theme.normalRowBg);
} else if (result.getChildCount() > rowCount) {
result.removeViews(rowCount, result.getChildCount() - rowCount);
}
for (int r = result.getChildCount(); r < rowCount; ++r) {
final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = mPaddingLarge;
final TableRow tableRow = new TableRow(result.getContext());
final TextView col1 = new TextView(tableRow.getContext());
final TextView col2 = new TextView(tableRow.getContext());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
col1.setTextIsSelectable(true);
col2.setTextIsSelectable(true);
}
col1.setTextColor(textColorFg);
col2.setTextColor(textColorFg);
// Set the columns in the table.
if (r > 0) {
final TextView bullet = new TextView(tableRow.getContext());
bullet.setText(" •");
tableRow.addView(bullet);
}
tableRow.addView(col1, layoutParams);
if (r > 0) {
final TextView bullet = new TextView(tableRow.getContext());
bullet.setText(" •");
tableRow.addView(bullet);
}
tableRow.addView(col2, layoutParams);
col1.setWidth(1);
col2.setWidth(1);
col1.setTypeface(typeface);
col2.setTypeface(typeface);
col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
// col2.setBackgroundResource(theme.otherLangBg);
if (index.swapPairEntries) {
col2.setOnLongClickListener(textViewLongClickListenerIndex0);
col1.setOnLongClickListener(textViewLongClickListenerIndex1);
} else {
col1.setOnLongClickListener(textViewLongClickListenerIndex0);
col2.setOnLongClickListener(textViewLongClickListenerIndex1);
}
result.addView(tableRow);
}
for (int r = 0; r < rowCount; ++r) {
final TableRow tableRow = (TableRow)result.getChildAt(r);
final TextView col1 = (TextView)tableRow.getChildAt(r == 0 ? 0 : 1);
final TextView col2 = (TextView)tableRow.getChildAt(r == 0 ? 1 : 3);
// Set what's in the columns.
final Pair pair = entry.pairs.get(r);
final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
final Spannable col1Spannable = new SpannableString(col1Text);
final Spannable col2Spannable = new SpannableString(col2Text);
// Bold the token instances in col1.
if (toHighlight != null) {
for (final String token : toHighlight) {
addBoldSpans(token, col1Text, col1Spannable);
}
} else
addBoldSpans(row.getTokenRow(true).getToken(), col1Text, col1Spannable);
createTokenLinkSpans(col1, col1Spannable, col1Text);
createTokenLinkSpans(col2, col2Spannable, col2Text);
col1.setText(col1Spannable);
col2.setText(col2Spannable);
}
result.setOnClickListener(new TextView.OnClickListener() {
@Override
public void onClick(View v) {
DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
}
});
return result;
}
private TextView getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
final String htmlTextToHighlight, ViewGroup parent, TextView textView) {
final Context context = parent.getContext();
if (textView == null) {
textView = new TextView(context);
// set up things invariant across one ItemViewType
// ItemViewTypes handled here are:
// 2: isTokenRow == true, htmlEntries.isEmpty() == true
// 3: isTokenRow == true, htmlEntries.isEmpty() == false
// 4: isTokenRow == false, htmlEntries.isEmpty() == false
textView.setPadding(isTokenRow ? mPaddingDefault : mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
textView.setLongClickable(true);
// Doesn't work:
// textView.setTextColor(android.R.color.secondary_text_light);
textView.setTypeface(typeface);
if (isTokenRow) {
textView.setTextAppearance(context, theme.tokenRowFg);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
} else {
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
}
if (!htmlEntries.isEmpty()) {
textView.setClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
textView.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
: theme.tokenRowOtherBg);
// Make it so we can long-click on these token rows, too:
final Spannable textSpannable = new SpannableString(text);
createTokenLinkSpans(textView, textSpannable, text);
if (!htmlEntries.isEmpty()) {
final ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
}
};
textSpannable.setSpan(clickableSpan, 0, text.length(),
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showHtml(htmlEntries, htmlTextToHighlight);
}
});
}
textView.setText(textSpannable);
return textView;
}
private TextView getView(TokenRow row, ViewGroup parent, final TextView result) {
final IndexEntry indexEntry = row.getIndexEntry();
return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
indexEntry.htmlEntries, null, parent, result);
}
private TextView getView(HtmlEntry.Row row, ViewGroup parent, final TextView result) {
final HtmlEntry htmlEntry = row.getEntry();
final TokenRow tokenRow = row.getTokenRow(true);
return getPossibleLinkToHtmlEntryView(false,
getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
result);
}
}
static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
final String text) {
// Saw from the source code that LinkMovementMethod sets the selection!
// http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
textView.setMovementMethod(LinkMovementMethod.getInstance());
final Matcher matcher = CHAR_DASH.matcher(text);
while (matcher.find()) {
spannable.setSpan(new NonLinkClickableSpan(), matcher.start(),
matcher.end(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
String selectedSpannableText = null;
int selectedSpannableIndex = -1;
@Override
public boolean onTouchEvent(MotionEvent event) {
selectedSpannableText = null;
selectedSpannableIndex = -1;
return super.onTouchEvent(event);
}
private class TextViewLongClickListener implements OnLongClickListener {
final int index;
private TextViewLongClickListener(final int index) {
this.index = index;
}
@Override
public boolean onLongClick(final View v) {
final TextView textView = (TextView) v;
final int start = textView.getSelectionStart();
final int end = textView.getSelectionEnd();
if (start >= 0 && end >= 0) {
selectedSpannableText = textView.getText().subSequence(start, end).toString();
selectedSpannableIndex = index;
}
return false;
}
}
final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
0);
final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1);
// --------------------------------------------------------------------------
// SearchText
// --------------------------------------------------------------------------
void onSearchTextChange(final String text) {
if ("thadolina".equals(text)) {
final Dialog dialog = new Dialog(getListView().getContext());
dialog.setContentView(R.layout.thadolina_dialog);
dialog.setTitle("Ti amo, amore mio!");
final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
startActivity(intent);
}
});
dialog.show();
}
if (dictRaf == null) {
Log.d(LOG, "searchText changed during shutdown, doing nothing.");
return;
}
// if (!searchView.hasFocus()) {
// Log.d(LOG, "searchText changed without focus, doing nothing.");
// return;
// }
Log.d(LOG, "onSearchTextChange: " + text);
if (currentSearchOperation != null) {
Log.d(LOG, "Interrupting currentSearchOperation.");
currentSearchOperation.interrupted.set(true);
}
currentSearchOperation = new SearchOperation(text, index);
searchExecutor.execute(currentSearchOperation);
((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
}
// --------------------------------------------------------------------------
// Filtered results.
// --------------------------------------------------------------------------
boolean isFiltered() {
return rowsToShow != null;
}
void setFiltered(final SearchOperation searchOperation) {
if (nextWordMenuItem != null) {
nextWordMenuItem.setEnabled(false);
previousWordMenuItem.setEnabled(false);
}
rowsToShow = searchOperation.multiWordSearchResult;
setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
}
void clearFiltered() {
if (nextWordMenuItem != null) {
nextWordMenuItem.setEnabled(true);
previousWordMenuItem.setEnabled(true);
}
setListAdapter(new IndexAdapter(index));
rowsToShow = null;
}
}
| src/com/hughes/android/dictionary/DictionaryActivity.java | // Copyright 2011 Google Inc. All Rights Reserved.
// Some Parts Copyright 2013 Dominik Köppl
// 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.hughes.android.dictionary;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.support.v7.widget.Toolbar;
import android.text.ClipboardManager;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.dictionary.engine.Dictionary;
import com.hughes.android.dictionary.engine.EntrySource;
import com.hughes.android.dictionary.engine.HtmlEntry;
import com.hughes.android.dictionary.engine.Index;
import com.hughes.android.dictionary.engine.Index.IndexEntry;
import com.hughes.android.dictionary.engine.Language.LanguageResources;
import com.hughes.android.dictionary.engine.PairEntry;
import com.hughes.android.dictionary.engine.PairEntry.Pair;
import com.hughes.android.dictionary.engine.RowBase;
import com.hughes.android.dictionary.engine.TokenRow;
import com.hughes.android.dictionary.engine.TransliteratorManager;
import com.hughes.android.util.IntentLauncher;
import com.hughes.android.util.NonLinkClickableSpan;
import com.hughes.util.StringUtil;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DictionaryActivity extends ActionBarActivity {
static final String LOG = "QuickDic";
DictionaryApplication application;
File dictFile = null;
FileChannel dictRaf = null;
String dictFileTitleName = null;
Dictionary dictionary = null;
int indexIndex = 0;
Index index = null;
List<RowBase> rowsToShow = null; // if not null, just show these rows.
final Random rand = new Random();
final Handler uiHandler = new Handler();
private final ExecutorService searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "searchExecutor");
}
});
private SearchOperation currentSearchOperation = null;
TextToSpeech textToSpeech;
volatile boolean ttsReady;
Typeface typeface;
DictionaryApplication.Theme theme = DictionaryApplication.Theme.LIGHT;
int textColorFg = Color.BLACK;
int fontSizeSp;
private ListView listView;
private ListView getListView() {
if (listView == null) {
listView = (ListView)findViewById(android.R.id.list);
}
return listView;
}
private void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
private ListAdapter getListAdapter() {
return getListView().getAdapter();
}
SearchView searchView;
ImageButton languageButton;
SearchView.OnQueryTextListener onQueryTextListener;
MenuItem nextWordMenuItem, previousWordMenuItem, randomWordMenuItem;
// Never null.
private File wordList = null;
private boolean saveOnlyFirstSubentry = false;
private boolean clickOpensContextMenu = false;
// Visible for testing.
ListAdapter indexAdapter = null;
/**
* For some languages, loading the transliterators used in this search takes
* a long time, so we fire it up on a different thread, and don't invoke it
* from the main thread until it's already finished once.
*/
private volatile boolean indexPrepFinished = false;
public DictionaryActivity() {
}
public static Intent getLaunchIntent(Context c, final File dictFile, final String indexShortName,
final String searchToken) {
final Intent intent = new Intent(c, DictionaryActivity.class);
intent.putExtra(C.DICT_FILE, dictFile.getPath());
intent.putExtra(C.INDEX_SHORT_NAME, indexShortName);
intent.putExtra(C.SEARCH_TOKEN, searchToken);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(LOG, "onSaveInstanceState: " + searchView.getQuery().toString());
outState.putString(C.INDEX_SHORT_NAME, index.shortName);
outState.putString(C.SEARCH_TOKEN, searchView.getQuery().toString());
}
private int getMatchLen(String search, Index.IndexEntry e) {
if (e == null) return 0;
for (int i = 0; i < search.length(); ++i) {
String a = search.substring(0, i + 1);
String b = e.token.substring(0, i + 1);
if (!a.equalsIgnoreCase(b))
return i;
}
return search.length();
}
private void dictionaryOpenFail(Exception e) {
Log.e(LOG, "Unable to load dictionary.", e);
if (dictRaf != null) {
indexAdapter = null;
setListAdapter(null);
try {
dictRaf.close();
} catch (IOException e1) {
Log.e(LOG, "Unable to close dictRaf.", e1);
}
dictRaf = null;
}
Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()),
Toast.LENGTH_LONG).show();
startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
finish();
}
@Override
public void onCreate(Bundle savedInstanceState) {
DictionaryApplication.INSTANCE.init(getApplicationContext());
application = DictionaryApplication.INSTANCE;
// This needs to be before super.onCreate, otherwise ActionbarSherlock
// doesn't makes the background of the actionbar white when you're
// in the dark theme.
setTheme(application.getSelectedTheme().themeId);
Log.d(LOG, "onCreate:" + this);
super.onCreate(savedInstanceState);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Don't auto-launch if this fails.
prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
setContentView(R.layout.dictionary_activity);
theme = application.getSelectedTheme();
textColorFg = getResources().getColor(theme.tokenRowFgColor);
if (dictRaf != null) {
try {
dictRaf.close();
} catch (IOException e) {
Log.e(LOG, "Failed to close dictionary", e);
}
dictRaf = null;
}
final Intent intent = getIntent();
String intentAction = intent.getAction();
/**
* @author Dominik Köppl Querying the Intent
* com.hughes.action.ACTION_SEARCH_DICT is the advanced query
* Arguments: SearchManager.QUERY -> the phrase to search from
* -> language in which the phrase is written to -> to which
* language shall be translated
*/
if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT")) {
String query = intent.getStringExtra(SearchManager.QUERY);
String from = intent.getStringExtra("from");
if (from != null)
from = from.toLowerCase(Locale.US);
String to = intent.getStringExtra("to");
if (to != null)
to = to.toLowerCase(Locale.US);
if (query != null) {
getIntent().putExtra(C.SEARCH_TOKEN, query);
}
if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null)) {
Log.d(LOG, "DictSearch: from: " + from + " to " + to);
List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
for (DictionaryInfo info : dicts) {
boolean hasFrom = from == null;
boolean hasTo = to == null;
for (IndexInfo index : info.indexInfos) {
if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
hasFrom = true;
if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
hasTo = true;
}
if (hasFrom && hasTo) {
if (from != null) {
int which_index = 0;
for (; which_index < info.indexInfos.size(); ++which_index) {
if (info.indexInfos.get(which_index).shortName.toLowerCase(
Locale.US).equals(from))
break;
}
intent.putExtra(C.INDEX_SHORT_NAME,
info.indexInfos.get(which_index).shortName);
}
intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename)
.toString());
break;
}
}
}
}
/**
* @author Dominik Köppl Querying the Intent Intent.ACTION_SEARCH is a
* simple query Arguments follow from android standard (see
* documentation)
*/
if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH)) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (query != null)
getIntent().putExtra(C.SEARCH_TOKEN, query);
}
if (intentAction != null && intentAction.equals(Intent.ACTION_SEND)) {
String query = intent.getStringExtra(Intent.EXTRA_TEXT);
if (query != null)
getIntent().putExtra(C.SEARCH_TOKEN, query);
}
/*
* This processes text on M+ devices where QuickDic shows up in the context menu.
*/
if (intentAction != null && intentAction.equals(Intent.ACTION_PROCESS_TEXT)) {
String query = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT);
if (query != null) {
getIntent().putExtra(C.SEARCH_TOKEN, query);
}
}
// Support opening dictionary file directly
if (intentAction != null && intentAction.equals(Intent.ACTION_VIEW)) {
Uri uri = intent.getData();
intent.putExtra(C.DICT_FILE, uri.toString());
dictFileTitleName = uri.getLastPathSegment();
try {
dictRaf = getContentResolver().openAssetFileDescriptor(uri, "r").createInputStream().getChannel();
} catch (Exception e) {
dictionaryOpenFail(e);
return;
}
}
/**
* @author Dominik Köppl If no dictionary is chosen, use the default
* dictionary specified in the preferences If this step does
* fail (no default dictionary specified), show a toast and
* abort.
*/
if (intent.getStringExtra(C.DICT_FILE) == null) {
String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
if (dictfile != null)
intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
}
String dictFilename = intent.getStringExtra(C.DICT_FILE);
if (dictFilename == null && intent.getStringExtra(C.SEARCH_TOKEN) != null) {
final List<DictionaryInfo> dics = application.getDictionariesOnDevice(null);
final String search = intent.getStringExtra(C.SEARCH_TOKEN);
String bestFname = null;
String bestIndex = null;
int bestMatchLen = 2; // ignore shorter matches
AtomicBoolean dummy = new AtomicBoolean();
for (int i = 0; dictFilename == null && i < dics.size(); ++i) {
try {
Log.d(LOG, "Checking dictionary " + dics.get(i).uncompressedFilename);
final File dictfile = application.getPath(dics.get(i).uncompressedFilename);
Dictionary dic = new Dictionary(new RandomAccessFile(dictfile, "r").getChannel());
for (int j = 0; j < dic.indices.size(); ++j) {
Index idx = dic.indices.get(j);
Log.d(LOG, "Checking index " + idx.shortName);
if (idx.findExact(search) != null) {
Log.d(LOG, "Found exact match");
dictFilename = dictfile.toString();
intent.putExtra(C.INDEX_SHORT_NAME, idx.shortName);
break;
}
int matchLen = getMatchLen(search, idx.findInsertionPoint(search, dummy));
Log.d(LOG, "Found partial match length " + matchLen);
if (matchLen > bestMatchLen) {
bestFname = dictfile.toString();
bestIndex = idx.shortName;
bestMatchLen = matchLen;
}
}
} catch (Exception e) {}
}
if (dictFilename == null && bestFname != null) {
dictFilename = bestFname;
intent.putExtra(C.INDEX_SHORT_NAME, bestIndex);
}
}
if (dictFilename == null) {
Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
finish();
return;
}
if (dictRaf == null && dictFilename != null)
dictFile = new File(dictFilename);
ttsReady = false;
textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
@Override
public void onInit(int status) {
ttsReady = true;
updateTTSLanguage(indexIndex);
}
});
try {
if (dictRaf == null) {
dictFileTitleName = application.getDictionaryName(dictFile.getName());
dictRaf = new RandomAccessFile(dictFile, "r").getChannel();
}
this.setTitle("QuickDic: " + dictFileTitleName);
dictionary = new Dictionary(dictRaf);
} catch (Exception e) {
dictionaryOpenFail(e);
return;
}
String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
}
indexIndex = 0;
for (int i = 0; i < dictionary.indices.size(); ++i) {
if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
indexIndex = i;
break;
}
}
Log.d(LOG, "Loading index " + indexIndex);
index = dictionary.indices.get(indexIndex);
getListView().setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
getListView().setEmptyView(findViewById(android.R.id.empty));
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int row, long id) {
onListItemClick(getListView(), view, row, id);
}
});
setListAdapter(new IndexAdapter(index));
// Pre-load the Transliterator (will spawn its own thread)
TransliteratorManager.init(new TransliteratorManager.Callback() {
@Override
public void onTransliteratorReady() {
uiHandler.post(new Runnable() {
@Override
public void run() {
onSearchTextChange(searchView.getQuery().toString());
}
});
}
}, DictionaryApplication.threadBackground);
// Pre-load the collators.
new Thread(new Runnable() {
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
final long startMillis = System.currentTimeMillis();
try {
for (final Index index : dictionary.indices) {
final String searchToken = index.sortedIndexEntries.get(0).token;
final IndexEntry entry = index.findExact(searchToken);
if (entry == null || !searchToken.equals(entry.token)) {
Log.e(LOG, "Couldn't find token: " + searchToken + ", " + (entry == null ? "null" : entry.token));
}
}
indexPrepFinished = true;
} catch (Exception e) {
Log.w(LOG,
"Exception while prepping. This can happen if dictionary is closed while search is happening.");
}
Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
}
}).start();
String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
if ("SYSTEM".equals(fontName)) {
typeface = Typeface.DEFAULT;
} else if ("SERIF".equals(fontName)) {
typeface = Typeface.SERIF;
} else if ("SANS_SERIF".equals(fontName)) {
typeface = Typeface.SANS_SERIF;
} else if ("MONOSPACE".equals(fontName)) {
typeface = Typeface.MONOSPACE;
} else {
if ("FreeSerif.ttf.jpg".equals(fontName)) {
fontName = "FreeSerif.otf.jpg";
}
try {
typeface = Typeface.createFromAsset(getAssets(), fontName);
} catch (Exception e) {
Log.w(LOG, "Exception trying to use typeface, using default.", e);
Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()),
Toast.LENGTH_LONG).show();
}
}
if (typeface == null) {
Log.w(LOG, "Unable to create typeface, using default.");
typeface = Typeface.DEFAULT;
}
final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
try {
fontSizeSp = Integer.parseInt(fontSize.trim());
} catch (NumberFormatException e) {
fontSizeSp = 14;
}
// ContextMenu.
registerForContextMenu(getListView());
// Cache some prefs.
wordList = application.getWordListFile();
saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey),
false);
clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey),
!getPackageManager().hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN));
Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
onCreateSetupActionBarAndSearchView();
View floatSwapButton = findViewById(R.id.floatSwapButton);
floatSwapButton.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
onLanguageButtonLongClick(v.getContext());
return true;
}
});
// Set the search text from the intent, then the saved state.
String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
if (savedInstanceState != null) {
text = savedInstanceState.getString(C.SEARCH_TOKEN);
}
if (text == null) {
text = "";
}
setSearchText(text, true);
Log.d(LOG, "Trying to restore searchText=" + text);
setDictionaryPrefs(this, dictFile, index.shortName);
updateLangButton();
searchView.requestFocus();
// http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
// getListView().setCacheColorHint(0);
}
private void onCreateSetupActionBarAndSearchView() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(false);
final LinearLayout customSearchView = new LinearLayout(getSupportActionBar().getThemedContext());
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
customSearchView.setLayoutParams(layoutParams);
languageButton = new ImageButton(customSearchView.getContext());
languageButton.setId(R.id.languageButton);
languageButton.setScaleType(ScaleType.FIT_CENTER);
languageButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onLanguageButtonLongClick(v.getContext());
}
});
languageButton.setAdjustViewBounds(true);
LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(application.languageButtonPixels, LinearLayout.LayoutParams.MATCH_PARENT);
customSearchView.addView(languageButton, lpb);
searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setId(R.id.searchView);
// Get rid of search icon, it takes up too much space.
// There is still text saying "search" in the search field.
searchView.setIconifiedByDefault(true);
searchView.setIconified(false);
searchView.setQueryHint(getString(R.string.searchText));
searchView.setSubmitButtonEnabled(false);
searchView.setInputType(InputType.TYPE_CLASS_TEXT);
searchView.setImeOptions(
EditorInfo.IME_ACTION_DONE |
EditorInfo.IME_FLAG_NO_EXTRACT_UI |
// EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
// 11
EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
onQueryTextListener = new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Log.d(LOG, "OnQueryTextListener: onQueryTextSubmit: " + searchView.getQuery());
hideKeyboard();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
Log.d(LOG, "OnQueryTextListener: onQueryTextChange: " + searchView.getQuery());
onSearchTextChange(searchView.getQuery().toString());
return true;
}
};
searchView.setOnQueryTextListener(onQueryTextListener);
searchView.setFocusable(true);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0,
FrameLayout.LayoutParams.WRAP_CONTENT, 1);
customSearchView.addView(searchView, lp);
actionBar.setCustomView(customSearchView);
actionBar.setDisplayShowCustomEnabled(true);
// Avoid wasting space on large left inset
Toolbar tb = (Toolbar)customSearchView.getParent();
tb.setContentInsetsRelative(0, 0);
getListView().setNextFocusLeftId(R.id.searchView);
findViewById(R.id.floatSwapButton).setNextFocusRightId(R.id.languageButton);
languageButton.setNextFocusLeftId(R.id.floatSwapButton);
}
@Override
protected void onResume() {
Log.d(LOG, "onResume");
super.onResume();
if (PreferenceActivity.prefsMightHaveChanged) {
PreferenceActivity.prefsMightHaveChanged = false;
finish();
startActivity(getIntent());
}
showKeyboard();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
/**
* Invoked when MyWebView returns, since the user might have clicked some
* hypertext in the MyWebView.
*/
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
if (result != null && result.hasExtra(C.SEARCH_TOKEN)) {
Log.d(LOG, "onActivityResult: " + result.getStringExtra(C.SEARCH_TOKEN));
jumpToTextFromHyperLink(result.getStringExtra(C.SEARCH_TOKEN), indexIndex);
}
}
private static void setDictionaryPrefs(final Context context, final File dictFile,
final String indexShortName) {
final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(
context).edit();
if (dictFile != null) {
prefs.putString(C.DICT_FILE, dictFile.getPath());
prefs.putString(C.INDEX_SHORT_NAME, indexShortName);
}
prefs.remove(C.SEARCH_TOKEN); // Don't need to save search token.
prefs.commit();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (dictRaf == null) {
return;
}
final SearchOperation searchOperation = currentSearchOperation;
currentSearchOperation = null;
// Before we close the RAF, we have to wind the current search down.
if (searchOperation != null) {
Log.d(LOG, "Interrupting search to shut down.");
currentSearchOperation = null;
searchOperation.interrupted.set(true);
}
searchExecutor.shutdownNow();
textToSpeech.shutdown();
textToSpeech = null;
indexAdapter = null;
setListAdapter(null);
try {
Log.d(LOG, "Closing RAF.");
dictRaf.close();
} catch (IOException e) {
Log.e(LOG, "Failed to close dictionary", e);
}
dictRaf = null;
}
// --------------------------------------------------------------------------
// Buttons
// --------------------------------------------------------------------------
private void showKeyboard() {
// For some reason, this doesn't always work the first time.
// One way to replicate the problem:
// Press the "task switch" button repeatedly to pause and resume
for (int delay = 1; delay <= 101; delay += 100) {
searchView.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(LOG, "Trying to show soft keyboard.");
final boolean searchTextHadFocus = searchView.hasFocus();
searchView.requestFocusFromTouch();
final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
if (!searchTextHadFocus) {
defocusSearchText();
}
}
}, delay);
}
}
private void hideKeyboard() {
Log.d(LOG, "Hide soft keyboard.");
searchView.clearFocus();
InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
}
void updateLangButton() {
final int flagId = IsoUtils.INSTANCE.getFlagIdForIsoCode(index.shortName);
if (flagId != 0) {
languageButton.setImageResource(flagId);
} else {
if (indexIndex % 2 == 0) {
languageButton.setImageResource(android.R.drawable.ic_media_next);
} else {
languageButton.setImageResource(android.R.drawable.ic_media_previous);
}
}
updateTTSLanguage(indexIndex);
}
private void updateTTSLanguage(int i) {
if (!ttsReady || index == null || textToSpeech == null) {
Log.d(LOG, "Can't updateTTSLanguage.");
return;
}
final Locale locale = new Locale(dictionary.indices.get(i).sortLanguage.getIsoCode());
Log.d(LOG, "Setting TTS locale to: " + locale);
try {
final int ttsResult = textToSpeech.setLanguage(locale);
if (ttsResult != TextToSpeech.LANG_AVAILABLE &&
ttsResult != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
Log.e(LOG, "TTS not available in this language: ttsResult=" + ttsResult);
}
} catch (Exception e) {
Toast.makeText(this, getString(R.string.TTSbroken), Toast.LENGTH_LONG).show();
}
}
public void onSearchButtonClick(View dummy) {
if (!searchView.hasFocus()) {
searchView.requestFocus();
}
if (searchView.getQuery().toString().length() > 0) {
searchView.setQuery("", false);
}
showKeyboard();
searchView.setIconified(false);
}
public void onLanguageButtonClick(View dummy) {
if (dictionary.indices.size() == 1) {
// No need to work to switch indices.
return;
}
if (currentSearchOperation != null) {
currentSearchOperation.interrupted.set(true);
currentSearchOperation = null;
}
setIndexAndSearchText((indexIndex + 1) % dictionary.indices.size(),
searchView.getQuery().toString(), false);
}
void onLanguageButtonLongClick(final Context context) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.select_dictionary_dialog);
dialog.setTitle(R.string.selectDictionary);
final List<DictionaryInfo> installedDicts = application.getDictionariesOnDevice(null);
ListView listView = (ListView) dialog.findViewById(android.R.id.list);
final Button button = new Button(listView.getContext());
final String name = getString(R.string.dictionaryManager);
button.setText(name);
final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(),
DictionaryManagerActivity.getLaunchIntent(getApplicationContext())) {
@Override
protected void onGo() {
dialog.dismiss();
DictionaryActivity.this.finish();
}
};
button.setOnClickListener(intentLauncher);
listView.addHeaderView(button);
listView.setItemsCanFocus(true);
listView.setAdapter(new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final DictionaryInfo dictionaryInfo = getItem(position);
final LinearLayout result = new LinearLayout(parent.getContext());
for (int i = 0; dictionaryInfo.indexInfos != null && i < dictionaryInfo.indexInfos.size(); ++i) {
final IndexInfo indexInfo = dictionaryInfo.indexInfos.get(i);
final View button = IsoUtils.INSTANCE.createButton(parent.getContext(),
dictionaryInfo, indexInfo, application.languageButtonPixels);
final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(),
getLaunchIntent(getApplicationContext(),
application.getPath(dictionaryInfo.uncompressedFilename),
indexInfo.shortName, searchView.getQuery().toString())) {
@Override
protected void onGo() {
dialog.dismiss();
DictionaryActivity.this.finish();
}
};
button.setOnClickListener(intentLauncher);
if (i == indexIndex && dictFile != null &&
dictFile.getName().equals(dictionaryInfo.uncompressedFilename)) {
button.setPressed(true);
}
result.addView(button);
}
final TextView nameView = new TextView(parent.getContext());
final String name = application
.getDictionaryName(dictionaryInfo.uncompressedFilename);
nameView.setText(name);
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.width = 0;
layoutParams.weight = 1.0f;
nameView.setLayoutParams(layoutParams);
nameView.setGravity(Gravity.CENTER_VERTICAL);
result.addView(nameView);
return result;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public DictionaryInfo getItem(int position) {
return installedDicts.get(position);
}
@Override
public int getCount() {
return installedDicts.size();
}
});
dialog.show();
}
void onUpDownButton(final boolean up) {
if (isFiltered()) {
return;
}
final int firstVisibleRow = getListView().getFirstVisiblePosition();
final RowBase row = index.rows.get(firstVisibleRow);
final TokenRow tokenRow = row.getTokenRow(true);
final int destIndexEntry;
if (up) {
if (row != tokenRow) {
destIndexEntry = tokenRow.referenceIndex;
} else {
destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
}
} else {
// Down
destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size() - 1);
}
final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
setSearchText(dest.token, false);
jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
defocusSearchText();
}
void onRandomWordButton() {
int destIndexEntry = rand.nextInt(index.sortedIndexEntries.size());
final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
setSearchText(dest.token, false);
jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
defocusSearchText();
}
// --------------------------------------------------------------------------
// Options Menu
// --------------------------------------------------------------------------
final Random random = new Random();
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
if (PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean(getString(R.string.showPrevNextButtonsKey), true)) {
// Next word.
nextWordMenuItem = menu.add(getString(R.string.nextWord))
.setIcon(R.drawable.arrow_down_float);
MenuItemCompat.setShowAsAction(nextWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
nextWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
onUpDownButton(false);
return true;
}
});
// Previous word.
previousWordMenuItem = menu.add(getString(R.string.previousWord))
.setIcon(R.drawable.arrow_up_float);
MenuItemCompat.setShowAsAction(previousWordMenuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
previousWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
onUpDownButton(true);
return true;
}
});
}
randomWordMenuItem = menu.add(getString(R.string.randomWord));
randomWordMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
onRandomWordButton();
return true;
}
});
application.onCreateGlobalOptionsMenu(this, menu);
{
final MenuItem dictionaryManager = menu.add(getString(R.string.dictionaryManager));
MenuItemCompat.setShowAsAction(dictionaryManager, MenuItem.SHOW_AS_ACTION_NEVER);
dictionaryManager.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem menuItem) {
startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
finish();
return false;
}
});
}
{
final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
MenuItemCompat.setShowAsAction(aboutDictionary, MenuItem.SHOW_AS_ACTION_NEVER);
aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem menuItem) {
final Context context = getListView().getContext();
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.about_dictionary_dialog);
final TextView textView = (TextView) dialog.findViewById(R.id.text);
dialog.setTitle(dictFileTitleName);
final StringBuilder builder = new StringBuilder();
final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
if (dictionaryInfo != null) {
try {
dictionaryInfo.uncompressedBytes = dictRaf.size();
} catch (IOException e) {
}
builder.append(dictionaryInfo.dictInfo).append("\n\n");
if (dictFile != null) {
builder.append(getString(R.string.dictionaryPath, dictFile.getPath()))
.append("\n");
}
builder.append(
getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes))
.append("\n");
builder.append(
getString(R.string.dictionaryCreationTime,
dictionaryInfo.creationMillis)).append("\n");
for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
builder.append("\n");
builder.append(getString(R.string.indexName, indexInfo.shortName))
.append("\n");
builder.append(
getString(R.string.mainTokenCount, indexInfo.mainTokenCount))
.append("\n");
}
builder.append("\n");
builder.append(getString(R.string.sources)).append("\n");
for (final EntrySource source : dictionary.sources) {
builder.append(
getString(R.string.sourceInfo, source.getName(),
source.getNumEntries())).append("\n");
}
}
textView.setText(builder.toString());
dialog.show();
final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.getWindow().setAttributes(layoutParams);
return false;
}
});
}
return true;
}
// --------------------------------------------------------------------------
// Context Menu + clicks
// --------------------------------------------------------------------------
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
final AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
if (clickOpensContextMenu && (row instanceof HtmlEntry.Row ||
(row instanceof TokenRow && ((TokenRow)row).getIndexEntry().htmlEntries.size() > 0))) {
final List<HtmlEntry> html = row instanceof TokenRow ? ((TokenRow)row).getIndexEntry().htmlEntries : Collections.singletonList(((HtmlEntry.Row)row).getEntry());
final String highlight = row instanceof HtmlEntry.Row ? ((HtmlEntry.Row)row).getTokenRow(true).getToken() : null;
final MenuItem open = menu.add("Open");
open.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
showHtml(html, highlight);
return false;
}
});
}
final android.view.MenuItem addToWordlist = menu.add(getString(R.string.addToWordList,
wordList.getName()));
addToWordlist
.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(android.view.MenuItem item) {
onAppendToWordList(row);
return false;
}
});
final android.view.MenuItem share = menu.add("Share");
share.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(android.view.MenuItem item) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, row.getTokenRow(true)
.getToken());
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
row.getRawText(saveOnlyFirstSubentry));
startActivity(shareIntent);
return false;
}
});
final android.view.MenuItem copy = menu.add(android.R.string.copy);
copy.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(android.view.MenuItem item) {
onCopy(row);
return false;
}
});
if (selectedSpannableText != null) {
final String selectedText = selectedSpannableText;
final android.view.MenuItem searchForSelection = menu.add(getString(
R.string.searchForSelection,
selectedSpannableText));
searchForSelection
.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
public boolean onMenuItemClick(android.view.MenuItem item) {
jumpToTextFromHyperLink(selectedText, selectedSpannableIndex);
return false;
}
});
// Rats, this won't be shown:
//searchForSelection.setIcon(R.drawable.abs__ic_search);
}
if ((row instanceof TokenRow || selectedSpannableText != null) && ttsReady) {
final android.view.MenuItem speak = menu.add(R.string.speak);
final String textToSpeak = row instanceof TokenRow ? ((TokenRow) row).getToken() : selectedSpannableText;
updateTTSLanguage(row instanceof TokenRow ? indexIndex : selectedSpannableIndex);
speak.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH,
new HashMap<String, String>());
return false;
}
});
}
if (row instanceof PairEntry.Row && ttsReady) {
final List<Pair> pairs = ((PairEntry.Row)row).getEntry().pairs;
final MenuItem speakLeft = menu.add(R.string.speak_left);
speakLeft.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
int idx = index.swapPairEntries ? 1 : 0;
updateTTSLanguage(idx);
String text = "";
for (Pair p : pairs) text += p.get(idx);
text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
new HashMap<String, String>());
return false;
}
});
final MenuItem speakRight = menu.add(R.string.speak_right);
speakRight.setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
int idx = index.swapPairEntries ? 0 : 1;
updateTTSLanguage(idx);
String text = "";
for (Pair p : pairs) text += p.get(idx);
text = text.replaceAll("\\{[^{}]*\\}", "").replace("{", "").replace("}", "");
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,
new HashMap<String, String>());
return false;
}
});
}
}
private void jumpToTextFromHyperLink(
final String selectedText, final int defaultIndexToUse) {
int indexToUse = -1;
int numFound = 0;
for (int i = 0; i < dictionary.indices.size(); ++i) {
final Index index = dictionary.indices.get(i);
if (indexPrepFinished) {
System.out.println("Doing index lookup: on " + selectedText);
final IndexEntry indexEntry = index.findExact(selectedText);
if (indexEntry != null) {
final TokenRow tokenRow = index.rows.get(indexEntry.startRow)
.getTokenRow(false);
if (tokenRow != null && tokenRow.hasMainEntry) {
indexToUse = i;
++numFound;
}
}
} else {
Log.w(LOG, "Skipping findExact on index " + index.shortName);
}
}
if (numFound != 1 || indexToUse == -1) {
indexToUse = defaultIndexToUse;
}
// Without this extra delay, the call to jumpToRow that this
// invokes doesn't always actually have any effect.
final int actualIndexToUse = indexToUse;
getListView().postDelayed(new Runnable() {
@Override
public void run() {
setIndexAndSearchText(actualIndexToUse, selectedText, true);
}
}, 100);
}
/**
* Called when user clicks outside of search text, so that they can start
* typing again immediately.
*/
void defocusSearchText() {
// Log.d(LOG, "defocusSearchText");
// Request focus so that if we start typing again, it clears the text
// input.
getListView().requestFocus();
// Visual indication that a new keystroke will clear the search text.
// Doesn't seem to work unless searchText has focus.
// searchView.selectAll();
}
protected void onListItemClick(ListView l, View v, int rowIdx, long id) {
defocusSearchText();
if (clickOpensContextMenu && dictRaf != null) {
openContextMenu(v);
} else {
final RowBase row = (RowBase)getListAdapter().getItem(rowIdx);
if (!(row instanceof PairEntry.Row)) {
v.performClick();
}
}
}
@SuppressLint("SimpleDateFormat")
void onAppendToWordList(final RowBase row) {
defocusSearchText();
final StringBuilder rawText = new StringBuilder();
rawText.append(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())).append("\t");
rawText.append(index.longName).append("\t");
rawText.append(row.getTokenRow(true).getToken()).append("\t");
rawText.append(row.getRawText(saveOnlyFirstSubentry));
Log.d(LOG, "Writing : " + rawText);
try {
wordList.getParentFile().mkdirs();
final PrintWriter out = new PrintWriter(new FileWriter(wordList, true));
out.println(rawText.toString());
out.close();
} catch (Exception e) {
Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
Toast.makeText(this,
getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()),
Toast.LENGTH_LONG).show();
}
return;
}
@SuppressWarnings("deprecation")
void onCopy(final RowBase row) {
defocusSearchText();
Log.d(LOG, "Copy, row=" + row);
final StringBuilder result = new StringBuilder();
result.append(row.getRawText(false));
final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(result.toString());
Log.d(LOG, "Copied: " + result);
}
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
if (event.getUnicodeChar() != 0) {
if (!searchView.hasFocus()) {
setSearchText("" + (char) event.getUnicodeChar(), true);
searchView.requestFocus();
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Log.d(LOG, "Clearing dictionary prefs.");
// Pretend that we just autolaunched so that we won't do it again.
// DictionaryManagerActivity.lastAutoLaunchMillis =
// System.currentTimeMillis();
}
if (keyCode == KeyEvent.KEYCODE_ENTER) {
Log.d(LOG, "Trying to hide soft keyboard.");
final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View focus = getCurrentFocus();
if (focus != null) {
inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private void setIndexAndSearchText(int newIndex, String newSearchText, boolean hideKeyboard) {
Log.d(LOG, "Changing index to: " + newIndex);
if (newIndex == -1) {
Log.e(LOG, "Invalid index.");
newIndex = 0;
}
if (newIndex != indexIndex) {
indexIndex = newIndex;
index = dictionary.indices.get(indexIndex);
indexAdapter = new IndexAdapter(index);
setListAdapter(indexAdapter);
Log.d(LOG, "changingIndex, newLang=" + index.longName);
setDictionaryPrefs(this, dictFile, index.shortName);
updateLangButton();
}
setSearchText(newSearchText, true, hideKeyboard);
}
private void setSearchText(final String text, final boolean triggerSearch, boolean hideKeyboard) {
Log.d(LOG, "setSearchText, text=" + text + ", triggerSearch=" + triggerSearch);
// Disable the listener, because sometimes it doesn't work.
searchView.setOnQueryTextListener(null);
searchView.setQuery(text, false);
moveCursorToRight();
searchView.setOnQueryTextListener(onQueryTextListener);
if (triggerSearch) {
onSearchTextChange(text);
}
// We don't want to show virtual keyboard when we're changing searchView text programatically:
if (hideKeyboard) {
hideKeyboard();
}
}
private void setSearchText(final String text, final boolean triggerSearch) {
setSearchText(text, triggerSearch, true);
}
// private long cursorDelayMillis = 100;
private void moveCursorToRight() {
// if (searchText.getLayout() != null) {
// cursorDelayMillis = 100;
// // Surprising, but this can crash when you rotate...
// Selection.moveToRightEdge(searchView.getQuery(),
// searchText.getLayout());
// } else {
// uiHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// moveCursorToRight();
// }
// }, cursorDelayMillis);
// cursorDelayMillis = Math.min(10 * 1000, 2 * cursorDelayMillis);
// }
}
// --------------------------------------------------------------------------
// SearchOperation
// --------------------------------------------------------------------------
private void searchFinished(final SearchOperation searchOperation) {
if (searchOperation.interrupted.get()) {
Log.d(LOG, "Search operation was interrupted: " + searchOperation);
return;
}
if (searchOperation != this.currentSearchOperation) {
Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
return;
}
final Index.IndexEntry searchResult = searchOperation.searchResult;
Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
currentSearchOperation = null;
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (currentSearchOperation == null) {
if (searchResult != null) {
if (isFiltered()) {
clearFiltered();
}
jumpToRow(searchResult.startRow);
} else if (searchOperation.multiWordSearchResult != null) {
// Multi-row search....
setFiltered(searchOperation);
} else {
throw new IllegalStateException("This should never happen.");
}
} else {
Log.d(LOG, "More coming, waiting for currentSearchOperation.");
}
}
}, 20);
}
private final void jumpToRow(final int row) {
Log.d(LOG, "jumpToRow: " + row + ", refocusSearchText=" + false);
// getListView().requestFocusFromTouch();
getListView().setSelectionFromTop(row, 0);
getListView().setSelected(true);
}
static final Pattern WHITESPACE = Pattern.compile("\\s+");
final class SearchOperation implements Runnable {
final AtomicBoolean interrupted = new AtomicBoolean(false);
final String searchText;
List<String> searchTokens; // filled in for multiWord.
final Index index;
long searchStartMillis;
Index.IndexEntry searchResult;
List<RowBase> multiWordSearchResult;
boolean done = false;
SearchOperation(final String searchText, final Index index) {
this.searchText = StringUtil.normalizeWhitespace(searchText);
this.index = index;
}
public String toString() {
return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
}
@Override
public void run() {
try {
searchStartMillis = System.currentTimeMillis();
final String[] searchTokenArray = WHITESPACE.split(searchText);
if (searchTokenArray.length == 1) {
searchResult = index.findInsertionPoint(searchText, interrupted);
} else {
searchTokens = Arrays.asList(searchTokenArray);
multiWordSearchResult = index.multiWordSearch(searchText, searchTokens,
interrupted);
}
Log.d(LOG,
"searchText=" + searchText + ", searchDuration="
+ (System.currentTimeMillis() - searchStartMillis)
+ ", interrupted=" + interrupted.get());
if (!interrupted.get()) {
uiHandler.post(new Runnable() {
@Override
public void run() {
searchFinished(SearchOperation.this);
}
});
} else {
Log.d(LOG, "interrupted, skipping searchFinished.");
}
} catch (Exception e) {
Log.e(LOG, "Failure during search (can happen during Activity close.");
} finally {
synchronized (this) {
done = true;
this.notifyAll();
}
}
}
}
// --------------------------------------------------------------------------
// IndexAdapter
// --------------------------------------------------------------------------
private void showHtml(final List<HtmlEntry> htmlEntries, final String htmlTextToHighlight) {
String html = HtmlEntry.htmlBody(htmlEntries, index.shortName);
// Log.d(LOG, "html=" + html);
startActivityForResult(
HtmlDisplayActivity.getHtmlIntent(getApplicationContext(), String.format(
"<html><head><meta name=\"viewport\" content=\"width=device-width\"></head><body>%s</body></html>", html),
htmlTextToHighlight, false),
0);
}
static ViewGroup.LayoutParams WEIGHT_1 = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
static ViewGroup.LayoutParams WEIGHT_0 = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0f);
final class IndexAdapter extends BaseAdapter {
private static final float PADDING_DEFAULT_DP = 8;
private static final float PADDING_LARGE_DP = 16;
final Index index;
final List<RowBase> rows;
final Set<String> toHighlight;
private int mPaddingDefault;
private int mPaddingLarge;
IndexAdapter(final Index index) {
this.index = index;
rows = index.rows;
this.toHighlight = null;
getMetrics();
}
IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
this.index = index;
this.rows = rows;
this.toHighlight = new LinkedHashSet<String>(toHighlight);
getMetrics();
}
private void getMetrics() {
float scale = 1;
// Get the screen's density scale
// The previous method getResources().getDisplayMetrics()
// used to occasionally trigger a null pointer exception,
// so try this instead.
// As it still crashes, add a fallback
try {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
scale = dm.density;
} catch (NullPointerException e)
{}
// Convert the dps to pixels, based on density scale
mPaddingDefault = (int) (PADDING_DEFAULT_DP * scale + 0.5f);
mPaddingLarge = (int) (PADDING_LARGE_DP * scale + 0.5f);
}
@Override
public int getCount() {
return rows.size();
}
@Override
public RowBase getItem(int position) {
return rows.get(position);
}
@Override
public long getItemId(int position) {
return getItem(position).index();
}
@Override
public int getViewTypeCount() {
return 5;
}
@Override
public int getItemViewType(int position) {
final RowBase row = getItem(position);
if (row instanceof PairEntry.Row) {
final PairEntry entry = ((PairEntry.Row)row).getEntry();
final int rowCount = entry.pairs.size();
return rowCount > 1 ? 1 : 0;
} else if (row instanceof TokenRow) {
final IndexEntry indexEntry = ((TokenRow)row).getIndexEntry();
return indexEntry.htmlEntries.isEmpty() ? 2 : 3;
} else if (row instanceof HtmlEntry.Row) {
return 4;
} else {
throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final RowBase row = getItem(position);
if (row instanceof PairEntry.Row) {
return getView(position, (PairEntry.Row) row, parent, (TableLayout)convertView);
} else if (row instanceof TokenRow) {
return getView((TokenRow) row, parent, (TextView)convertView);
} else if (row instanceof HtmlEntry.Row) {
return getView((HtmlEntry.Row) row, parent, (TextView)convertView);
} else {
throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
}
}
private void addBoldSpans(String token, String col1Text, Spannable col1Spannable) {
int startPos = 0;
while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos, startPos
+ token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
startPos += token.length();
}
}
private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent,
TableLayout result) {
final Context context = parent.getContext();
final PairEntry entry = row.getEntry();
final int rowCount = entry.pairs.size();
if (result == null) {
result = new TableLayout(context);
// Because we have a Button inside a ListView row:
// http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
result.setClickable(true);
result.setFocusable(false);
result.setLongClickable(true);
// result.setBackgroundResource(android.R.drawable.menuitem_background);
result.setBackgroundResource(theme.normalRowBg);
} else if (result.getChildCount() > rowCount) {
result.removeViews(rowCount, result.getChildCount() - rowCount);
}
final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
layoutParams.weight = 0.5f;
layoutParams.leftMargin = mPaddingLarge;
for (int r = result.getChildCount(); r < rowCount; ++r) {
final TableRow tableRow = new TableRow(result.getContext());
final TextView col1 = new TextView(tableRow.getContext());
final TextView col2 = new TextView(tableRow.getContext());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
col1.setTextIsSelectable(true);
col2.setTextIsSelectable(true);
}
col1.setTextColor(textColorFg);
col2.setTextColor(textColorFg);
// Set the columns in the table.
if (r > 0) {
final TextView bullet = new TextView(tableRow.getContext());
bullet.setText(" •");
tableRow.addView(bullet);
}
tableRow.addView(col1, layoutParams);
if (r > 0) {
final TextView bullet = new TextView(tableRow.getContext());
bullet.setText(" •");
tableRow.addView(bullet);
}
tableRow.addView(col2, layoutParams);
col1.setWidth(1);
col2.setWidth(1);
col1.setTypeface(typeface);
col2.setTypeface(typeface);
col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
// col2.setBackgroundResource(theme.otherLangBg);
if (index.swapPairEntries) {
col2.setOnLongClickListener(textViewLongClickListenerIndex0);
col1.setOnLongClickListener(textViewLongClickListenerIndex1);
} else {
col1.setOnLongClickListener(textViewLongClickListenerIndex0);
col2.setOnLongClickListener(textViewLongClickListenerIndex1);
}
result.addView(tableRow);
}
for (int r = 0; r < rowCount; ++r) {
final TableRow tableRow = (TableRow)result.getChildAt(r);
final TextView col1 = (TextView)tableRow.getChildAt(r == 0 ? 0 : 1);
final TextView col2 = (TextView)tableRow.getChildAt(r == 0 ? 1 : 3);
// Set what's in the columns.
final Pair pair = entry.pairs.get(r);
final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
final Spannable col1Spannable = new SpannableString(col1Text);
final Spannable col2Spannable = new SpannableString(col2Text);
// Bold the token instances in col1.
if (toHighlight != null) {
for (final String token : toHighlight) {
addBoldSpans(token, col1Text, col1Spannable);
}
} else
addBoldSpans(row.getTokenRow(true).getToken(), col1Text, col1Spannable);
createTokenLinkSpans(col1, col1Spannable, col1Text);
createTokenLinkSpans(col2, col2Spannable, col2Text);
col1.setText(col1Spannable);
col2.setText(col2Spannable);
}
result.setOnClickListener(new TextView.OnClickListener() {
@Override
public void onClick(View v) {
DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
}
});
return result;
}
private TextView getPossibleLinkToHtmlEntryView(final boolean isTokenRow,
final String text, final boolean hasMainEntry, final List<HtmlEntry> htmlEntries,
final String htmlTextToHighlight, ViewGroup parent, TextView textView) {
final Context context = parent.getContext();
if (textView == null) {
textView = new TextView(context);
// set up things invariant across one ItemViewType
// ItemViewTypes handled here are:
// 2: isTokenRow == true, htmlEntries.isEmpty() == true
// 3: isTokenRow == true, htmlEntries.isEmpty() == false
// 4: isTokenRow == false, htmlEntries.isEmpty() == false
textView.setPadding(isTokenRow ? mPaddingDefault : mPaddingLarge, mPaddingDefault, mPaddingDefault, 0);
textView.setOnLongClickListener(indexIndex > 0 ? textViewLongClickListenerIndex1 : textViewLongClickListenerIndex0);
textView.setLongClickable(true);
// Doesn't work:
// textView.setTextColor(android.R.color.secondary_text_light);
textView.setTypeface(typeface);
if (isTokenRow) {
textView.setTextAppearance(context, theme.tokenRowFg);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 4 * fontSizeSp / 3);
} else {
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
}
if (!htmlEntries.isEmpty()) {
textView.setClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
textView.setBackgroundResource(hasMainEntry ? theme.tokenRowMainBg
: theme.tokenRowOtherBg);
// Make it so we can long-click on these token rows, too:
final Spannable textSpannable = new SpannableString(text);
createTokenLinkSpans(textView, textSpannable, text);
if (!htmlEntries.isEmpty()) {
final ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
}
};
textSpannable.setSpan(clickableSpan, 0, text.length(),
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showHtml(htmlEntries, htmlTextToHighlight);
}
});
}
textView.setText(textSpannable);
return textView;
}
private TextView getView(TokenRow row, ViewGroup parent, final TextView result) {
final IndexEntry indexEntry = row.getIndexEntry();
return getPossibleLinkToHtmlEntryView(true, indexEntry.token, row.hasMainEntry,
indexEntry.htmlEntries, null, parent, result);
}
private TextView getView(HtmlEntry.Row row, ViewGroup parent, final TextView result) {
final HtmlEntry htmlEntry = row.getEntry();
final TokenRow tokenRow = row.getTokenRow(true);
return getPossibleLinkToHtmlEntryView(false,
getString(R.string.seeAlso, htmlEntry.title, htmlEntry.entrySource.getName()),
false, Collections.singletonList(htmlEntry), tokenRow.getToken(), parent,
result);
}
}
static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
private void createTokenLinkSpans(final TextView textView, final Spannable spannable,
final String text) {
// Saw from the source code that LinkMovementMethod sets the selection!
// http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
textView.setMovementMethod(LinkMovementMethod.getInstance());
final Matcher matcher = CHAR_DASH.matcher(text);
while (matcher.find()) {
spannable.setSpan(new NonLinkClickableSpan(), matcher.start(),
matcher.end(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
String selectedSpannableText = null;
int selectedSpannableIndex = -1;
@Override
public boolean onTouchEvent(MotionEvent event) {
selectedSpannableText = null;
selectedSpannableIndex = -1;
return super.onTouchEvent(event);
}
private class TextViewLongClickListener implements OnLongClickListener {
final int index;
private TextViewLongClickListener(final int index) {
this.index = index;
}
@Override
public boolean onLongClick(final View v) {
final TextView textView = (TextView) v;
final int start = textView.getSelectionStart();
final int end = textView.getSelectionEnd();
if (start >= 0 && end >= 0) {
selectedSpannableText = textView.getText().subSequence(start, end).toString();
selectedSpannableIndex = index;
}
return false;
}
}
final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(
0);
final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(
1);
// --------------------------------------------------------------------------
// SearchText
// --------------------------------------------------------------------------
void onSearchTextChange(final String text) {
if ("thadolina".equals(text)) {
final Dialog dialog = new Dialog(getListView().getContext());
dialog.setContentView(R.layout.thadolina_dialog);
dialog.setTitle("Ti amo, amore mio!");
final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
startActivity(intent);
}
});
dialog.show();
}
if (dictRaf == null) {
Log.d(LOG, "searchText changed during shutdown, doing nothing.");
return;
}
// if (!searchView.hasFocus()) {
// Log.d(LOG, "searchText changed without focus, doing nothing.");
// return;
// }
Log.d(LOG, "onSearchTextChange: " + text);
if (currentSearchOperation != null) {
Log.d(LOG, "Interrupting currentSearchOperation.");
currentSearchOperation.interrupted.set(true);
}
currentSearchOperation = new SearchOperation(text, index);
searchExecutor.execute(currentSearchOperation);
((FloatingActionButton)findViewById(R.id.floatSearchButton)).setImageResource(text.length() > 0 ? R.drawable.ic_clear_black_24dp : R.drawable.ic_search_black_24dp);
}
// --------------------------------------------------------------------------
// Filtered results.
// --------------------------------------------------------------------------
boolean isFiltered() {
return rowsToShow != null;
}
void setFiltered(final SearchOperation searchOperation) {
if (nextWordMenuItem != null) {
nextWordMenuItem.setEnabled(false);
previousWordMenuItem.setEnabled(false);
}
rowsToShow = searchOperation.multiWordSearchResult;
setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
}
void clearFiltered() {
if (nextWordMenuItem != null) {
nextWordMenuItem.setEnabled(true);
previousWordMenuItem.setEnabled(true);
}
setListAdapter(new IndexAdapter(index));
rowsToShow = null;
}
}
| Simplify LayoutParams.
| src/com/hughes/android/dictionary/DictionaryActivity.java | Simplify LayoutParams. | <ide><path>rc/com/hughes/android/dictionary/DictionaryActivity.java
<ide> final int rowCount = entry.pairs.size();
<ide> if (result == null) {
<ide> result = new TableLayout(context);
<add> result.setStretchAllColumns(true);
<ide> // Because we have a Button inside a ListView row:
<ide> // http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
<ide> result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
<ide> result.removeViews(rowCount, result.getChildCount() - rowCount);
<ide> }
<ide>
<del> final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
<del> layoutParams.weight = 0.5f;
<del> layoutParams.leftMargin = mPaddingLarge;
<del>
<ide> for (int r = result.getChildCount(); r < rowCount; ++r) {
<add> final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
<add> layoutParams.leftMargin = mPaddingLarge;
<add>
<ide> final TableRow tableRow = new TableRow(result.getContext());
<ide>
<ide> final TextView col1 = new TextView(tableRow.getContext()); |
|
JavaScript | mit | 76761d354cc26715bbc6c627baccbe7eac837038 | 0 | JohnnyTheTank/apiNG | "use strict";
var apingApp = angular.module('jtt_aping', [])
.directive('aping', function (apingDefaultSettings) {
return {
restrict: 'E',
replace: 'false',
scope: {
type: '@',
items: '@',
maxItems: '@',
},
link: function (scope, element, attrs) {
},
controller: function ($scope) {
$scope.results = [];
this.concatToResults = function (_array) {
$scope.results = $scope.results.concat(_array);
};
this.getAppSettings = function () {
return {
type: $scope.type || apingDefaultSettings.type,
items: $scope.items || apingDefaultSettings.items,
maxItems: $scope.maxItems || apingDefaultSettings.maxItems,
};
};
},
templateUrl: function (elem, attrs) {
return attrs.templateUrl || apingDefaultSettings.templateUrl;
}
};
}
);
/**
* TODO: Twitter https://github.com/pavelk2/social-feed/
* TODO: TweeCool (twitter api) http://tweecool.com/
* TODO: Twitter https://github.com/jublonet/codebird-js
* TODO: Youtube Fullscreen Angular Tool: https://github.com/kanzelm3/angular-video-bg
*/ | js/aping/aping/aping-directives.js | "use strict";
var apingApp = angular.module('jtt_aping', [])
.directive('aping', function (apingDefaultSettings) {
return {
restrict: 'E',
replace: 'false',
scope: {
type: '@',
items: '@',
maxItems: '@',
},
link: function (scope, element, attrs) {
},
controller: function ($scope) {
$scope.results = [];
this.concatToResults = function (_array) {
$scope.results = $scope.results.concat(_array);
};
this.getAppSettings = function () {
return {
type: $scope.type || apingDefaultSettings.type,
items: $scope.items || apingDefaultSettings.items,
maxItems: $scope.maxItems || apingDefaultSettings.maxItems,
};
};
},
templateUrl: function (elem, attrs) {
return attrs.templateUrl || apingDefaultSettings.templateUrl;
}
};
}
);
/**
* TODO: Twitter https://github.com/pavelk2/social-feed/
* TODO: TweeCool (twitter api) http://tweecool.com/
* TODO: Twitter https://github.com/jublonet/codebird-js
* TODO: Youtube Fullscreen Angular Tool: https://github.com/kanzelm3/angular-video-bg
* TODO: Creating a Plugin System: http://taoofcode.net/creating-a-plugin-system-with-the-compile-provider/
* TODO: parentscope: http://stackoverflow.com/a/21454647
*/ | checked two todos
| js/aping/aping/aping-directives.js | checked two todos | <ide><path>s/aping/aping/aping-directives.js
<ide> * TODO: TweeCool (twitter api) http://tweecool.com/
<ide> * TODO: Twitter https://github.com/jublonet/codebird-js
<ide> * TODO: Youtube Fullscreen Angular Tool: https://github.com/kanzelm3/angular-video-bg
<del> * TODO: Creating a Plugin System: http://taoofcode.net/creating-a-plugin-system-with-the-compile-provider/
<del> * TODO: parentscope: http://stackoverflow.com/a/21454647
<ide> */ |
|
Java | apache-2.0 | c16f8a534992f39d88eb5598bbf963c8138e70d5 | 0 | adamsp/DestinyRaidTimers,adamsp/DestinyRaidTimers | /*
* Copyright 2015 Adam Speakman
*
* 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 nz.net.speakman.destinyraidtimers.consumables.views;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.sefford.circularprogressdrawable.CircularProgressDrawable;
import com.squareup.otto.Bus;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import nz.net.speakman.destinyraidtimers.R;
import nz.net.speakman.destinyraidtimers.RaidApplication;
import nz.net.speakman.destinyraidtimers.consumables.ConsumablesTimer;
/**
* Created by Adam on 15-03-28.
*/
public abstract class ConsumablesCountdownView extends RelativeLayout {
private static final String KEY_SUPER_STATE = "nz.net.speakman.destinyraidtimers.consumables.views.ConsumablesCountdownView.KEY_SUPER_STATE";
private static final String KEY_COUNTDOWN_PROGRESS = "nz.net.speakman.destinyraidtimers.consumables.views.ConsumablesCountdownView.KEY_COUNTDOWN_PROGRESS";
private static final String KEY_COUNTDOWN_LABEL = "nz.net.speakman.destinyraidtimers.consumables.views.ConsumablesCountdownView.KEY_COUNTDOWN_LABEL";
protected abstract static class AnimationEndListener implements Animator.AnimatorListener {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
}
protected abstract static class AnimationStartListener implements Animator.AnimatorListener {
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
}
// TODO Put in resources?...
protected static final int RESET_ANIMATION_DURATION = 750;
public static String formatMinutesFromMillis(long millis) {
return String.format("%d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis % (1000 * 60)));
}
@InjectView(R.id.consumables_countdown_label)
TextView countdown;
@InjectView(R.id.consumables_countdown_image)
ImageView progressView;
@InjectView(R.id.consumables_countdown_timer_reset)
View resetButton;
@Inject
Bus bus;
ObjectAnimator animator;
CircularProgressDrawable progressDrawable;
public ConsumablesCountdownView(Context context) {
super(context);
init(context);
}
public ConsumablesCountdownView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ConsumablesCountdownView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ConsumablesCountdownView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
protected void init(Context ctx) {
View target = this;
View source = inflate(ctx, R.layout.consumables_countdown, this);
ButterKnife.inject(target, source);
RaidApplication.getApplication().inject(this);
Resources resources = ctx.getResources();
progressDrawable = new CircularProgressDrawable.Builder()
.setRingColor(resources.getColor(R.color.consumables_accent))
.setRingWidth(resources.getDimensionPixelSize(R.dimen.consumables_progress_width))
.create();
progressDrawable.setProgress(1f);
progressView.setImageDrawable(progressDrawable);
bus.register(this);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
Bundle outState = new Bundle();
outState.putParcelable(KEY_SUPER_STATE, superState);
outState.putFloat(KEY_COUNTDOWN_PROGRESS, progressDrawable.getProgress());
outState.putString(KEY_COUNTDOWN_LABEL, countdown.getText().toString());
return outState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
float progress = ((Bundle) state).getFloat(KEY_COUNTDOWN_PROGRESS, 1f);
progressDrawable.setProgress(progress);
String text = ((Bundle)state).getString(KEY_COUNTDOWN_LABEL, getDefaultText());
countdown.setText(text);
state = ((Bundle) state).getParcelable(KEY_SUPER_STATE);
if (getTimer().isRunning()) {
resetButton.setVisibility(View.VISIBLE);
}
}
super.onRestoreInstanceState(state);
}
public void reset() {
hideResetButton();
resetProgressBar();
countdown.setText(getDefaultText());
}
protected void onTimerUpdated(long timeRemainingMs, long totalTimeMs) {
if (timeRemainingMs == 0) {
reset();
} else {
countdown.setText(formatMinutesFromMillis(timeRemainingMs));
}
if (animator == null) {
float progressPct = timeRemainingMs / (float) totalTimeMs;
startAnimator(progressPct, timeRemainingMs);
}
}
protected void resetProgressBar() {
if (animator != null) {
animator.cancel();
}
ObjectAnimator resetAnimator = ObjectAnimator.ofFloat(progressDrawable, CircularProgressDrawable.PROGRESS_PROPERTY,
progressDrawable.getProgress(), 1f);
resetAnimator.setDuration(RESET_ANIMATION_DURATION);
resetAnimator.addListener(new AnimationEndListener() {
@Override
public void onAnimationEnd(Animator animation) {
animator = null;
}
});
resetAnimator.start();
}
protected void startAnimator(float progressPct, long duration) {
// Drawable goes backwards, so we count down from 1 -> 0
progressDrawable.setProgress(progressPct);
animator = ObjectAnimator.ofFloat(progressDrawable, CircularProgressDrawable.PROGRESS_PROPERTY,
progressPct, 0f);
animator.setDuration(duration);
animator.setInterpolator(new LinearInterpolator());
animator.start();
}
private void showResetButton() {
ObjectAnimator showAnimator;
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
showAnimator = ObjectAnimator.ofFloat(resetButton, "translationY",
resetButton.getMeasuredHeight(), 0f);
} else {
showAnimator = ObjectAnimator.ofFloat(resetButton, "translationX",
resetButton.getMeasuredWidth(), 0f);
}
showAnimator.setDuration(500);
showAnimator.addListener(new AnimationStartListener() {
@Override
public void onAnimationStart(Animator animation) {
resetButton.setVisibility(View.VISIBLE);
}
});
showAnimator.start();
}
private void hideResetButton() {
ObjectAnimator hideAnimator;
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
hideAnimator = ObjectAnimator.ofFloat(resetButton, "translationY",
0, resetButton.getMeasuredHeight());
} else {
hideAnimator = ObjectAnimator.ofFloat(resetButton, "translationX",
0, resetButton.getMeasuredWidth());
}
hideAnimator.setDuration(500);
hideAnimator.addListener(new AnimationEndListener() {
@Override
public void onAnimationEnd(Animator animation) {
resetButton.setVisibility(View.INVISIBLE);
}
});
hideAnimator.start();
}
@OnClick(R.id.consumables_countdown_image)
public void onCountdownClick() {
showResetButton();
getTimer().start();
}
@OnClick(R.id.consumables_countdown_timer_reset)
public void onResetClick() {
getTimer().reset();
reset();
}
protected abstract String getDefaultText();
protected abstract ConsumablesTimer getTimer();
}
| app/src/main/java/nz/net/speakman/destinyraidtimers/consumables/views/ConsumablesCountdownView.java | /*
* Copyright 2015 Adam Speakman
*
* 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 nz.net.speakman.destinyraidtimers.consumables.views;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.sefford.circularprogressdrawable.CircularProgressDrawable;
import com.squareup.otto.Bus;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import nz.net.speakman.destinyraidtimers.R;
import nz.net.speakman.destinyraidtimers.RaidApplication;
import nz.net.speakman.destinyraidtimers.consumables.ConsumablesTimer;
/**
* Created by Adam on 15-03-28.
*/
public abstract class ConsumablesCountdownView extends RelativeLayout {
private static final String KEY_SUPER_STATE = "nz.net.speakman.destinyraidtimers.consumables.views.ConsumablesCountdownView.KEY_SUPER_STATE";
private static final String KEY_COUNTDOWN_PROGRESS = "nz.net.speakman.destinyraidtimers.consumables.views.ConsumablesCountdownView.KEY_COUNTDOWN_PROGRESS";
private static final String KEY_COUNTDOWN_LABEL = "nz.net.speakman.destinyraidtimers.consumables.views.ConsumablesCountdownView.KEY_COUNTDOWN_LABEL";
protected abstract static class AnimationEndListener implements Animator.AnimatorListener {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
}
protected abstract static class AnimationStartListener implements Animator.AnimatorListener {
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
}
// TODO Put in resources?...
protected static final int RESET_ANIMATION_DURATION = 750;
public static String formatMinutesFromMillis(long millis) {
return String.format("%d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis % (1000 * 60)));
}
@InjectView(R.id.consumables_countdown_label)
TextView countdown;
@InjectView(R.id.consumables_countdown_image)
ImageView progressView;
@InjectView(R.id.consumables_countdown_timer_reset)
View resetButton;
@Inject
Bus bus;
ObjectAnimator animator;
CircularProgressDrawable progressDrawable;
public ConsumablesCountdownView(Context context) {
super(context);
init(context);
}
public ConsumablesCountdownView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ConsumablesCountdownView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ConsumablesCountdownView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
protected void init(Context ctx) {
View target = this;
View source = inflate(ctx, R.layout.consumables_countdown, this);
ButterKnife.inject(target, source);
RaidApplication.getApplication().inject(this);
Resources resources = ctx.getResources();
progressDrawable = new CircularProgressDrawable.Builder()
.setRingColor(resources.getColor(R.color.consumables_accent))
.setRingWidth(resources.getDimensionPixelSize(R.dimen.consumables_progress_width))
.create();
progressDrawable.setProgress(1f);
progressView.setImageDrawable(progressDrawable);
bus.register(this);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
Bundle outState = new Bundle();
outState.putParcelable(KEY_SUPER_STATE, superState);
outState.putFloat(KEY_COUNTDOWN_PROGRESS, progressDrawable.getProgress());
outState.putString(KEY_COUNTDOWN_LABEL, countdown.getText().toString());
return outState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
float progress = ((Bundle) state).getFloat(KEY_COUNTDOWN_PROGRESS, 1f);
progressDrawable.setProgress(progress);
String text = ((Bundle)state).getString(KEY_COUNTDOWN_LABEL, getDefaultText());
countdown.setText(text);
state = ((Bundle) state).getParcelable(KEY_SUPER_STATE);
}
super.onRestoreInstanceState(state);
}
public void reset() {
hideResetButton();
resetProgressBar();
countdown.setText(getDefaultText());
}
protected void onTimerUpdated(long timeRemainingMs, long totalTimeMs) {
if (timeRemainingMs == 0) {
reset();
} else {
countdown.setText(formatMinutesFromMillis(timeRemainingMs));
}
if (animator == null) {
float progressPct = timeRemainingMs / (float) totalTimeMs;
startAnimator(progressPct, timeRemainingMs);
}
}
protected void resetProgressBar() {
if (animator != null) {
animator.cancel();
}
ObjectAnimator resetAnimator = ObjectAnimator.ofFloat(progressDrawable, CircularProgressDrawable.PROGRESS_PROPERTY,
progressDrawable.getProgress(), 1f);
resetAnimator.setDuration(RESET_ANIMATION_DURATION);
resetAnimator.addListener(new AnimationEndListener() {
@Override
public void onAnimationEnd(Animator animation) {
animator = null;
}
});
resetAnimator.start();
}
protected void startAnimator(float progressPct, long duration) {
// Drawable goes backwards, so we count down from 1 -> 0
progressDrawable.setProgress(progressPct);
animator = ObjectAnimator.ofFloat(progressDrawable, CircularProgressDrawable.PROGRESS_PROPERTY,
progressPct, 0f);
animator.setDuration(duration);
animator.setInterpolator(new LinearInterpolator());
animator.start();
}
private void showResetButton() {
ObjectAnimator showAnimator;
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
showAnimator = ObjectAnimator.ofFloat(resetButton, "translationY",
resetButton.getMeasuredHeight(), 0f);
} else {
showAnimator = ObjectAnimator.ofFloat(resetButton, "translationX",
resetButton.getMeasuredWidth(), 0f);
}
showAnimator.setDuration(500);
showAnimator.addListener(new AnimationStartListener() {
@Override
public void onAnimationStart(Animator animation) {
resetButton.setVisibility(View.VISIBLE);
}
});
showAnimator.start();
}
private void hideResetButton() {
ObjectAnimator hideAnimator;
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
hideAnimator = ObjectAnimator.ofFloat(resetButton, "translationY",
0, resetButton.getMeasuredHeight());
} else {
hideAnimator = ObjectAnimator.ofFloat(resetButton, "translationX",
0, resetButton.getMeasuredWidth());
}
hideAnimator.setDuration(500);
hideAnimator.addListener(new AnimationEndListener() {
@Override
public void onAnimationEnd(Animator animation) {
resetButton.setVisibility(View.INVISIBLE);
}
});
hideAnimator.start();
}
@OnClick(R.id.consumables_countdown_image)
public void onCountdownClick() {
showResetButton();
getTimer().start();
}
@OnClick(R.id.consumables_countdown_timer_reset)
public void onResetClick() {
getTimer().reset();
reset();
}
protected abstract String getDefaultText();
protected abstract ConsumablesTimer getTimer();
}
| Showing reset button after rotation
| app/src/main/java/nz/net/speakman/destinyraidtimers/consumables/views/ConsumablesCountdownView.java | Showing reset button after rotation | <ide><path>pp/src/main/java/nz/net/speakman/destinyraidtimers/consumables/views/ConsumablesCountdownView.java
<ide> String text = ((Bundle)state).getString(KEY_COUNTDOWN_LABEL, getDefaultText());
<ide> countdown.setText(text);
<ide> state = ((Bundle) state).getParcelable(KEY_SUPER_STATE);
<add> if (getTimer().isRunning()) {
<add> resetButton.setVisibility(View.VISIBLE);
<add> }
<ide> }
<ide> super.onRestoreInstanceState(state);
<ide> } |
|
Java | lgpl-2.1 | 3b1eb927867d044461868ec870b68950c5e139e9 | 0 | gallardo/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,alkacon/opencms-core,alkacon/opencms-core,it-tavis/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,victos/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,gallardo/opencms-core,victos/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,victos/opencms-core,victos/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,alkacon/opencms-core | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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 org.opencms.ade.containerpage.client.ui;
import com.alkacon.acacia.client.I_InlineFormParent;
import com.alkacon.acacia.client.widgets.I_EditWidget;
import org.opencms.ade.containerpage.client.CmsContainerpageController;
import org.opencms.ade.containerpage.client.ui.css.I_CmsLayoutBundle;
import org.opencms.ade.containerpage.shared.CmsInheritanceInfo;
import org.opencms.ade.contenteditor.client.CmsContentEditor;
import org.opencms.gwt.client.dnd.I_CmsDraggable;
import org.opencms.gwt.client.dnd.I_CmsDropTarget;
import org.opencms.gwt.client.ui.CmsHighlightingBorder;
import org.opencms.gwt.client.util.CmsDomUtil;
import org.opencms.gwt.client.util.CmsDomUtil.Tag;
import org.opencms.gwt.client.util.CmsPositionBean;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Content element within a container-page.<p>
*
* @since 8.0.0
*/
public class CmsContainerPageElementPanel extends AbsolutePanel
implements I_CmsDraggable, HasClickHandlers, I_InlineFormParent {
/** The height necessary for a container page element. */
public static int NECESSARY_HEIGHT = 24;
/** Highlighting border for this element. */
protected CmsHighlightingBorder m_highlighting;
/** A flag which indicates whether the height has already been checked. */
private boolean m_checkedHeight;
/** Flag indicating the the editables are currently being checked. */
private boolean m_checkingEditables;
/** The elements client id. */
private String m_clientId;
/**
* Flag which indicates whether the new editor is disabled for this element.<p>
*/
private boolean m_disableNewEditor;
/** The direct edit bar instances. */
private Map<Element, CmsListCollectorEditor> m_editables;
/** The editor click handler registration. */
private HandlerRegistration m_editorClickHandlerRegistration;
/** The option bar, holding optional function buttons. */
private CmsElementOptionBar m_elementOptionBar;
/** The overlay for expired elements. */
private Element m_expiredOverlay;
/** Indicates whether this element has settings to edit. */
private boolean m_hasSettings;
/** The inheritance info for this element. */
private CmsInheritanceInfo m_inheritanceInfo;
/** The is new element type. */
private String m_newType;
/** The registered node insert event handler. */
private JavaScriptObject m_nodeInsertHandler;
/** The no edit reason, if empty editing is allowed. */
private String m_noEditReason;
/** The parent drop target. */
private I_CmsDropContainer m_parent;
/** Flag indicating if the element resource is currently released and not expired. */
private boolean m_releasedAndNotExpired;
/** The element resource site-path. */
private String m_sitePath;
/**
* Indicates if the current user has view permissions on the element resource.
* Without view permissions, the element can neither be edited, nor moved.
**/
private boolean m_viewPermission;
/**
* Indicates if the current user has write permissions on the element resource.
* Without write permissions, the element can not be edited.
**/
private boolean m_writePermission;
/**
* Constructor.<p>
*
* @param element the DOM element
* @param parent the drag parent
* @param clientId the client id
* @param sitePath the element site-path
* @param noEditReason the no edit reason, if empty, editing is allowed
* @param hasSettings should be true if the element has settings which can be edited
* @param hasViewPermission indicates if the current user has view permissions on the element resource
* @param hasWritePermission indicates if the current user has write permissions on the element resource
* @param releasedAndNotExpired <code>true</code> if the element resource is currently released and not expired
* @param disableNewEditor flag to disable the new editor for this element
*/
public CmsContainerPageElementPanel(
Element element,
I_CmsDropContainer parent,
String clientId,
String sitePath,
String noEditReason,
boolean hasSettings,
boolean hasViewPermission,
boolean hasWritePermission,
boolean releasedAndNotExpired,
boolean disableNewEditor) {
super((com.google.gwt.user.client.Element)element);
m_clientId = clientId;
m_sitePath = sitePath;
m_noEditReason = noEditReason;
m_hasSettings = hasSettings;
m_parent = parent;
m_disableNewEditor = disableNewEditor;
setViewPermission(hasViewPermission);
setWritePermission(hasWritePermission);
setReleasedAndNotExpired(releasedAndNotExpired);
getElement().addClassName(I_CmsLayoutBundle.INSTANCE.dragdropCss().dragElement());
}
/**
* Returns the necessary height as a CSS height string in pixels.<p>
*
* @return the necessary height as a CSS string
*/
public static String getNecessaryHeight() {
return NECESSARY_HEIGHT + "px !important";
}
/**
* @see com.google.gwt.event.dom.client.HasClickHandlers#addClickHandler(com.google.gwt.event.dom.client.ClickHandler)
*/
public HandlerRegistration addClickHandler(ClickHandler handler) {
return addDomHandler(handler, ClickEvent.getType());
}
/**
* @see com.alkacon.acacia.client.I_InlineFormParent#adoptWidget(com.alkacon.acacia.client.widgets.I_EditWidget)
*/
public void adoptWidget(I_EditWidget widget) {
getChildren().add(widget.asWidget());
adopt(widget.asWidget());
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#getDragHelper(org.opencms.gwt.client.dnd.I_CmsDropTarget)
*/
public Element getDragHelper(I_CmsDropTarget target) {
Element helper = CmsDomUtil.clone(getElement());
target.getElement().appendChild(helper);
// preparing helper styles
String width = CmsDomUtil.getCurrentStyle(helper, CmsDomUtil.Style.width);
Style style = helper.getStyle();
style.setPosition(Position.ABSOLUTE);
style.setMargin(0, Unit.PX);
style.setProperty(CmsDomUtil.Style.width.name(), width);
style.setZIndex(I_CmsLayoutBundle.INSTANCE.constants().css().zIndexDND());
helper.addClassName(I_CmsLayoutBundle.INSTANCE.dragdropCss().dragging());
helper.addClassName(org.opencms.gwt.client.ui.css.I_CmsLayoutBundle.INSTANCE.generalCss().shadow());
if (!CmsDomUtil.hasBackground(helper)) {
helper.addClassName(I_CmsLayoutBundle.INSTANCE.dragdropCss().dragElementBackground());
}
if (!CmsDomUtil.hasBorder(helper)) {
helper.addClassName(I_CmsLayoutBundle.INSTANCE.dragdropCss().dragElementBorder());
}
return helper;
}
/**
* Returns the option bar of this element.<p>
*
* @return the option bar widget
*/
public CmsElementOptionBar getElementOptionBar() {
return m_elementOptionBar;
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#getId()
*/
public String getId() {
return m_clientId;
}
/**
* Returns the inheritance info for this element.<p>
*
* @return the inheritance info for this element
*/
public CmsInheritanceInfo getInheritanceInfo() {
return m_inheritanceInfo;
}
/**
* Returns the new element type.
*
* @return the new element type
*/
public String getNewType() {
return m_newType;
}
/**
* Returns the no edit reason.<p>
*
* @return the no edit reason
*/
public String getNoEditReason() {
return m_noEditReason;
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#getParentTarget()
*/
public I_CmsDropContainer getParentTarget() {
return m_parent;
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#getPlaceholder(org.opencms.gwt.client.dnd.I_CmsDropTarget)
*/
public Element getPlaceholder(I_CmsDropTarget target) {
Element placeholder = CmsDomUtil.clone(getElement());
placeholder.addClassName(I_CmsLayoutBundle.INSTANCE.dragdropCss().dragPlaceholder());
return placeholder;
}
/**
* Returns if the element resource is currently released and not expired.<p>
*
* @return <code>true</code> if the element resource is currently released and not expired
*/
public boolean getReleasedAndNotExpired() {
return m_releasedAndNotExpired;
}
/**
* Returns the site-path.<p>
*
* @return the site-path
*/
public String getSitePath() {
return m_sitePath;
}
/**
* Returns the structure id of the element.<p>
*
* @return the structure id of the element
*/
public CmsUUID getStructureId() {
if (m_clientId == null) {
return null;
}
return new CmsUUID(CmsContainerpageController.getServerId(m_clientId));
}
/**
* Returns true if the element has settings to edit.<p>
*
* @return true if the element has settings to edit
*/
public boolean hasSettings() {
return m_hasSettings;
}
/**
* Returns if the current user has view permissions for the element resource.<p>
*
* @return <code>true</code> if the current user has view permissions for the element resource
*/
public boolean hasViewPermission() {
return m_viewPermission;
}
/**
* Returns if the user has write permission.<p>
*
* @return <code>true</code> if the user has write permission
*/
public boolean hasWritePermission() {
return m_writePermission;
}
/**
* Hides list collector direct edit buttons, if present.<p>
*/
public void hideEditableListButtons() {
if (m_editables != null) {
for (CmsListCollectorEditor editor : m_editables.values()) {
editor.getElement().getStyle().setDisplay(Display.NONE);
}
}
}
/**
* Puts a highlighting border around the element.<p>
*/
public void highlightElement() {
if (m_highlighting == null) {
m_highlighting = new CmsHighlightingBorder(CmsPositionBean.generatePositionInfo(this), isNew()
? CmsHighlightingBorder.BorderColor.blue
: CmsHighlightingBorder.BorderColor.red);
RootPanel.get().add(m_highlighting);
} else {
m_highlighting.setPosition(CmsPositionBean.generatePositionInfo(this));
}
}
/**
* Initializes the editor click handler.<p>
*
* @param controller the container page controller instance
*/
public void initInlineEditor(final CmsContainerpageController controller) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_noEditReason)
&& !m_disableNewEditor
&& CmsContentEditor.setEditable(getElement(), true)) {
if (m_editorClickHandlerRegistration != null) {
m_editorClickHandlerRegistration.removeHandler();
}
m_editorClickHandlerRegistration = addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// if another content is already being edited, don't start another editor
if (controller.isContentEditing()) {
return;
}
Element eventTarget = event.getNativeEvent().getEventTarget().cast();
Element linkTag = CmsDomUtil.getAncestor(eventTarget, Tag.a);
if (linkTag == null) {
Element target = event.getNativeEvent().getEventTarget().cast();
while ((target != null) && (target != getElement())) {
if ("true".equals(target.getAttribute("contentEditable"))) {
controller.getHandler().openEditorForElement(CmsContainerPageElementPanel.this, true);
removeEditorHandler();
break;
} else {
target = target.getParentElement();
}
}
}
}
});
}
}
/**
* Returns if this is e newly created element.<p>
*
* @return <code>true</code> if the element is new
*/
public boolean isNew() {
return m_newType != null;
}
/**
* Returns true if the new content editor is disabled for this element.<p>
*
* @return true if the new editor is disabled for this element
*/
public boolean isNewEditorDisabled() {
return m_disableNewEditor;
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#onDragCancel()
*/
public void onDragCancel() {
clearDrag();
resetOptionbar();
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#onDrop(org.opencms.gwt.client.dnd.I_CmsDropTarget)
*/
public void onDrop(I_CmsDropTarget target) {
clearDrag();
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#onStartDrag(org.opencms.gwt.client.dnd.I_CmsDropTarget)
*/
public void onStartDrag(I_CmsDropTarget target) {
CmsDomUtil.addDisablingOverlay(getElement());
getElement().getStyle().setOpacity(0.5);
removeHighlighting();
}
/**
* @see com.google.gwt.user.client.ui.Widget#removeFromParent()
*/
@Override
public void removeFromParent() {
removeHighlighting();
super.removeFromParent();
}
/**
* Removes the highlighting border.<p>
*/
public void removeHighlighting() {
if (m_highlighting != null) {
m_highlighting.removeFromParent();
m_highlighting = null;
}
}
/**
* Removes the inline editor.<p>
*/
public void removeInlineEditor() {
CmsContentEditor.setEditable(getElement(), false);
removeEditorHandler();
}
/**
* Sets the elementOptionBar.<p>
*
* @param elementOptionBar the elementOptionBar to set
*/
public void setElementOptionBar(CmsElementOptionBar elementOptionBar) {
if ((m_elementOptionBar != null) && (getWidgetIndex(m_elementOptionBar) >= 0)) {
m_elementOptionBar.removeFromParent();
}
m_elementOptionBar = elementOptionBar;
insert(m_elementOptionBar, 0);
if (isOptionbarIFrameCollision(m_elementOptionBar.getCalculatedWidth())) {
m_elementOptionBar.getElement().getStyle().setPosition(Position.RELATIVE);
int marginLeft = getElement().getOffsetWidth() - m_elementOptionBar.getCalculatedWidth();
m_elementOptionBar.getElement().getStyle().setMarginLeft(marginLeft, Unit.PX);
}
}
/**
* Sets the element id.<p>
*
* @param id the id
*/
public void setId(String id) {
m_clientId = id;
}
/**
* Sets the inheritance info for this element.<p>
*
* @param inheritanceInfo the inheritance info for this element to set
*/
public void setInheritanceInfo(CmsInheritanceInfo inheritanceInfo) {
m_inheritanceInfo = inheritanceInfo;
}
/**
* Sets the new-type of the element.<p>
*
* @param newType the new-type
*/
public void setNewType(String newType) {
m_newType = newType;
}
/**
* Sets the no edit reason.<p>
*
* @param noEditReason the no edit reason to set
*/
public void setNoEditReason(String noEditReason) {
m_noEditReason = noEditReason;
}
/**
* Sets if the element resource is currently released and not expired.<p>
*
* @param releasedAndNotExpired <code>true</code> if the element resource is currently released and not expired
*/
public void setReleasedAndNotExpired(boolean releasedAndNotExpired) {
m_releasedAndNotExpired = releasedAndNotExpired;
if (m_releasedAndNotExpired) {
getElement().removeClassName(I_CmsLayoutBundle.INSTANCE.containerpageCss().expired());
if (m_expiredOverlay != null) {
m_expiredOverlay.removeFromParent();
m_expiredOverlay = null;
}
} else {
getElement().addClassName(I_CmsLayoutBundle.INSTANCE.containerpageCss().expired());
m_expiredOverlay = DOM.createDiv();
m_expiredOverlay.setTitle("Expired resource");
m_expiredOverlay.addClassName(I_CmsLayoutBundle.INSTANCE.containerpageCss().expiredOverlay());
getElement().appendChild(m_expiredOverlay);
}
}
/**
* Sets the site path.<p>
*
* @param sitePath the site path to set
*/
public void setSitePath(String sitePath) {
m_sitePath = sitePath;
}
/**
* Sets if the current user has view permissions for the element resource.<p>
*
* @param viewPermission the view permission to set
*/
public void setViewPermission(boolean viewPermission) {
m_viewPermission = viewPermission;
}
/**
* Sets the user write permission.<p>
*
* @param writePermission the user write permission to set
*/
public void setWritePermission(boolean writePermission) {
m_writePermission = writePermission;
}
/**
* Shows list collector direct edit buttons (old direct edit style), if present.<p>
*/
public void showEditableListButtons() {
m_checkingEditables = true;
if (m_editables == null) {
m_editables = new HashMap<Element, CmsListCollectorEditor>();
List<Element> editables = CmsDomUtil.getElementsByClass("cms-editable", Tag.div, getElement());
if ((editables != null) && (editables.size() > 0)) {
for (Element editable : editables) {
CmsListCollectorEditor editor = new CmsListCollectorEditor(editable, m_clientId);
add(editor, (com.google.gwt.user.client.Element)editable.getParentElement());
if (CmsDomUtil.hasDimension(editable.getParentElement())) {
editor.setPosition(CmsDomUtil.getEditablePosition(editable), getElement());
} else {
editor.getElement().getStyle().setDisplay(Display.NONE);
}
m_editables.put(editable, editor);
}
}
} else {
Iterator<Entry<Element, CmsListCollectorEditor>> it = m_editables.entrySet().iterator();
while (it.hasNext()) {
Entry<Element, CmsListCollectorEditor> entry = it.next();
if (!entry.getValue().isValid()) {
entry.getValue().removeFromParent();
it.remove();
} else if (CmsDomUtil.hasDimension(entry.getValue().getElement().getParentElement())) {
entry.getValue().getElement().getStyle().clearDisplay();
entry.getValue().setPosition(
CmsDomUtil.getEditablePosition(entry.getValue().getMarkerTag()),
getElement());
}
}
List<Element> editables = CmsDomUtil.getElementsByClass("cms-editable", Tag.div, getElement());
if (editables.size() > m_editables.size()) {
for (Element editable : editables) {
if (!m_editables.containsKey(editable)) {
CmsListCollectorEditor editor = new CmsListCollectorEditor(editable, m_clientId);
add(editor, (com.google.gwt.user.client.Element)editable.getParentElement());
if (CmsDomUtil.hasDimension(editable.getParentElement())) {
editor.setPosition(CmsDomUtil.getEditablePosition(editable), getElement());
} else {
editor.getElement().getStyle().setDisplay(Display.NONE);
}
m_editables.put(editable, editor);
}
}
}
}
m_checkingEditables = false;
resetNodeInsertedHandler();
}
/**
* Checks for changes in the list collector direct edit content.<p>
*/
protected void checkForEditableChanges() {
if (!m_checkingEditables) {
m_checkingEditables = true;
Timer timer = new Timer() {
@Override
public void run() {
showEditableListButtons();
}
};
timer.schedule(500);
}
}
/**
* Returns if the list collector direct edit content has changed.<p>
*
* @return <code>true</code> if the list collector direct edit content has changed
*/
protected boolean hasChangedEditables() {
if (m_editables == null) {
return true;
}
for (CmsListCollectorEditor editor : m_editables.values()) {
if (!editor.isValid()) {
return true;
}
}
return CmsDomUtil.getElementsByClass("cms-editable", Tag.div, getElement()).size() > m_editables.size();
}
/**
* @see com.google.gwt.user.client.ui.Widget#onLoad()
*/
@Override
protected void onLoad() {
if (!hasCheckedHeight() && (getParentTarget() instanceof CmsContainerPageContainer)) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
if (!hasCheckedHeight()
&& (CmsPositionBean.generatePositionInfo(getElement()).getHeight() < NECESSARY_HEIGHT)
&& (CmsPositionBean.getInnerDimensions(getElement()).getHeight() < NECESSARY_HEIGHT)) {
CmsContainerpageController.get().getHandler().enableShowSmallElements();
addStyleName(org.opencms.ade.containerpage.client.ui.css.I_CmsLayoutBundle.INSTANCE.containerpageCss().smallElement());
}
setCheckedHeight(true);
}
});
}
resetOptionbar();
}
/**
* Removes the inline editor handler.<p>
*/
protected void removeEditorHandler() {
if (m_editorClickHandlerRegistration != null) {
m_editorClickHandlerRegistration.removeHandler();
m_editorClickHandlerRegistration = null;
}
}
/**
* Returns if the minimum element height has been checked.<p>
*
* @return <code>true</code> if the minimum element height has been checked
*/
boolean hasCheckedHeight() {
return m_checkedHeight;
}
/**
* Sets the checked height flag.<p>
*
* @param checked the checked height flag
*/
void setCheckedHeight(boolean checked) {
m_checkedHeight = checked;
}
/**
* Removes all styling done during drag and drop.<p>
*/
private void clearDrag() {
CmsDomUtil.removeDisablingOverlay(getElement());
m_elementOptionBar.getElement().removeClassName(
org.opencms.gwt.client.ui.css.I_CmsLayoutBundle.INSTANCE.stateCss().cmsHovering());
// using own implementation as GWT won't do it properly on IE7-8
CmsDomUtil.clearOpacity(getElement());
getElement().getStyle().clearDisplay();
}
/**
* Returns if the option bar position collides with any iframe child elements.<p>
*
* @param optionWidth the option bar witdh
*
* @return <code>true</code> if there are iframe child elements located no less than 25px below the upper edge of the element
*/
private boolean isOptionbarIFrameCollision(int optionWidth) {
if (RootPanel.getBodyElement().isOrHasChild(getElement())) {
int elementTop = getElement().getAbsoluteTop();
NodeList<Element> frames = getElement().getElementsByTagName(CmsDomUtil.Tag.iframe.name());
for (int i = 0; i < frames.getLength(); i++) {
if (((frames.getItem(i).getAbsoluteTop() - elementTop) < 25)
&& ((frames.getItem(i).getAbsoluteRight() - getElement().getAbsoluteRight()) < optionWidth)) {
return true;
}
}
}
return false;
}
/**
* Resets the node inserted handler.<p>
*/
private native void resetNodeInsertedHandler()/*-{
var $this = this;
var element = $this.@org.opencms.ade.containerpage.client.ui.CmsContainerPageElementPanel::getElement()();
var handler = $this.@org.opencms.ade.containerpage.client.ui.CmsContainerPageElementPanel::m_nodeInsertHandler;
if (handler == null) {
handler = function(event) {
$this.@org.opencms.ade.containerpage.client.ui.CmsContainerPageElementPanel::checkForEditableChanges()();
};
$this.@org.opencms.ade.containerpage.client.ui.CmsContainerPageElementPanel::m_nodeInsertHandler = handler;
} else {
if (element.removeEventLister) {
element.removeEventListener("DOMNodeInserted", handler);
} else if (element.detachEvent) {
// IE specific
element.detachEvent("onDOMNodeInserted", handler);
}
}
if (element.addEventListener) {
element.addEventListener("DOMNodeInserted", handler, false);
} else if (element.attachEvent) {
// IE specific
element.attachEvent("onDOMNodeInserted", handler);
}
}-*/;
/**
* This method removes the option-bar widget from DOM and re-attaches it at it's original position.<p>
* Use to avoid mouse-over and mouse-down malfunction.<p>
*/
private void resetOptionbar() {
if (m_elementOptionBar != null) {
if (getWidgetIndex(m_elementOptionBar) >= 0) {
m_elementOptionBar.removeFromParent();
}
if (isOptionbarIFrameCollision(m_elementOptionBar.getCalculatedWidth())) {
m_elementOptionBar.getElement().getStyle().setPosition(Position.RELATIVE);
int marginLeft = getElement().getClientWidth() - m_elementOptionBar.getCalculatedWidth();
if (marginLeft > 0) {
m_elementOptionBar.getElement().getStyle().setMarginLeft(marginLeft, Unit.PX);
}
} else {
m_elementOptionBar.getElement().getStyle().clearPosition();
m_elementOptionBar.getElement().getStyle().clearMarginLeft();
}
insert(m_elementOptionBar, 0);
}
}
}
| src-gwt/org/opencms/ade/containerpage/client/ui/CmsContainerPageElementPanel.java | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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 org.opencms.ade.containerpage.client.ui;
import com.alkacon.acacia.client.I_InlineFormParent;
import com.alkacon.acacia.client.widgets.I_EditWidget;
import org.opencms.ade.containerpage.client.CmsContainerpageController;
import org.opencms.ade.containerpage.client.ui.css.I_CmsLayoutBundle;
import org.opencms.ade.containerpage.shared.CmsInheritanceInfo;
import org.opencms.ade.contenteditor.client.CmsContentEditor;
import org.opencms.gwt.client.dnd.I_CmsDraggable;
import org.opencms.gwt.client.dnd.I_CmsDropTarget;
import org.opencms.gwt.client.ui.CmsHighlightingBorder;
import org.opencms.gwt.client.util.CmsDomUtil;
import org.opencms.gwt.client.util.CmsDomUtil.Tag;
import org.opencms.gwt.client.util.CmsPositionBean;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Content element within a container-page.<p>
*
* @since 8.0.0
*/
public class CmsContainerPageElementPanel extends AbsolutePanel
implements I_CmsDraggable, HasClickHandlers, I_InlineFormParent {
/** The height necessary for a container page element. */
public static int NECESSARY_HEIGHT = 24;
/** Highlighting border for this element. */
protected CmsHighlightingBorder m_highlighting;
/** A flag which indicates whether the height has already been checked. */
private boolean m_checkedHeight;
/** Flag indicating the the editables are currently being checked. */
private boolean m_checkingEditables;
/** The elements client id. */
private String m_clientId;
/** The direct edit bar instances. */
private Map<Element, CmsListCollectorEditor> m_editables;
/** The editor click handler registration. */
private HandlerRegistration m_editorClickHandlerRegistration;
/** The option bar, holding optional function buttons. */
private CmsElementOptionBar m_elementOptionBar;
/** The overlay for expired elements. */
private Element m_expiredOverlay;
/** Indicates whether this element has settings to edit. */
private boolean m_hasSettings;
/** The inheritance info for this element. */
private CmsInheritanceInfo m_inheritanceInfo;
/** The is new element type. */
private String m_newType;
/** The registered node insert event handler. */
private JavaScriptObject m_nodeInsertHandler;
/** The no edit reason, if empty editing is allowed. */
private String m_noEditReason;
/** The parent drop target. */
private I_CmsDropContainer m_parent;
/** Flag indicating if the element resource is currently released and not expired. */
private boolean m_releasedAndNotExpired;
/** The element resource site-path. */
private String m_sitePath;
/**
* Indicates if the current user has view permissions on the element resource.
* Without view permissions, the element can neither be edited, nor moved.
**/
private boolean m_viewPermission;
/**
* Indicates if the current user has write permissions on the element resource.
* Without write permissions, the element can not be edited.
**/
private boolean m_writePermission;
/**
* Returns if the user has write permission.<p>
*
* @return <code>true</code> if the user has write permission
*/
public boolean hasWritePermission() {
return m_writePermission;
}
/**
* Sets the user write permission.<p>
*
* @param writePermission the user write permission to set
*/
public void setWritePermission(boolean writePermission) {
m_writePermission = writePermission;
}
/**
* Flag which indicates whether the new editor is disabled for this element.<p>
*/
private boolean m_disableNewEditor;
/**
* Constructor.<p>
*
* @param element the DOM element
* @param parent the drag parent
* @param clientId the client id
* @param sitePath the element site-path
* @param noEditReason the no edit reason, if empty, editing is allowed
* @param hasSettings should be true if the element has settings which can be edited
* @param hasViewPermission indicates if the current user has view permissions on the element resource
* @param hasWritePermission indicates if the current user has write permissions on the element resource
* @param releasedAndNotExpired <code>true</code> if the element resource is currently released and not expired
* @param disableNewEditor flag to disable the new editor for this element
*/
public CmsContainerPageElementPanel(
Element element,
I_CmsDropContainer parent,
String clientId,
String sitePath,
String noEditReason,
boolean hasSettings,
boolean hasViewPermission,
boolean hasWritePermission,
boolean releasedAndNotExpired,
boolean disableNewEditor) {
super((com.google.gwt.user.client.Element)element);
m_clientId = clientId;
m_sitePath = sitePath;
m_noEditReason = noEditReason;
m_hasSettings = hasSettings;
m_parent = parent;
m_disableNewEditor = disableNewEditor;
setViewPermission(hasViewPermission);
setWritePermission(hasWritePermission);
setReleasedAndNotExpired(releasedAndNotExpired);
getElement().addClassName(I_CmsLayoutBundle.INSTANCE.dragdropCss().dragElement());
}
/**
* Returns the necessary height as a CSS height string in pixels.<p>
*
* @return the necessary height as a CSS string
*/
public static String getNecessaryHeight() {
return NECESSARY_HEIGHT + "px !important";
}
/**
* @see com.google.gwt.event.dom.client.HasClickHandlers#addClickHandler(com.google.gwt.event.dom.client.ClickHandler)
*/
public HandlerRegistration addClickHandler(ClickHandler handler) {
return addDomHandler(handler, ClickEvent.getType());
}
/**
* @see com.alkacon.acacia.client.I_InlineFormParent#adoptWidget(com.alkacon.acacia.client.widgets.I_EditWidget)
*/
public void adoptWidget(I_EditWidget widget) {
getChildren().add(widget.asWidget());
adopt(widget.asWidget());
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#getDragHelper(org.opencms.gwt.client.dnd.I_CmsDropTarget)
*/
public Element getDragHelper(I_CmsDropTarget target) {
Element helper = CmsDomUtil.clone(getElement());
target.getElement().appendChild(helper);
// preparing helper styles
String width = CmsDomUtil.getCurrentStyle(helper, CmsDomUtil.Style.width);
Style style = helper.getStyle();
style.setPosition(Position.ABSOLUTE);
style.setMargin(0, Unit.PX);
style.setProperty(CmsDomUtil.Style.width.name(), width);
style.setZIndex(I_CmsLayoutBundle.INSTANCE.constants().css().zIndexDND());
helper.addClassName(I_CmsLayoutBundle.INSTANCE.dragdropCss().dragging());
helper.addClassName(org.opencms.gwt.client.ui.css.I_CmsLayoutBundle.INSTANCE.generalCss().shadow());
if (!CmsDomUtil.hasBackground(helper)) {
helper.addClassName(I_CmsLayoutBundle.INSTANCE.dragdropCss().dragElementBackground());
}
if (!CmsDomUtil.hasBorder(helper)) {
helper.addClassName(I_CmsLayoutBundle.INSTANCE.dragdropCss().dragElementBorder());
}
return helper;
}
/**
* Returns the option bar of this element.<p>
*
* @return the option bar widget
*/
public CmsElementOptionBar getElementOptionBar() {
return m_elementOptionBar;
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#getId()
*/
public String getId() {
return m_clientId;
}
/**
* Returns the inheritance info for this element.<p>
*
* @return the inheritance info for this element
*/
public CmsInheritanceInfo getInheritanceInfo() {
return m_inheritanceInfo;
}
/**
* Returns the new element type.
*
* @return the new element type
*/
public String getNewType() {
return m_newType;
}
/**
* Returns the no edit reason.<p>
*
* @return the no edit reason
*/
public String getNoEditReason() {
return m_noEditReason;
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#getParentTarget()
*/
public I_CmsDropContainer getParentTarget() {
return m_parent;
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#getPlaceholder(org.opencms.gwt.client.dnd.I_CmsDropTarget)
*/
public Element getPlaceholder(I_CmsDropTarget target) {
Element placeholder = CmsDomUtil.clone(getElement());
placeholder.addClassName(I_CmsLayoutBundle.INSTANCE.dragdropCss().dragPlaceholder());
return placeholder;
}
/**
* Returns if the element resource is currently released and not expired.<p>
*
* @return <code>true</code> if the element resource is currently released and not expired
*/
public boolean getReleasedAndNotExpired() {
return m_releasedAndNotExpired;
}
/**
* Returns the site-path.<p>
*
* @return the site-path
*/
public String getSitePath() {
return m_sitePath;
}
/**
* Returns the structure id of the element.<p>
*
* @return the structure id of the element
*/
public CmsUUID getStructureId() {
if (m_clientId == null) {
return null;
}
return new CmsUUID(CmsContainerpageController.getServerId(m_clientId));
}
/**
* Returns true if the element has settings to edit.<p>
*
* @return true if the element has settings to edit
*/
public boolean hasSettings() {
return m_hasSettings;
}
/**
* Returns if the current user has view permissions for the element resource.<p>
*
* @return <code>true</code> if the current user has view permissions for the element resource
*/
public boolean hasViewPermission() {
return m_viewPermission;
}
/**
* Hides list collector direct edit buttons, if present.<p>
*/
public void hideEditableListButtons() {
if (m_editables != null) {
for (CmsListCollectorEditor editor : m_editables.values()) {
editor.getElement().getStyle().setDisplay(Display.NONE);
}
}
}
/**
* Puts a highlighting border around the element.<p>
*/
public void highlightElement() {
if (m_highlighting == null) {
m_highlighting = new CmsHighlightingBorder(CmsPositionBean.generatePositionInfo(this), isNew()
? CmsHighlightingBorder.BorderColor.blue
: CmsHighlightingBorder.BorderColor.red);
RootPanel.get().add(m_highlighting);
} else {
m_highlighting.setPosition(CmsPositionBean.generatePositionInfo(this));
}
}
/**
* Initializes the editor click handler.<p>
*
* @param controller the container page controller instance
*/
public void initInlineEditor(final CmsContainerpageController controller) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_noEditReason)
&& !m_disableNewEditor
&& CmsContentEditor.setEditable(getElement(), true)) {
if (m_editorClickHandlerRegistration != null) {
m_editorClickHandlerRegistration.removeHandler();
}
m_editorClickHandlerRegistration = addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// if another content is already being edited, don't start another editor
if (controller.isContentEditing()) {
return;
}
Element eventTarget = event.getNativeEvent().getEventTarget().cast();
Element linkTag = CmsDomUtil.getAncestor(eventTarget, Tag.a);
if (linkTag == null) {
Element target = event.getNativeEvent().getEventTarget().cast();
while ((target != null) && (target != getElement())) {
if ("true".equals(target.getAttribute("contentEditable"))) {
controller.getHandler().openEditorForElement(CmsContainerPageElementPanel.this, true);
removeEditorHandler();
break;
} else {
target = target.getParentElement();
}
}
}
}
});
}
}
/**
* Returns if this is e newly created element.<p>
*
* @return <code>true</code> if the element is new
*/
public boolean isNew() {
return m_newType != null;
}
/**
* Returns true if the new content editor is disabled for this element.<p>
*
* @return true if the new editor is disabled for this element
*/
public boolean isNewEditorDisabled() {
return m_disableNewEditor;
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#onDragCancel()
*/
public void onDragCancel() {
clearDrag();
resetOptionbar();
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#onDrop(org.opencms.gwt.client.dnd.I_CmsDropTarget)
*/
public void onDrop(I_CmsDropTarget target) {
clearDrag();
}
/**
* @see org.opencms.gwt.client.dnd.I_CmsDraggable#onStartDrag(org.opencms.gwt.client.dnd.I_CmsDropTarget)
*/
public void onStartDrag(I_CmsDropTarget target) {
CmsDomUtil.addDisablingOverlay(getElement());
getElement().getStyle().setOpacity(0.5);
removeHighlighting();
}
/**
* @see com.google.gwt.user.client.ui.Widget#removeFromParent()
*/
@Override
public void removeFromParent() {
removeHighlighting();
super.removeFromParent();
}
/**
* Removes the highlighting border.<p>
*/
public void removeHighlighting() {
if (m_highlighting != null) {
m_highlighting.removeFromParent();
m_highlighting = null;
}
}
/**
* Removes the inline editor.<p>
*/
public void removeInlineEditor() {
CmsContentEditor.setEditable(getElement(), false);
removeEditorHandler();
}
/**
* Sets the elementOptionBar.<p>
*
* @param elementOptionBar the elementOptionBar to set
*/
public void setElementOptionBar(CmsElementOptionBar elementOptionBar) {
if ((m_elementOptionBar != null) && (getWidgetIndex(m_elementOptionBar) >= 0)) {
m_elementOptionBar.removeFromParent();
}
m_elementOptionBar = elementOptionBar;
insert(m_elementOptionBar, 0);
if (isOptionbarIFrameCollision(m_elementOptionBar.getCalculatedWidth())) {
m_elementOptionBar.getElement().getStyle().setPosition(Position.RELATIVE);
int marginLeft = getElement().getOffsetWidth() - m_elementOptionBar.getCalculatedWidth();
m_elementOptionBar.getElement().getStyle().setMarginLeft(marginLeft, Unit.PX);
}
}
/**
* Sets the element id.<p>
*
* @param id the id
*/
public void setId(String id) {
m_clientId = id;
}
/**
* Sets the inheritance info for this element.<p>
*
* @param inheritanceInfo the inheritance info for this element to set
*/
public void setInheritanceInfo(CmsInheritanceInfo inheritanceInfo) {
m_inheritanceInfo = inheritanceInfo;
}
/**
* Sets the new-type of the element.<p>
*
* @param newType the new-type
*/
public void setNewType(String newType) {
m_newType = newType;
}
/**
* Sets the no edit reason.<p>
*
* @param noEditReason the no edit reason to set
*/
public void setNoEditReason(String noEditReason) {
m_noEditReason = noEditReason;
}
/**
* Sets if the element resource is currently released and not expired.<p>
*
* @param releasedAndNotExpired <code>true</code> if the element resource is currently released and not expired
*/
public void setReleasedAndNotExpired(boolean releasedAndNotExpired) {
m_releasedAndNotExpired = releasedAndNotExpired;
if (m_releasedAndNotExpired) {
getElement().removeClassName(I_CmsLayoutBundle.INSTANCE.containerpageCss().expired());
if (m_expiredOverlay != null) {
m_expiredOverlay.removeFromParent();
m_expiredOverlay = null;
}
} else {
getElement().addClassName(I_CmsLayoutBundle.INSTANCE.containerpageCss().expired());
m_expiredOverlay = DOM.createDiv();
m_expiredOverlay.setTitle("Expired resource");
m_expiredOverlay.addClassName(I_CmsLayoutBundle.INSTANCE.containerpageCss().expiredOverlay());
getElement().appendChild(m_expiredOverlay);
}
}
/**
* Sets the site path.<p>
*
* @param sitePath the site path to set
*/
public void setSitePath(String sitePath) {
m_sitePath = sitePath;
}
/**
* Sets if the current user has view permissions for the element resource.<p>
*
* @param viewPermission the view permission to set
*/
public void setViewPermission(boolean viewPermission) {
m_viewPermission = viewPermission;
}
/**
* Shows list collector direct edit buttons (old direct edit style), if present.<p>
*/
public void showEditableListButtons() {
m_checkingEditables = true;
if (m_editables == null) {
m_editables = new HashMap<Element, CmsListCollectorEditor>();
List<Element> editables = CmsDomUtil.getElementsByClass("cms-editable", Tag.div, getElement());
if ((editables != null) && (editables.size() > 0)) {
for (Element editable : editables) {
CmsListCollectorEditor editor = new CmsListCollectorEditor(editable, m_clientId);
add(editor, (com.google.gwt.user.client.Element)editable.getParentElement());
if (CmsDomUtil.hasDimension(editable.getParentElement())) {
editor.setPosition(CmsDomUtil.getEditablePosition(editable), getElement());
} else {
editor.getElement().getStyle().setDisplay(Display.NONE);
}
m_editables.put(editable, editor);
}
}
} else {
Iterator<Entry<Element, CmsListCollectorEditor>> it = m_editables.entrySet().iterator();
while (it.hasNext()) {
Entry<Element, CmsListCollectorEditor> entry = it.next();
if (!entry.getValue().isValid()) {
entry.getValue().removeFromParent();
it.remove();
} else if (CmsDomUtil.hasDimension(entry.getValue().getElement().getParentElement())) {
entry.getValue().getElement().getStyle().clearDisplay();
entry.getValue().setPosition(
CmsDomUtil.getEditablePosition(entry.getValue().getMarkerTag()),
getElement());
}
}
List<Element> editables = CmsDomUtil.getElementsByClass("cms-editable", Tag.div, getElement());
if (editables.size() > m_editables.size()) {
for (Element editable : editables) {
if (!m_editables.containsKey(editable)) {
CmsListCollectorEditor editor = new CmsListCollectorEditor(editable, m_clientId);
add(editor, (com.google.gwt.user.client.Element)editable.getParentElement());
if (CmsDomUtil.hasDimension(editable.getParentElement())) {
editor.setPosition(CmsDomUtil.getEditablePosition(editable), getElement());
} else {
editor.getElement().getStyle().setDisplay(Display.NONE);
}
m_editables.put(editable, editor);
}
}
}
}
m_checkingEditables = false;
resetNodeInsertedHandler();
}
/**
* Checks for changes in the list collector direct edit content.<p>
*/
protected void checkForEditableChanges() {
if (!m_checkingEditables) {
m_checkingEditables = true;
Timer timer = new Timer() {
@Override
public void run() {
showEditableListButtons();
}
};
timer.schedule(500);
}
}
/**
* Returns if the list collector direct edit content has changed.<p>
*
* @return <code>true</code> if the list collector direct edit content has changed
*/
protected boolean hasChangedEditables() {
if (m_editables == null) {
return true;
}
for (CmsListCollectorEditor editor : m_editables.values()) {
if (!editor.isValid()) {
return true;
}
}
return CmsDomUtil.getElementsByClass("cms-editable", Tag.div, getElement()).size() > m_editables.size();
}
/**
* @see com.google.gwt.user.client.ui.Widget#onLoad()
*/
@Override
protected void onLoad() {
if (!m_checkedHeight) {
m_checkedHeight = true;
if (getOffsetHeight() < NECESSARY_HEIGHT) {
m_checkedHeight = true;
if (m_parent instanceof CmsContainerPageContainer) {
CmsContainerpageController.get().getHandler().enableShowSmallElements();
// CmsContainerpageController.get().enableShowSmallElementsButton();
addStyleName(org.opencms.ade.containerpage.client.ui.css.I_CmsLayoutBundle.INSTANCE.containerpageCss().smallElement());
}
}
}
resetOptionbar();
}
/**
* Removes the inline editor handler.<p>
*/
protected void removeEditorHandler() {
if (m_editorClickHandlerRegistration != null) {
m_editorClickHandlerRegistration.removeHandler();
m_editorClickHandlerRegistration = null;
}
}
/**
* Removes all styling done during drag and drop.<p>
*/
private void clearDrag() {
CmsDomUtil.removeDisablingOverlay(getElement());
m_elementOptionBar.getElement().removeClassName(
org.opencms.gwt.client.ui.css.I_CmsLayoutBundle.INSTANCE.stateCss().cmsHovering());
// using own implementation as GWT won't do it properly on IE7-8
CmsDomUtil.clearOpacity(getElement());
getElement().getStyle().clearDisplay();
}
/**
* Returns if the option bar position collides with any iframe child elements.<p>
*
* @param optionWidth the option bar witdh
*
* @return <code>true</code> if there are iframe child elements located no less than 25px below the upper edge of the element
*/
private boolean isOptionbarIFrameCollision(int optionWidth) {
if (RootPanel.getBodyElement().isOrHasChild(getElement())) {
int elementTop = getElement().getAbsoluteTop();
NodeList<Element> frames = getElement().getElementsByTagName(CmsDomUtil.Tag.iframe.name());
for (int i = 0; i < frames.getLength(); i++) {
if (((frames.getItem(i).getAbsoluteTop() - elementTop) < 25)
&& ((frames.getItem(i).getAbsoluteRight() - getElement().getAbsoluteRight()) < optionWidth)) {
return true;
}
}
}
return false;
}
/**
* Resets the node inserted handler.<p>
*/
private native void resetNodeInsertedHandler()/*-{
var $this = this;
var element = $this.@org.opencms.ade.containerpage.client.ui.CmsContainerPageElementPanel::getElement()();
var handler = $this.@org.opencms.ade.containerpage.client.ui.CmsContainerPageElementPanel::m_nodeInsertHandler;
if (handler == null) {
handler = function(event) {
$this.@org.opencms.ade.containerpage.client.ui.CmsContainerPageElementPanel::checkForEditableChanges()();
};
$this.@org.opencms.ade.containerpage.client.ui.CmsContainerPageElementPanel::m_nodeInsertHandler = handler;
} else {
if (element.removeEventLister) {
element.removeEventListener("DOMNodeInserted", handler);
} else if (element.detachEvent) {
// IE specific
element.detachEvent("onDOMNodeInserted", handler);
}
}
if (element.addEventListener) {
element.addEventListener("DOMNodeInserted", handler, false);
} else if (element.attachEvent) {
// IE specific
element.attachEvent("onDOMNodeInserted", handler);
}
}-*/;
/**
* This method removes the option-bar widget from DOM and re-attaches it at it's original position.<p>
* Use to avoid mouse-over and mouse-down malfunction.<p>
*/
private void resetOptionbar() {
if (m_elementOptionBar != null) {
if (getWidgetIndex(m_elementOptionBar) >= 0) {
m_elementOptionBar.removeFromParent();
}
if (isOptionbarIFrameCollision(m_elementOptionBar.getCalculatedWidth())) {
m_elementOptionBar.getElement().getStyle().setPosition(Position.RELATIVE);
int marginLeft = getElement().getClientWidth() - m_elementOptionBar.getCalculatedWidth();
if (marginLeft > 0) {
m_elementOptionBar.getElement().getStyle().setMarginLeft(marginLeft, Unit.PX);
}
} else {
m_elementOptionBar.getElement().getStyle().clearPosition();
m_elementOptionBar.getElement().getStyle().clearMarginLeft();
}
insert(m_elementOptionBar, 0);
}
}
}
| Improved element height check. | src-gwt/org/opencms/ade/containerpage/client/ui/CmsContainerPageElementPanel.java | Improved element height check. | <ide><path>rc-gwt/org/opencms/ade/containerpage/client/ui/CmsContainerPageElementPanel.java
<ide> import java.util.Map.Entry;
<ide>
<ide> import com.google.gwt.core.client.JavaScriptObject;
<add>import com.google.gwt.core.client.Scheduler;
<add>import com.google.gwt.core.client.Scheduler.ScheduledCommand;
<ide> import com.google.gwt.dom.client.Element;
<ide> import com.google.gwt.dom.client.NodeList;
<ide> import com.google.gwt.dom.client.Style;
<ide> /** The elements client id. */
<ide> private String m_clientId;
<ide>
<add> /**
<add> * Flag which indicates whether the new editor is disabled for this element.<p>
<add> */
<add> private boolean m_disableNewEditor;
<add>
<ide> /** The direct edit bar instances. */
<ide> private Map<Element, CmsListCollectorEditor> m_editables;
<ide>
<ide> * Without write permissions, the element can not be edited.
<ide> **/
<ide> private boolean m_writePermission;
<del>
<del> /**
<del> * Returns if the user has write permission.<p>
<del> *
<del> * @return <code>true</code> if the user has write permission
<del> */
<del> public boolean hasWritePermission() {
<del>
<del> return m_writePermission;
<del> }
<del>
<del> /**
<del> * Sets the user write permission.<p>
<del> *
<del> * @param writePermission the user write permission to set
<del> */
<del> public void setWritePermission(boolean writePermission) {
<del>
<del> m_writePermission = writePermission;
<del> }
<del>
<del> /**
<del> * Flag which indicates whether the new editor is disabled for this element.<p>
<del> */
<del> private boolean m_disableNewEditor;
<ide>
<ide> /**
<ide> * Constructor.<p>
<ide> public boolean hasViewPermission() {
<ide>
<ide> return m_viewPermission;
<add> }
<add>
<add> /**
<add> * Returns if the user has write permission.<p>
<add> *
<add> * @return <code>true</code> if the user has write permission
<add> */
<add> public boolean hasWritePermission() {
<add>
<add> return m_writePermission;
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> /**
<add> * Sets the user write permission.<p>
<add> *
<add> * @param writePermission the user write permission to set
<add> */
<add> public void setWritePermission(boolean writePermission) {
<add>
<add> m_writePermission = writePermission;
<add> }
<add>
<add> /**
<ide> * Shows list collector direct edit buttons (old direct edit style), if present.<p>
<ide> */
<ide> public void showEditableListButtons() {
<ide> @Override
<ide> protected void onLoad() {
<ide>
<del> if (!m_checkedHeight) {
<del> m_checkedHeight = true;
<del> if (getOffsetHeight() < NECESSARY_HEIGHT) {
<del> m_checkedHeight = true;
<del> if (m_parent instanceof CmsContainerPageContainer) {
<del> CmsContainerpageController.get().getHandler().enableShowSmallElements();
<del> // CmsContainerpageController.get().enableShowSmallElementsButton();
<del> addStyleName(org.opencms.ade.containerpage.client.ui.css.I_CmsLayoutBundle.INSTANCE.containerpageCss().smallElement());
<add> if (!hasCheckedHeight() && (getParentTarget() instanceof CmsContainerPageContainer)) {
<add> Scheduler.get().scheduleDeferred(new ScheduledCommand() {
<add>
<add> public void execute() {
<add>
<add> if (!hasCheckedHeight()
<add> && (CmsPositionBean.generatePositionInfo(getElement()).getHeight() < NECESSARY_HEIGHT)
<add> && (CmsPositionBean.getInnerDimensions(getElement()).getHeight() < NECESSARY_HEIGHT)) {
<add>
<add> CmsContainerpageController.get().getHandler().enableShowSmallElements();
<add> addStyleName(org.opencms.ade.containerpage.client.ui.css.I_CmsLayoutBundle.INSTANCE.containerpageCss().smallElement());
<add> }
<add> setCheckedHeight(true);
<ide> }
<del> }
<add> });
<ide> }
<ide> resetOptionbar();
<ide> }
<ide> m_editorClickHandlerRegistration.removeHandler();
<ide> m_editorClickHandlerRegistration = null;
<ide> }
<add> }
<add>
<add> /**
<add> * Returns if the minimum element height has been checked.<p>
<add> *
<add> * @return <code>true</code> if the minimum element height has been checked
<add> */
<add> boolean hasCheckedHeight() {
<add>
<add> return m_checkedHeight;
<add> }
<add>
<add> /**
<add> * Sets the checked height flag.<p>
<add> *
<add> * @param checked the checked height flag
<add> */
<add> void setCheckedHeight(boolean checked) {
<add>
<add> m_checkedHeight = checked;
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | df5a468f736f4d9a405b9ba746ef17707b506b30 | 0 | nengxu/OrientDB,nengxu/OrientDB,vivosys/orientdb,nengxu/OrientDB,vivosys/orientdb,nengxu/OrientDB,vivosys/orientdb,vivosys/orientdb | /*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.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 com.orientechnologies.orient.test.database.speed;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import com.orientechnologies.common.test.SpeedTestMonoThread;
import com.orientechnologies.orient.core.db.record.ODatabaseFlat;
import com.orientechnologies.orient.core.record.impl.ORecordFlat;
import com.orientechnologies.orient.core.storage.OStorage;
public class CreateRelationshipsSpeedTest extends SpeedTestMonoThread {
private ODatabaseFlat database;
private ORecordFlat record;
public CreateRelationshipsSpeedTest() {
super(1000000);
}
@Override
public void init() throws IOException {
if (!database.getClusterNames().contains("Animal"))
database.addCluster("Animal", OStorage.CLUSTER_TYPE.PHYSICAL);
if (!database.getClusterNames().contains("Vaccinate"))
database.getStorage().addCluster("Vaccinate", OStorage.CLUSTER_TYPE.PHYSICAL);
}
@Override
public void cycle() throws UnsupportedEncodingException {
record.value(data.getCyclesDone() + "|" + System.currentTimeMillis() + "|AAA").save("Vaccinate");
record.value(
data.getCyclesDone() + "|Gipsy|Cat|European|Italy|" + (data.getCyclesDone() + 300) + ".00|#Vaccinate:"
+ data.getCyclesDone()).save("Animal");
}
}
| tests/src/test/java/com/orientechnologies/orient/test/database/speed/CreateRelationshipsSpeedTest.java | /*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.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 com.orientechnologies.orient.test.database.speed;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import com.orientechnologies.common.test.SpeedTestMonoThread;
import com.orientechnologies.orient.core.db.record.ODatabaseFlat;
import com.orientechnologies.orient.core.record.impl.ORecordFlat;
import com.orientechnologies.orient.core.storage.OStorage;
public class CreateRelationshipsSpeedTest extends SpeedTestMonoThread {
private ODatabaseFlat database;
private ORecordFlat record;
public CreateRelationshipsSpeedTest() {
super(1000000);
}
@Override
public void init() throws IOException {
if (!database.getClusterNames().contains("Animal"))
database.getStorage().addCluster("Animal", OStorage.CLUSTER_TYPE.PHYSICAL);
if (!database.getClusterNames().contains("Vaccinate"))
database.getStorage().addCluster("Vaccinate", OStorage.CLUSTER_TYPE.PHYSICAL);
}
@Override
public void cycle() throws UnsupportedEncodingException {
record.value(data.getCyclesDone() + "|" + System.currentTimeMillis() + "|AAA").save("Vaccinate");
record.value(
data.getCyclesDone() + "|Gipsy|Cat|European|Italy|" + (data.getCyclesDone() + 300) + ".00|#Vaccinate:"
+ data.getCyclesDone()).save("Animal");
}
}
| Added new method addCluster() to avoid to call the storage directly
git-svn-id: 9ddf022f45b579842a47abc018ed2b18cdc52108@3150 3625ad7b-9c83-922f-a72b-73d79161f2ea
| tests/src/test/java/com/orientechnologies/orient/test/database/speed/CreateRelationshipsSpeedTest.java | Added new method addCluster() to avoid to call the storage directly | <ide><path>ests/src/test/java/com/orientechnologies/orient/test/database/speed/CreateRelationshipsSpeedTest.java
<ide> import com.orientechnologies.orient.core.storage.OStorage;
<ide>
<ide> public class CreateRelationshipsSpeedTest extends SpeedTestMonoThread {
<del> private ODatabaseFlat database;
<del> private ORecordFlat record;
<add> private ODatabaseFlat database;
<add> private ORecordFlat record;
<ide>
<del> public CreateRelationshipsSpeedTest() {
<del> super(1000000);
<del> }
<add> public CreateRelationshipsSpeedTest() {
<add> super(1000000);
<add> }
<ide>
<del> @Override
<del> public void init() throws IOException {
<del> if (!database.getClusterNames().contains("Animal"))
<del> database.getStorage().addCluster("Animal", OStorage.CLUSTER_TYPE.PHYSICAL);
<add> @Override
<add> public void init() throws IOException {
<add> if (!database.getClusterNames().contains("Animal"))
<add> database.addCluster("Animal", OStorage.CLUSTER_TYPE.PHYSICAL);
<ide>
<del> if (!database.getClusterNames().contains("Vaccinate"))
<del> database.getStorage().addCluster("Vaccinate", OStorage.CLUSTER_TYPE.PHYSICAL);
<del> }
<add> if (!database.getClusterNames().contains("Vaccinate"))
<add> database.getStorage().addCluster("Vaccinate", OStorage.CLUSTER_TYPE.PHYSICAL);
<add> }
<ide>
<del> @Override
<del> public void cycle() throws UnsupportedEncodingException {
<del> record.value(data.getCyclesDone() + "|" + System.currentTimeMillis() + "|AAA").save("Vaccinate");
<del> record.value(
<del> data.getCyclesDone() + "|Gipsy|Cat|European|Italy|" + (data.getCyclesDone() + 300) + ".00|#Vaccinate:"
<del> + data.getCyclesDone()).save("Animal");
<del> }
<add> @Override
<add> public void cycle() throws UnsupportedEncodingException {
<add> record.value(data.getCyclesDone() + "|" + System.currentTimeMillis() + "|AAA").save("Vaccinate");
<add> record.value(
<add> data.getCyclesDone() + "|Gipsy|Cat|European|Italy|" + (data.getCyclesDone() + 300) + ".00|#Vaccinate:"
<add> + data.getCyclesDone()).save("Animal");
<add> }
<ide> } |
|
Java | lgpl-2.1 | 40f3ab84202b76281abbb1fa794e35f6d414af23 | 0 | svartika/ccnx,ebollens/ccnmp,ebollens/ccnmp,ebollens/ccnmp,cawka/ndnx,cawka/ndnx,svartika/ccnx,svartika/ccnx,cawka/ndnx,cawka/ndnx,ebollens/ccnmp,svartika/ccnx,svartika/ccnx,svartika/ccnx,svartika/ccnx,cawka/ndnx | package test.ccn.security.crypto;
import java.util.Arrays;
import java.util.Random;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.parc.ccn.security.crypto.CCNDigestHelper;
import com.parc.ccn.security.crypto.MerklePath;
import com.parc.ccn.security.crypto.MerkleTree;
public class MerkleTreeTest {
protected static Random _rand = new Random(); // don't need SecureRandom
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@Test
public void testMerkleTree() throws Exception {
int [] sizes = new int[]{128,256,512,4096};
try {
testTree(0, sizes[0], false);
Assert.fail("MerkleTree should throw an exception for tree sizes < 2.");
} catch (IllegalArgumentException e) {
// ok
}
try {
testTree(1, sizes[0], false);
Assert.fail("MerkleTree should throw an exception for tree sizes < 2.");
} catch (IllegalArgumentException e) {
// ok
}
System.out.println("Testing small trees.");
for (int i=2; i < 515; ++i) {
testTree(i,sizes[i%sizes.length],false);
}
System.out.println("Testing large trees.");
int [] nodecounts = new int[]{1000,1001,1025,1098,1536,1575,2053,5147,8900,9998,9999,10000};
for (int i=0; i < nodecounts.length; ++i) {
testTree(nodecounts[i],sizes[i%sizes.length],false);
}
}
public static void testTree(int numLeaves, int nodeLength, boolean digest) throws Exception {
try {
byte [][] data = makeContent(numLeaves, nodeLength, digest);
testTree(data, numLeaves, digest);
} catch (Exception e) {
System.out.println("Building tree of " + numLeaves + " Nodes. Caught a " + e.getClass().getName() + " exception: " + e.getMessage());
throw e;
}
}
public static byte [][] makeContent(int numNodes, int nodeLength, boolean digest) {
byte [][] bufs = new byte[numNodes][];
byte [] tmpbuf = null;
if (digest)
tmpbuf = new byte[nodeLength];
int blocklen = (digest ? CCNDigestHelper.DEFAULT_DIGEST_LENGTH : nodeLength);
for (int i=0; i < numNodes; ++i) {
bufs[i] = new byte[blocklen];
if (digest) {
_rand.nextBytes(tmpbuf);
bufs[i] = CCNDigestHelper.digest(tmpbuf);
} else {
_rand.nextBytes(bufs[i]);
}
}
return bufs;
}
public static void testTree(byte [][] content, int count, boolean digest) {
// Generate a merkle tree. Verify each path for the content.
MerkleTree tree = new MerkleTree(content, digest, count, 0,
((count-1) >= 0) && ((count-1) < content.length) ? content[count-1].length : 0);
MerklePath [] paths = new MerklePath[count];
for (int i=0; i < count; ++i) {
paths[i] = tree.path(i);
//checkPath(tree, paths[i]);
byte [] root = paths[i].root(content[i],digest);
boolean result = Arrays.equals(root, tree.root());
if (!result) {
System.out.println("Constructed tree of " + count + " blocks (of " + content.length + "), numleaves: " +
tree.numLeaves() + " max pathlength: " + tree.maxDepth());
System.out.println("Path " + i + " verified for leaf " + paths[i].leafNodeIndex() + "? " + result);
}
Assert.assertTrue("Path " + i + " failed to verify.", result);
try {
byte [] encodedPath = paths[i].derEncodedPath();
DigestInfo info = CCNDigestHelper.digestDecoder(encodedPath);
MerklePath decoded = new MerklePath(info.getDigest());
if (!decoded.equals(paths[i])) {
System.out.println("Path " + i + " failed to encode and decode.");
Assert.fail("Path " + i + " failed to encode and decode.");
}
} catch (Exception e) {
System.out.println("Exception encoding path " + i + " :" + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
Assert.fail("Exception encoding path " + i + " :" + e.getClass().getName() + ": " + e.getMessage());
}
}
}
protected static void checkPath(MerkleTree tree, MerklePath path) {
// Check path against the tree, and see if it contains the hashes it should.
System.out.println("Checking path for nodeID: " + path.leafNodeIndex() + " path length: " + path.pathLength() + " num components: " + path.pathLength());
StringBuffer buf = new StringBuffer("Path nodes: ");
for (int i=0; i < path.pathLength(); ++i) {
buf.append(tree.getNodeIndex(path.entry(i)));
buf.append(" ");
}
System.out.println(buf.toString());
}
}
| Java_CCN/test/ccn/security/crypto/MerkleTreeTest.java | package test.ccn.security.crypto;
import java.util.Arrays;
import java.util.Random;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.parc.ccn.security.crypto.CCNDigestHelper;
import com.parc.ccn.security.crypto.MerklePath;
import com.parc.ccn.security.crypto.MerkleTree;
public class MerkleTreeTest {
protected static Random _rand = new Random(); // don't need SecureRandom
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@Test
public void testMerkleTree() {
int [] sizes = new int[]{128,256,512,4096};
try {
testTree(0, sizes[0], false);
Assert.fail("MerkleTree should throw an exception for tree sizes < 2.");
} catch (IllegalArgumentException e) {
// ok
}
try {
testTree(1, sizes[0], false);
Assert.fail("MerkleTree should throw an exception for tree sizes < 2.");
} catch (IllegalArgumentException e) {
// ok
}
System.out.println("Testing small trees.");
for (int i=2; i < 515; ++i) {
testTree(i,sizes[i%sizes.length],false);
}
System.out.println("Testing large trees.");
int [] nodecounts = new int[]{1000,1001,1025,1098,1536,1575,2053,5147,8900,9998,9999,10000};
for (int i=0; i < nodecounts.length; ++i) {
testTree(nodecounts[i],sizes[i%sizes.length],false);
}
}
public static void testTree(int numLeaves, int nodeLength, boolean digest) {
try {
byte [][] data = makeContent(numLeaves, nodeLength, digest);
testTree(data, numLeaves, digest);
} catch (Exception e) {
System.out.println("Building tree of " + numLeaves + " Nodes. Caught a " + e.getClass().getName() + " exception: " + e.getMessage());
e.printStackTrace();
}
}
public static byte [][] makeContent(int numNodes, int nodeLength, boolean digest) {
byte [][] bufs = new byte[numNodes][];
byte [] tmpbuf = null;
if (digest)
tmpbuf = new byte[nodeLength];
int blocklen = (digest ? CCNDigestHelper.DEFAULT_DIGEST_LENGTH : nodeLength);
for (int i=0; i < numNodes; ++i) {
bufs[i] = new byte[blocklen];
if (digest) {
_rand.nextBytes(tmpbuf);
bufs[i] = CCNDigestHelper.digest(tmpbuf);
} else {
_rand.nextBytes(bufs[i]);
}
}
return bufs;
}
public static void testTree(byte [][] content, int count, boolean digest) {
// Generate a merkle tree. Verify each path for the content.
MerkleTree tree = new MerkleTree(content, digest, count, 0, content[count-1].length);
MerklePath [] paths = new MerklePath[count];
for (int i=0; i < count; ++i) {
paths[i] = tree.path(i);
//checkPath(tree, paths[i]);
byte [] root = paths[i].root(content[i],digest);
boolean result = Arrays.equals(root, tree.root());
if (!result) {
System.out.println("Constructed tree of " + count + " blocks (of " + content.length + "), numleaves: " +
tree.numLeaves() + " max pathlength: " + tree.maxDepth());
System.out.println("Path " + i + " verified for leaf " + paths[i].leafNodeIndex() + "? " + result);
}
Assert.assertTrue("Path " + i + " failed to verify.", result);
try {
byte [] encodedPath = paths[i].derEncodedPath();
DigestInfo info = CCNDigestHelper.digestDecoder(encodedPath);
MerklePath decoded = new MerklePath(info.getDigest());
if (!decoded.equals(paths[i])) {
System.out.println("Path " + i + " failed to encode and decode.");
Assert.fail("Path " + i + " failed to encode and decode.");
}
} catch (Exception e) {
System.out.println("Exception encoding path " + i + " :" + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
Assert.fail("Exception encoding path " + i + " :" + e.getClass().getName() + ": " + e.getMessage());
}
}
}
protected static void checkPath(MerkleTree tree, MerklePath path) {
// Check path against the tree, and see if it contains the hashes it should.
System.out.println("Checking path for nodeID: " + path.leafNodeIndex() + " path length: " + path.pathLength() + " num components: " + path.pathLength());
StringBuffer buf = new StringBuffer("Path nodes: ");
for (int i=0; i < path.pathLength(); ++i) {
buf.append(tree.getNodeIndex(path.entry(i)));
buf.append(" ");
}
System.out.println(buf.toString());
}
}
| Fixed exception-expecting tests...
| Java_CCN/test/ccn/security/crypto/MerkleTreeTest.java | Fixed exception-expecting tests... | <ide><path>ava_CCN/test/ccn/security/crypto/MerkleTreeTest.java
<ide> }
<ide>
<ide> @Test
<del> public void testMerkleTree() {
<add> public void testMerkleTree() throws Exception {
<ide> int [] sizes = new int[]{128,256,512,4096};
<ide>
<ide> try {
<ide> }
<ide> }
<ide>
<del> public static void testTree(int numLeaves, int nodeLength, boolean digest) {
<add> public static void testTree(int numLeaves, int nodeLength, boolean digest) throws Exception {
<ide> try {
<ide> byte [][] data = makeContent(numLeaves, nodeLength, digest);
<ide> testTree(data, numLeaves, digest);
<ide> } catch (Exception e) {
<ide> System.out.println("Building tree of " + numLeaves + " Nodes. Caught a " + e.getClass().getName() + " exception: " + e.getMessage());
<del> e.printStackTrace();
<add> throw e;
<ide> }
<ide> }
<ide>
<ide>
<ide> public static void testTree(byte [][] content, int count, boolean digest) {
<ide> // Generate a merkle tree. Verify each path for the content.
<del> MerkleTree tree = new MerkleTree(content, digest, count, 0, content[count-1].length);
<add> MerkleTree tree = new MerkleTree(content, digest, count, 0,
<add> ((count-1) >= 0) && ((count-1) < content.length) ? content[count-1].length : 0);
<ide>
<ide> MerklePath [] paths = new MerklePath[count];
<ide> for (int i=0; i < count; ++i) { |
|
JavaScript | mit | 4d4b7a011516d6fafdbc21f0fb7e6223c92e108f | 0 | conveyal/analysis-ui,conveyal/analysis-ui,conveyal/analysis-ui,conveyal/scenario-editor,conveyal/scenario-editor | /**
* @flow
*
* Redux actions related to Single Point Analysis requests.
*/
import lonlat from '@conveyal/lonlat'
import {fetchMultiple} from '@conveyal/woonerf/fetch'
import get from 'lodash/get'
import {createAction} from 'redux-actions'
import {
ANALYSIS_URL,
FETCH_TRAVEL_TIME_SURFACE,
PROFILE_REQUEST_DEFAULTS,
TRAVEL_TIME_PERCENTILES
} from '../../constants'
import {
PERFORMING_ANALYSIS,
INITIALIZING_CLUSTER
} from '../../constants/analysis-status'
import * as select from '../../selectors'
import downloadGeoTIFF from '../../utils/download-geotiff'
import localStorage from '../../utils/local-storage'
import timeout from '../../utils/timeout'
import R5Version from '../../modules/r5-version'
import type {GetState, LonLat} from '../../types'
import {parseTimesData} from './parse-times-data'
const RETRY_TIMEOUT_MILLISECONDS = 1000 * 30 // 30 seconds
const MAX_RETRIES = 10
export const clearComparisonProject = createAction('clear comparison project')
export const setActiveVariant = createAction('set active variant')
export const setComparisonProject = createAction('set comparison project')
export const setDestination = createAction('set destination')
export const setIsochroneCutoff = createAction('set isochrone cutoff')
export const setIsochroneFetchStatus = createAction(
'set isochrone fetch status'
)
export const setIsochroneLonLat = createAction('set isochrone lonlat', x =>
lonlat(x)
)
export const setIsochroneResults = createAction('set isochrone results')
export const setScenarioApplicationErrors = createAction(
'set scenario application errors'
)
export const setScenarioApplicationWarnings = createAction(
'set scenario application warnings'
)
export const selectBookmark = createAction('select bookmark')
export const setTravelTimeSurface = createAction('set travel time surface')
export const setComparisonTravelTimeSurface = createAction(
'set comparison travel time surface'
)
/**
* Save the profile request parameters to local storage
*/
export const setEntireProfileRequest = createAction('set profile request')
export const setProfileRequest = createAction('update profile request')
export const setDisplayedProfileRequest = createAction('set displayed profile request')
const requestSettingsKey = 'profileRequestSettings'
const getStoredSettings = () => JSON.parse(localStorage.getItem(requestSettingsKey) || '{}')
export const storeProfileRequestSettings = (profileRequest: any) =>
(dispatch: Dispatch, getState: GetState) => {
const state = getState()
const regionId = select.currentRegionId(state, {})
const storedSettings = getStoredSettings()
storedSettings[regionId] = profileRequest
localStorage.setItem(requestSettingsKey, JSON.stringify(storedSettings))
dispatch(setEntireProfileRequest(profileRequest))
}
export const loadProfileRequestSettings = (regionId: string) => {
const storedProfileRequestSettings = getStoredSettings()
const profileRequestSettings = storedProfileRequestSettings[regionId]
if (profileRequestSettings) {
return [
setEntireProfileRequest({
...PROFILE_REQUEST_DEFAULTS, // keep this in case we want to add new fields / change the defaults
...profileRequestSettings
}),
R5Version.actions.setCurrentR5Version(profileRequestSettings.workerVersion)
]
} else {
return [
setEntireProfileRequest(PROFILE_REQUEST_DEFAULTS),
R5Version.actions.setCurrentR5Version(R5Version.RECOMMENDED_R5_VERSION)
]
}
}
const straightLineDistance = () =>
/compareToStraightLineDistance=([0-9.]+)/.exec(window.search)
/**
* Handle fetching and constructing the travel time surface and comparison
* surface and dispatching updates along the way.
*/
export const fetchTravelTimeSurface = (asGeoTIFF?: boolean) =>
(dispatch: Dispatch, getState: GetState) => {
dispatch(setIsochroneFetchStatus(PERFORMING_ANALYSIS))
const state = getState()
const project = select.currentProject(state)
const currentProjectId = select.currentProjectId(state)
const comparisonInProgress = select.comparisonInProgress(state)
const comparisonProject = select.comparisonProject(state)
const workerVersion = R5Version.select.currentR5Version(state, {})
const profileRequest = {
...PROFILE_REQUEST_DEFAULTS,
...get(state, 'analysis.profileRequest', {}),
workerVersion,
percentiles: TRAVEL_TIME_PERCENTILES,
projectId: currentProjectId
}
// Store the profile request settings for the user/region
dispatch(storeProfileRequestSettings(profileRequest))
let retryCount = 0
async function retry (response) {
if (response.status === 202 && ++retryCount < MAX_RETRIES) {
dispatch(setIsochroneFetchStatus(INITIALIZING_CLUSTER))
await timeout(RETRY_TIMEOUT_MILLISECONDS)
return true
} else {
return false
}
}
const headers = {}
if (asGeoTIFF === true) {
headers.Accept = 'image/tiff'
}
const fetches = [{
url: ANALYSIS_URL,
options: {
body: profileRequest,
headers,
method: 'post'
},
retry
}]
if (comparisonInProgress && !straightLineDistance()) {
fetches.push({
url: ANALYSIS_URL,
options: {
body: {
...profileRequest,
projectId: state.analysis.comparisonProjectId, // override with comparison values
variantIndex: state.analysis.comparisonVariant
},
headers,
method: 'post'
},
retry
})
}
return dispatch(fetchMultiple({
type: FETCH_TRAVEL_TIME_SURFACE,
fetches,
next: asGeoTIFF === true
? handleGeoTIFF(
`${get(project, 'name', '')}-${profileRequest.variantIndex}`,
`${get(comparisonProject, 'name', '')}-${profileRequest.variantIndex}`
)
: handleSurface(profileRequest)
}))
}
/**
* Handle the response for a GeoTIFF request.
*/
const handleGeoTIFF = (name, comparisonName) => (responses) => {
downloadGeoTIFF({
data: responses[0].value,
filename: `analysis-geotiff-${name}.geotiff`
})
if (responses[1] && responses[1].value) {
downloadGeoTIFF({
data: responses[1].value,
filename: `analysis-geotiff-${comparisonName}.geotiff`
})
}
return setIsochroneFetchStatus(false)
}
/**
* Handle response for a travel time surface request.
*/
export const handleSurface = (profileRequest: any) => (error: any, responses: any) => {
if (error) {
return [
setScenarioApplicationWarnings(null),
setTravelTimeSurface(null),
setComparisonTravelTimeSurface(null),
setIsochroneFetchStatus(false),
// responses is just the single response when there was an error
setScenarioApplicationErrors(Array.isArray(responses.value)
? responses.value
: [responses.value])
]
}
try {
const surface = responseToSurface(responses[0].value)
const comparisonSurface = responses.length > 1
? responseToSurface(responses[1].value)
: undefined
let straightLineSurface = null
if (straightLineDistance()) {
const speedKmh = parseFloat(straightLineDistance()[1])
straightLineSurface = createStraightLineDistanceTravelTimeSurface(
surface,
{lon: profileRequest.fromLon, lat: profileRequest.fromLat},
speedKmh
)
}
return [
setScenarioApplicationErrors(null),
setScenarioApplicationWarnings([
...surface.warnings,
...(comparisonSurface ? comparisonSurface.warnings : [])
]),
setTravelTimeSurface(surface),
setComparisonTravelTimeSurface(straightLineSurface || comparisonSurface),
setIsochroneFetchStatus(false),
// Attempt to keep the UI in sync if changes have been made
setDisplayedProfileRequest(profileRequest)
]
} catch (e) {
console.error(e)
throw e
}
}
// exported for testing
export function responseToSurface (response: any): any {
if (response[0] && response[0].title) {
// this is a list of errors from the backend
return {
errors: response,
warnings: []
}
}
return parseTimesData(response)
}
/**
* Create a straight-line-distance travel time surface. This is a hidden feature
* to allow a particular client to demonstrate that straight-line distance _from
* the origin_ is absurd when used to compute transit access. Yes, people
* actually do this.
*/
function createStraightLineDistanceTravelTimeSurface (surface: any, origin: LonLat, speedKmh: number) {
const array = new Uint8ClampedArray(surface.depth)
return {
...surface,
errors: [],
warnings: [{
title: `Comparison project is using straight line distance with speed ${speedKmh} km/h`,
messages: []
}],
get (x, y) {
const ll = lonlat.fromPixel({
x: x + surface.west,
y: y + surface.north
}, surface.zoom)
const distMeters = lonlat.toLeaflet(ll).distanceTo([origin.lat, origin.lon])
const timeMinutes = (distMeters / 1000 / speedKmh * 60) | 0
for (let i = 0; i < surface.depth; i++) {
array[i] = timeMinutes
}
return array
}
}
}
| lib/actions/analysis/index.js | /**
* @flow
*
* Redux actions related to Single Point Analysis requests.
*/
import lonlat from '@conveyal/lonlat'
import {fetchMultiple} from '@conveyal/woonerf/fetch'
import get from 'lodash/get'
import {createAction} from 'redux-actions'
import {
ANALYSIS_URL,
FETCH_TRAVEL_TIME_SURFACE,
PROFILE_REQUEST_DEFAULTS,
TRAVEL_TIME_PERCENTILES
} from '../../constants'
import {
PERFORMING_ANALYSIS,
INITIALIZING_CLUSTER
} from '../../constants/analysis-status'
import * as select from '../../selectors'
import downloadGeoTIFF from '../../utils/download-geotiff'
import localStorage from '../../utils/local-storage'
import timeout from '../../utils/timeout'
import R5Version from '../../modules/r5-version'
import type {GetState, LonLat} from '../../types'
import {parseTimesData} from './parse-times-data'
const RETRY_TIMEOUT_MILLISECONDS = 1000 * 30 // 30 seconds
const MAX_RETRIES = 10
export const clearComparisonProject = createAction('clear comparison project')
export const setActiveVariant = createAction('set active variant')
export const setComparisonProject = createAction('set comparison project')
export const setDestination = createAction('set destination')
export const setIsochroneCutoff = createAction('set isochrone cutoff')
export const setIsochroneFetchStatus = createAction(
'set isochrone fetch status'
)
export const setIsochroneLonLat = createAction('set isochrone lonlat', x =>
lonlat(x)
)
export const setIsochroneResults = createAction('set isochrone results')
export const setScenarioApplicationErrors = createAction(
'set scenario application errors'
)
export const setScenarioApplicationWarnings = createAction(
'set scenario application warnings'
)
export const selectBookmark = createAction('select bookmark')
export const setTravelTimeSurface = createAction('set travel time surface')
export const setComparisonTravelTimeSurface = createAction(
'set comparison travel time surface'
)
/**
* Save the profile request parameters to local storage
*/
export const setEntireProfileRequest = createAction('set profile request')
export const setProfileRequest = createAction('update profile request')
export const setDisplayedProfileRequest = createAction('set displayed profile request')
const requestSettingsKey = 'profileRequestSettings'
const getStoredSettings = () => JSON.parse(localStorage.getItem(requestSettingsKey) || '{}')
export const storeProfileRequestSettings = (profileRequest: any) =>
(dispatch: Dispatch, getState: GetState) => {
const state = getState()
const regionId = select.currentRegionId(state, {})
const storedSettings = getStoredSettings()
storedSettings[regionId] = profileRequest
localStorage.setItem(requestSettingsKey, JSON.stringify(storedSettings))
dispatch(setEntireProfileRequest(profileRequest))
}
export const loadProfileRequestSettings = (regionId: string) => {
const storedProfileRequestSettings = getStoredSettings()
const profileRequestSettings = storedProfileRequestSettings[regionId]
if (profileRequestSettings) {
return [
setEntireProfileRequest({
...PROFILE_REQUEST_DEFAULTS, // keep this in case we want to add new fields / change the defaults
...profileRequestSettings
}),
R5Version.actions.setCurrentR5Version(profileRequestSettings.workerVersion)
]
} else {
return [
setEntireProfileRequest(PROFILE_REQUEST_DEFAULTS),
R5Version.actions.setCurrentR5Version(R5Version.RECOMMENDED_R5_VERSION)
]
}
}
const straightLineDistance = () =>
/compareToStraightLineDistance=([0-9.]+)/.exec(window.search)
/**
* Handle fetching and constructing the travel time surface and comparison
* surface and dispatching updates along the way.
*/
export const fetchTravelTimeSurface = (asGeoTIFF?: boolean) =>
(dispatch: Dispatch, getState: GetState) => {
dispatch(setIsochroneFetchStatus(PERFORMING_ANALYSIS))
const state = getState()
const project = select.currentProject(state)
const currentProjectId = select.currentProjectId(state)
const comparisonInProgress = select.comparisonInProgress(state)
const comparisonProject = select.comparisonProject(state)
const workerVersion = R5Version.select.currentR5Version(state, {})
const profileRequest = {
...PROFILE_REQUEST_DEFAULTS,
...get(state, 'analysis.profileRequest', {}),
workerVersion,
percentiles: TRAVEL_TIME_PERCENTILES,
projectId: currentProjectId
}
// Store the profile request settings for the user/region
dispatch(storeProfileRequestSettings(profileRequest))
let retryCount = 0
async function retry (response) {
if (response.status === 202 && ++retryCount < MAX_RETRIES) {
dispatch(setIsochroneFetchStatus(INITIALIZING_CLUSTER))
await timeout(RETRY_TIMEOUT_MILLISECONDS)
return true
} else {
return false
}
}
const headers = {}
if (asGeoTIFF === true) {
headers.Accept = 'image/tiff'
}
const fetches = [{
url: ANALYSIS_URL,
options: {
body: profileRequest,
headers,
method: 'post'
},
retry
}]
if (comparisonInProgress && !straightLineDistance()) {
fetches.push({
url: ANALYSIS_URL,
options: {
body: {
...profileRequest,
projectId: state.analysis.comparisonProjectId, // override with comparison values
variantIndex: state.analysis.comparisonVariant
},
headers,
method: 'post'
},
retry
})
}
return dispatch(fetchMultiple({
type: FETCH_TRAVEL_TIME_SURFACE,
fetches,
next: asGeoTIFF
? handleGeoTIFF(
`${get(project, 'name', '')}-${profileRequest.variantIndex}`,
`${get(comparisonProject, 'name', '')}-${profileRequest.variantIndex}`
)
: handleSurface(profileRequest)
}))
}
/**
* Handle the response for a GeoTIFF request.
*/
const handleGeoTIFF = (name, comparisonName) => (responses) => {
downloadGeoTIFF({
data: responses[0].value,
filename: `analysis-geotiff-${name}.geotiff`
})
if (responses[1] && responses[1].value) {
downloadGeoTIFF({
data: responses[1].value,
filename: `analysis-geotiff-${comparisonName}.geotiff`
})
}
return setIsochroneFetchStatus(false)
}
/**
* Handle response for a travel time surface request.
*/
export const handleSurface = (profileRequest: any) => (error: any, responses: any) => {
if (error) {
return [
setScenarioApplicationWarnings(null),
setTravelTimeSurface(null),
setComparisonTravelTimeSurface(null),
setIsochroneFetchStatus(false),
// responses is just the single response when there was an error
setScenarioApplicationErrors(Array.isArray(responses.value)
? responses.value
: [responses.value])
]
}
try {
const surface = responseToSurface(responses[0].value)
const comparisonSurface = responses.length > 1
? responseToSurface(responses[1].value)
: undefined
let straightLineSurface = null
if (straightLineDistance()) {
const speedKmh = parseFloat(straightLineDistance()[1])
straightLineSurface = createStraightLineDistanceTravelTimeSurface(
surface,
{lon: profileRequest.fromLon, lat: profileRequest.fromLat},
speedKmh
)
}
return [
setScenarioApplicationErrors(null),
setScenarioApplicationWarnings([
...surface.warnings,
...(comparisonSurface ? comparisonSurface.warnings : [])
]),
setTravelTimeSurface(surface),
setComparisonTravelTimeSurface(straightLineSurface || comparisonSurface),
setIsochroneFetchStatus(false),
// Attempt to keep the UI in sync if changes have been made
setDisplayedProfileRequest(profileRequest)
]
} catch (e) {
console.error(e)
throw e
}
}
// exported for testing
export function responseToSurface (response: any): any {
if (response[0] && response[0].title) {
// this is a list of errors from the backend
return {
errors: response,
warnings: []
}
}
return parseTimesData(response)
}
/**
* Create a straight-line-distance travel time surface. This is a hidden feature
* to allow a particular client to demonstrate that straight-line distance _from
* the origin_ is absurd when used to compute transit access. Yes, people
* actually do this.
*/
function createStraightLineDistanceTravelTimeSurface (surface: any, origin: LonLat, speedKmh: number) {
const array = new Uint8ClampedArray(surface.depth)
return {
...surface,
errors: [],
warnings: [{
title: `Comparison project is using straight line distance with speed ${speedKmh} km/h`,
messages: []
}],
get (x, y) {
const ll = lonlat.fromPixel({
x: x + surface.west,
y: y + surface.north
}, surface.zoom)
const distMeters = lonlat.toLeaflet(ll).distanceTo([origin.lat, origin.lon])
const timeMinutes = (distMeters / 1000 / speedKmh * 60) | 0
for (let i = 0; i < surface.depth; i++) {
array[i] = timeMinutes
}
return array
}
}
}
| refactor(analysis): Dont download GeoTIFFs on manual fetch
| lib/actions/analysis/index.js | refactor(analysis): Dont download GeoTIFFs on manual fetch | <ide><path>ib/actions/analysis/index.js
<ide> return dispatch(fetchMultiple({
<ide> type: FETCH_TRAVEL_TIME_SURFACE,
<ide> fetches,
<del> next: asGeoTIFF
<add> next: asGeoTIFF === true
<ide> ? handleGeoTIFF(
<ide> `${get(project, 'name', '')}-${profileRequest.variantIndex}`,
<ide> `${get(comparisonProject, 'name', '')}-${profileRequest.variantIndex}` |
|
Java | lgpl-2.1 | e0c031b62420d86c9a3657eab440326852660ec2 | 0 | lafita/biojava,heuermh/biojava,lafita/biojava,pwrose/biojava,sbliven/biojava-sbliven,emckee2006/biojava,pwrose/biojava,sbliven/biojava-sbliven,heuermh/biojava,heuermh/biojava,lafita/biojava,emckee2006/biojava,biojava/biojava,biojava/biojava,sbliven/biojava-sbliven,emckee2006/biojava,pwrose/biojava,biojava/biojava | /*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* Created on 08.05.2004
*
*/
package org.biojava.nbio.structure;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.vecmath.Matrix3d;
import javax.vecmath.Matrix4d;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;
import org.biojava.nbio.structure.geometry.CalcPoint;
import org.biojava.nbio.structure.geometry.Matrices;
import org.biojava.nbio.structure.geometry.SuperPositionSVD;
import org.biojava.nbio.structure.jama.Matrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility operations on Atoms, AminoAcids, Matrices, Point3d, etc.
* <p>
* Currently the coordinates of an Atom are stored as an array of size 3
* (double[3]). It would be more powerful to use Point3d from javax.vecmath.
* Overloaded methods for Point3d operations exist in the {@link CalcPoint}
* Class.
*
* @author Andreas Prlic
* @author Aleix Lafita
* @since 1.4
* @version %I% %G%
*/
public class Calc {
private final static Logger logger = LoggerFactory.getLogger(Calc.class);
/**
* calculate distance between two atoms.
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return a double
*/
public static final double getDistance(Atom a, Atom b) {
double x = a.getX() - b.getX();
double y = a.getY() - b.getY();
double z = a.getZ() - b.getZ();
double s = x * x + y * y + z * z;
return Math.sqrt(s);
}
/**
* Will calculate the square of distances between two atoms. This will be
* faster as it will not perform the final square root to get the actual
* distance. Use this if doing large numbers of distance comparisons - it is
* marginally faster than getDistance().
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return a double
*/
public static double getDistanceFast(Atom a, Atom b) {
double x = a.getX() - b.getX();
double y = a.getY() - b.getY();
double z = a.getZ() - b.getZ();
return x * x + y * y + z * z;
}
public static final Atom invert(Atom a) {
double[] coords = new double[] { 0.0, 0.0, 0.0 };
Atom zero = new AtomImpl();
zero.setCoords(coords);
return subtract(zero, a);
}
/**
* add two atoms ( a + b).
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return an Atom object
*/
public static final Atom add(Atom a, Atom b) {
Atom c = new AtomImpl();
c.setX(a.getX() + b.getX());
c.setY(a.getY() + b.getY());
c.setZ(a.getZ() + b.getZ());
return c;
}
/**
* subtract two atoms ( a - b).
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return n new Atom object representing the difference
*/
public static final Atom subtract(Atom a, Atom b) {
Atom c = new AtomImpl();
c.setX(a.getX() - b.getX());
c.setY(a.getY() - b.getY());
c.setZ(a.getZ() - b.getZ());
return c;
}
/**
* Vector product (cross product).
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return an Atom object
*/
public static final Atom vectorProduct(Atom a, Atom b) {
Atom c = new AtomImpl();
c.setX(a.getY() * b.getZ() - a.getZ() * b.getY());
c.setY(a.getZ() * b.getX() - a.getX() * b.getZ());
c.setZ(a.getX() * b.getY() - a.getY() * b.getX());
return c;
}
/**
* Scalar product (dot product).
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return a double
*/
public static final double scalarProduct(Atom a, Atom b) {
return a.getX() * b.getX() + a.getY() * b.getY() + a.getZ() * b.getZ();
}
/**
* Gets the length of the vector (2-norm)
*
* @param a
* an Atom object
* @return Square root of the sum of the squared elements
*/
public static final double amount(Atom a) {
return Math.sqrt(scalarProduct(a, a));
}
/**
* Gets the angle between two vectors
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return Angle between a and b in degrees, in range [0,180]. If either
* vector has length 0 then angle is not defined and NaN is returned
*/
public static final double angle(Atom a, Atom b) {
Vector3d va = new Vector3d(a.getCoordsAsPoint3d());
Vector3d vb = new Vector3d(b.getCoordsAsPoint3d());
return Math.toDegrees(va.angle(vb));
}
/**
* Returns the unit vector of vector a .
*
* @param a
* an Atom object
* @return an Atom object
*/
public static final Atom unitVector(Atom a) {
double amount = amount(a);
double[] coords = new double[3];
coords[0] = a.getX() / amount;
coords[1] = a.getY() / amount;
coords[2] = a.getZ() / amount;
a.setCoords(coords);
return a;
}
/**
* Calculate the torsion angle, i.e. the angle between the normal vectors of
* the two plains a-b-c and b-c-d. See
* http://en.wikipedia.org/wiki/Dihedral_angle
*
* @param a
* an Atom object
* @param b
* an Atom object
* @param c
* an Atom object
* @param d
* an Atom object
* @return the torsion angle in degrees, in range +-[0,180]. If either first
* 3 or last 3 atoms are colinear then torsion angle is not defined
* and NaN is returned
*/
public static final double torsionAngle(Atom a, Atom b, Atom c, Atom d) {
Atom ab = subtract(a, b);
Atom cb = subtract(c, b);
Atom bc = subtract(b, c);
Atom dc = subtract(d, c);
Atom abc = vectorProduct(ab, cb);
Atom bcd = vectorProduct(bc, dc);
double angl = angle(abc, bcd);
/* calc the sign: */
Atom vecprod = vectorProduct(abc, bcd);
double val = scalarProduct(cb, vecprod);
if (val < 0.0)
angl = -angl;
return angl;
}
/**
* Calculate the phi angle.
*
* @param a
* an AminoAcid object
* @param b
* an AminoAcid object
* @return a double
* @throws StructureException
* if aminoacids not connected or if any of the 4 needed atoms
* missing
*/
public static final double getPhi(AminoAcid a, AminoAcid b)
throws StructureException {
if (!isConnected(a, b)) {
throw new StructureException(
"can not calc Phi - AminoAcids are not connected!");
}
Atom a_C = a.getC();
Atom b_N = b.getN();
Atom b_CA = b.getCA();
Atom b_C = b.getC();
// C and N were checked in isConnected already
if (b_CA == null)
throw new StructureException(
"Can not calculate Phi, CA atom is missing");
return torsionAngle(a_C, b_N, b_CA, b_C);
}
/**
* Calculate the psi angle.
*
* @param a
* an AminoAcid object
* @param b
* an AminoAcid object
* @return a double
* @throws StructureException
* if aminoacids not connected or if any of the 4 needed atoms
* missing
*/
public static final double getPsi(AminoAcid a, AminoAcid b)
throws StructureException {
if (!isConnected(a, b)) {
throw new StructureException(
"can not calc Psi - AminoAcids are not connected!");
}
Atom a_N = a.getN();
Atom a_CA = a.getCA();
Atom a_C = a.getC();
Atom b_N = b.getN();
// C and N were checked in isConnected already
if (a_CA == null)
throw new StructureException(
"Can not calculate Psi, CA atom is missing");
return torsionAngle(a_N, a_CA, a_C, b_N);
}
/**
* Test if two amino acids are connected, i.e. if the distance from C to N <
* 2.5 Angstrom.
*
* If one of the AminoAcids has an atom missing, returns false.
*
* @param a
* an AminoAcid object
* @param b
* an AminoAcid object
* @return true if ...
*/
public static final boolean isConnected(AminoAcid a, AminoAcid b) {
Atom C = null;
Atom N = null;
C = a.getC();
N = b.getN();
if (C == null || N == null)
return false;
// one could also check if the CA atoms are < 4 A...
double distance = getDistance(C, N);
return distance < 2.5;
}
/**
* Rotate a single Atom aroud a rotation matrix. The rotation Matrix must be
* a pre-multiplication 3x3 Matrix.
*
* If the matrix is indexed m[row][col], then the matrix will be
* pre-multiplied (y=atom*M)
*
* @param atom
* atom to be rotated
* @param m
* a rotation matrix represented as a double[3][3] array
*/
public static final void rotate(Atom atom, double[][] m) {
double x = atom.getX();
double y = atom.getY();
double z = atom.getZ();
double nx = m[0][0] * x + m[0][1] * y + m[0][2] * z;
double ny = m[1][0] * x + m[1][1] * y + m[1][2] * z;
double nz = m[2][0] * x + m[2][1] * y + m[2][2] * z;
atom.setX(nx);
atom.setY(ny);
atom.setZ(nz);
}
/**
* Rotate a structure. The rotation Matrix must be a pre-multiplication
* Matrix.
*
* @param structure
* a Structure object
* @param rotationmatrix
* an array (3x3) of double representing the rotation matrix.
* @throws StructureException
* ...
*/
public static final void rotate(Structure structure,
double[][] rotationmatrix) throws StructureException {
if (rotationmatrix.length != 3) {
throw new StructureException("matrix does not have size 3x3 !");
}
AtomIterator iter = new AtomIterator(structure);
while (iter.hasNext()) {
Atom atom = iter.next();
Calc.rotate(atom, rotationmatrix);
}
}
/**
* Rotate a Group. The rotation Matrix must be a pre-multiplication Matrix.
*
* @param group
* a group object
* @param rotationmatrix
* an array (3x3) of double representing the rotation matrix.
* @throws StructureException
* ...
*/
public static final void rotate(Group group, double[][] rotationmatrix)
throws StructureException {
if (rotationmatrix.length != 3) {
throw new StructureException("matrix does not have size 3x3 !");
}
AtomIterator iter = new AtomIterator(group);
while (iter.hasNext()) {
Atom atom = null;
atom = iter.next();
rotate(atom, rotationmatrix);
}
}
/**
* Rotate an Atom around a Matrix object. The rotation Matrix must be a
* pre-multiplication Matrix.
*
* @param atom
* atom to be rotated
* @param m
* rotation matrix to be applied to the atom
*/
public static final void rotate(Atom atom, Matrix m) {
double x = atom.getX();
double y = atom.getY();
double z = atom.getZ();
double[][] ad = new double[][] { { x, y, z } };
Matrix am = new Matrix(ad);
Matrix na = am.times(m);
atom.setX(na.get(0, 0));
atom.setY(na.get(0, 1));
atom.setZ(na.get(0, 2));
}
/**
* Rotate a group object. The rotation Matrix must be a pre-multiplication
* Matrix.
*
* @param group
* a group to be rotated
* @param m
* a Matrix object representing the rotation matrix
*/
public static final void rotate(Group group, Matrix m) {
AtomIterator iter = new AtomIterator(group);
while (iter.hasNext()) {
Atom atom = iter.next();
rotate(atom, m);
}
}
/**
* Rotate a structure object. The rotation Matrix must be a
* pre-multiplication Matrix.
*
* @param structure
* the structure to be rotated
* @param m
* rotation matrix to be applied
*/
public static final void rotate(Structure structure, Matrix m) {
AtomIterator iter = new AtomIterator(structure);
while (iter.hasNext()) {
Atom atom = iter.next();
rotate(atom, m);
}
}
/**
* Transform an array of atoms at once. The transformation Matrix must be a
* post-multiplication Matrix.
*
* @param ca
* array of Atoms to shift
* @param t
* transformation Matrix4d
*/
public static void transform(Atom[] ca, Matrix4d t) {
for (Atom atom : ca)
Calc.transform(atom, t);
}
/**
* Transforms an atom object, given a Matrix4d (i.e. the vecmath library
* double-precision 4x4 rotation+translation matrix). The transformation
* Matrix must be a post-multiplication Matrix.
*
* @param atom
* @param m
*/
public static final void transform(Atom atom, Matrix4d m) {
Point3d p = new Point3d(atom.getX(), atom.getY(), atom.getZ());
m.transform(p);
atom.setX(p.x);
atom.setY(p.y);
atom.setZ(p.z);
}
/**
* Transforms a group object, given a Matrix4d (i.e. the vecmath library
* double-precision 4x4 rotation+translation matrix). The transformation
* Matrix must be a post-multiplication Matrix.
*
* @param group
* @param m
*/
public static final void transform(Group group, Matrix4d m) {
for (Atom atom : group.getAtoms()) {
transform(atom, m);
}
for (Group altG : group.getAltLocs()) {
transform(altG, m);
}
}
/**
* Transforms a structure object, given a Matrix4d (i.e. the vecmath library
* double-precision 4x4 rotation+translation matrix). The transformation
* Matrix must be a post-multiplication Matrix.
*
* @param structure
* @param m
*/
public static final void transform(Structure structure, Matrix4d m) {
for (int n=0; n<structure.nrModels();n++) {
for (Chain c : structure.getChains(n)) {
transform(c, m);
}
}
}
/**
* Transforms a chain object, given a Matrix4d (i.e. the vecmath library
* double-precision 4x4 rotation+translation matrix). The transformation
* Matrix must be a post-multiplication Matrix.
*
* @param chain
* @param m
*/
public static final void transform(Chain chain, Matrix4d m) {
for (Group g : chain.getAtomGroups()) {
transform(g, m);
}
}
/**
* Translates an atom object, given a Vector3d (i.e. the vecmath library
* double-precision 3-d vector)
*
* @param atom
* @param v
*/
public static final void translate(Atom atom, Vector3d v) {
atom.setX(atom.getX() + v.x);
atom.setY(atom.getY() + v.y);
atom.setZ(atom.getZ() + v.z);
}
/**
* Translates a group object, given a Vector3d (i.e. the vecmath library
* double-precision 3-d vector)
*
* @param group
* @param v
*/
public static final void translate(Group group, Vector3d v) {
for (Atom atom : group.getAtoms()) {
translate(atom, v);
}
for (Group altG : group.getAltLocs()) {
translate(altG, v);
}
}
/**
* Translates a chain object, given a Vector3d (i.e. the vecmath library
* double-precision 3-d vector)
*
* @param chain
* @param v
*/
public static final void translate(Chain chain, Vector3d v) {
for (Group g : chain.getAtomGroups()) {
translate(g, v);
}
}
/**
* Translates a Structure object, given a Vector3d (i.e. the vecmath library
* double-precision 3-d vector)
*
* @param structure
* @param v
*/
public static final void translate(Structure structure, Vector3d v) {
for (int n=0; n<structure.nrModels();n++) {
for (Chain c : structure.getChains(n)) {
translate(c, v);
}
}
}
/**
* calculate structure + Matrix coodinates ...
*
* @param s
* the structure to operate on
* @param matrix
* a Matrix object
*/
public static final void plus(Structure s, Matrix matrix) {
AtomIterator iter = new AtomIterator(s);
Atom oldAtom = null;
Atom rotOldAtom = null;
while (iter.hasNext()) {
Atom atom = null;
atom = iter.next();
try {
if (oldAtom != null) {
logger.debug("before {}", getDistance(oldAtom, atom));
}
} catch (Exception e) {
logger.error("Exception: ", e);
}
oldAtom = (Atom) atom.clone();
double x = atom.getX();
double y = atom.getY();
double z = atom.getZ();
double[][] ad = new double[][] { { x, y, z } };
Matrix am = new Matrix(ad);
Matrix na = am.plus(matrix);
double[] coords = new double[3];
coords[0] = na.get(0, 0);
coords[1] = na.get(0, 1);
coords[2] = na.get(0, 2);
atom.setCoords(coords);
try {
if (rotOldAtom != null) {
logger.debug("after {}", getDistance(rotOldAtom, atom));
}
} catch (Exception e) {
logger.error("Exception: ", e);
}
rotOldAtom = (Atom) atom.clone();
}
}
/**
* shift a structure with a vector.
*
* @param structure
* a Structure object
* @param a
* an Atom object representing a shift vector
*/
public static final void shift(Structure structure, Atom a) {
AtomIterator iter = new AtomIterator(structure);
while (iter.hasNext()) {
Atom atom = null;
atom = iter.next();
Atom natom = add(atom, a);
double x = natom.getX();
double y = natom.getY();
double z = natom.getZ();
atom.setX(x);
atom.setY(y);
atom.setZ(z);
}
}
/**
* Shift a vector.
*
* @param a
* vector a
* @param b
* vector b
*/
public static final void shift(Atom a, Atom b) {
Atom natom = add(a, b);
double x = natom.getX();
double y = natom.getY();
double z = natom.getZ();
a.setX(x);
a.setY(y);
a.setZ(z);
}
/**
* Shift a Group with a vector.
*
* @param group
* a group object
* @param a
* an Atom object representing a shift vector
*/
public static final void shift(Group group, Atom a) {
AtomIterator iter = new AtomIterator(group);
while (iter.hasNext()) {
Atom atom = null;
atom = iter.next();
Atom natom = add(atom, a);
double x = natom.getX();
double y = natom.getY();
double z = natom.getZ();
atom.setX(x);
atom.setY(y);
atom.setZ(z);
}
}
/**
* Returns the centroid of the set of atoms.
*
* @param atomSet
* a set of Atoms
* @return an Atom representing the Centroid of the set of atoms
*/
public static final Atom getCentroid(Atom[] atomSet) {
// if we don't catch this case, the centroid returned is (NaN,NaN,NaN), which can cause lots of problems down the line
if (atomSet.length==0)
throw new IllegalArgumentException("Atom array has length 0, can't calculate centroid!");
// if we don't catch this case, the centroid returned is (NaN,NaN,NaN), which can cause lots of problems down the line
if (atomSet.length==0)
throw new IllegalArgumentException("Atom array has length 0, can't calculate centroid!");
double[] coords = new double[3];
coords[0] = 0;
coords[1] = 0;
coords[2] = 0;
for (Atom a : atomSet) {
coords[0] += a.getX();
coords[1] += a.getY();
coords[2] += a.getZ();
}
int n = atomSet.length;
coords[0] = coords[0] / n;
coords[1] = coords[1] / n;
coords[2] = coords[2] / n;
Atom vec = new AtomImpl();
vec.setCoords(coords);
return vec;
}
/**
* Returns the center of mass of the set of atoms. Atomic masses of the
* Atoms are used.
*
* @param atomSet
* a set of Atoms
* @return an Atom representing the center of mass
*/
public static Atom centerOfMass(Atom[] points) {
Atom center = new AtomImpl();
float totalMass = 0.0f;
for (Atom a : points) {
float mass = a.getElement().getAtomicMass();
totalMass += mass;
center = scaleAdd(mass, a, center);
}
center = scaleEquals(center, 1.0f / totalMass);
return center;
}
/**
* Multiply elements of a by s (in place)
*
* @param a
* @param s
* @return the modified a
*/
public static Atom scaleEquals(Atom a, double s) {
double x = a.getX();
double y = a.getY();
double z = a.getZ();
x *= s;
y *= s;
z *= s;
// Atom b = new AtomImpl();
a.setX(x);
a.setY(y);
a.setZ(z);
return a;
}
/**
* Multiply elements of a by s
*
* @param a
* @param s
* @return A new Atom with s*a
*/
public static Atom scale(Atom a, double s) {
double x = a.getX();
double y = a.getY();
double z = a.getZ();
Atom b = new AtomImpl();
b.setX(x * s);
b.setY(y * s);
b.setZ(z * s);
return b;
}
/**
* Perform linear transformation s*X+B, and store the result in b
*
* @param s
* Amount to scale x
* @param x
* Input coordinate
* @param b
* Vector to translate (will be modified)
* @return b, after modification
*/
public static Atom scaleAdd(double s, Atom x, Atom b) {
double xc = s * x.getX() + b.getX();
double yc = s * x.getY() + b.getY();
double zc = s * x.getZ() + b.getZ();
// Atom a = new AtomImpl();
b.setX(xc);
b.setY(yc);
b.setZ(zc);
return b;
}
/**
* Returns the Vector that needs to be applied to shift a set of atoms to
* the Centroid.
*
* @param atomSet
* array of Atoms
* @return the vector needed to shift the set of atoms to its geometric
* center
*/
public static final Atom getCenterVector(Atom[] atomSet) {
Atom centroid = getCentroid(atomSet);
return getCenterVector(atomSet, centroid);
}
/**
* Returns the Vector that needs to be applied to shift a set of atoms to
* the Centroid, if the centroid is already known
*
* @param atomSet
* array of Atoms
* @return the vector needed to shift the set of atoms to its geometric
* center
*/
public static final Atom getCenterVector(Atom[] atomSet, Atom centroid) {
double[] coords = new double[3];
coords[0] = 0 - centroid.getX();
coords[1] = 0 - centroid.getY();
coords[2] = 0 - centroid.getZ();
Atom shiftVec = new AtomImpl();
shiftVec.setCoords(coords);
return shiftVec;
}
/**
* Center the atoms at the Centroid.
*
* @param atomSet
* a set of Atoms
* @return an Atom representing the Centroid of the set of atoms
* @throws StructureException
* */
public static final Atom[] centerAtoms(Atom[] atomSet)
throws StructureException {
Atom centroid = getCentroid(atomSet);
return centerAtoms(atomSet, centroid);
}
/**
* Center the atoms at the Centroid, if the centroid is already know.
*
* @param atomSet
* a set of Atoms
* @return an Atom representing the Centroid of the set of atoms
* @throws StructureException
* */
public static final Atom[] centerAtoms(Atom[] atomSet, Atom centroid)
throws StructureException {
Atom shiftVector = getCenterVector(atomSet, centroid);
Atom[] newAtoms = new AtomImpl[atomSet.length];
for (int i = 0; i < atomSet.length; i++) {
Atom a = atomSet[i];
Atom n = add(a, shiftVector);
newAtoms[i] = n;
}
return newAtoms;
}
/**
* creates a virtual C-beta atom. this might be needed when working with GLY
*
* thanks to Peter Lackner for a python template of this method.
*
* @param amino
* the amino acid for which a "virtual" CB atom should be
* calculated
* @return a "virtual" CB atom
* @throws StructureException
*/
public static final Atom createVirtualCBAtom(AminoAcid amino)
throws StructureException {
AminoAcid ala = StandardAminoAcid.getAminoAcid("ALA");
Atom aN = ala.getN();
Atom aCA = ala.getCA();
Atom aC = ala.getC();
Atom aCB = ala.getCB();
Atom[] arr1 = new Atom[3];
arr1[0] = aN;
arr1[1] = aCA;
arr1[2] = aC;
Atom[] arr2 = new Atom[3];
arr2[0] = amino.getN();
arr2[1] = amino.getCA();
arr2[2] = amino.getC();
// ok now we got the two arrays, do a Superposition:
SuperPositionSVD svd = new SuperPositionSVD(false);
Matrix4d transform = svd.superpose(Calc.atomsToPoints(arr1), Calc.atomsToPoints(arr2));
Matrix rotMatrix = Matrices.getRotationJAMA(transform);
Atom tranMatrix = getTranslationVector(transform);
Calc.rotate(aCB, rotMatrix);
Atom virtualCB = Calc.add(aCB, tranMatrix);
virtualCB.setName("CB");
return virtualCB;
}
/**
* Gets euler angles for a matrix given in ZYZ convention. (as e.g. used by
* Jmol)
*
* @param m
* the rotation matrix
* @return the euler values for a rotation around Z, Y, Z in degrees...
*/
public static final double[] getZYZEuler(Matrix m) {
double m22 = m.get(2, 2);
double rY = Math.toDegrees(Math.acos(m22));
double rZ1, rZ2;
if (m22 > .999d || m22 < -.999d) {
rZ1 = Math.toDegrees(Math.atan2(m.get(1, 0), m.get(1, 1)));
rZ2 = 0;
} else {
rZ1 = Math.toDegrees(Math.atan2(m.get(2, 1), -m.get(2, 0)));
rZ2 = Math.toDegrees(Math.atan2(m.get(1, 2), m.get(0, 2)));
}
return new double[] { rZ1, rY, rZ2 };
}
/**
* Convert a rotation Matrix to Euler angles. This conversion uses
* conventions as described on page:
* http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm
* Coordinate System: right hand Positive angle: right hand Order of euler
* angles: heading first, then attitude, then bank
*
* @param m
* the rotation matrix
* @return a array of three doubles containing the three euler angles in
* radians
*/
public static final double[] getXYZEuler(Matrix m) {
double heading, attitude, bank;
// Assuming the angles are in radians.
if (m.get(1, 0) > 0.998) { // singularity at north pole
heading = Math.atan2(m.get(0, 2), m.get(2, 2));
attitude = Math.PI / 2;
bank = 0;
} else if (m.get(1, 0) < -0.998) { // singularity at south pole
heading = Math.atan2(m.get(0, 2), m.get(2, 2));
attitude = -Math.PI / 2;
bank = 0;
} else {
heading = Math.atan2(-m.get(2, 0), m.get(0, 0));
bank = Math.atan2(-m.get(1, 2), m.get(1, 1));
attitude = Math.asin(m.get(1, 0));
}
return new double[] { heading, attitude, bank };
}
/**
* This conversion uses NASA standard aeroplane conventions as described on
* page:
* http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm
* Coordinate System: right hand Positive angle: right hand Order of euler
* angles: heading first, then attitude, then bank. matrix row column
* ordering: [m00 m01 m02] [m10 m11 m12] [m20 m21 m22]
*
* @param heading
* in radians
* @param attitude
* in radians
* @param bank
* in radians
* @return the rotation matrix
*/
public static final Matrix matrixFromEuler(double heading, double attitude,
double bank) {
// Assuming the angles are in radians.
double ch = Math.cos(heading);
double sh = Math.sin(heading);
double ca = Math.cos(attitude);
double sa = Math.sin(attitude);
double cb = Math.cos(bank);
double sb = Math.sin(bank);
Matrix m = new Matrix(3, 3);
m.set(0, 0, ch * ca);
m.set(0, 1, sh * sb - ch * sa * cb);
m.set(0, 2, ch * sa * sb + sh * cb);
m.set(1, 0, sa);
m.set(1, 1, ca * cb);
m.set(1, 2, -ca * sb);
m.set(2, 0, -sh * ca);
m.set(2, 1, sh * sa * cb + ch * sb);
m.set(2, 2, -sh * sa * sb + ch * cb);
return m;
}
/**
* Calculates the angle from centerPt to targetPt in degrees. The return
* should range from [0,360), rotating CLOCKWISE, 0 and 360 degrees
* represents NORTH, 90 degrees represents EAST, etc...
*
* Assumes all points are in the same coordinate space. If they are not, you
* will need to call SwingUtilities.convertPointToScreen or equivalent on
* all arguments before passing them to this function.
*
* @param centerPt
* Point we are rotating around.
* @param targetPt
* Point we want to calculate the angle to.
* @return angle in degrees. This is the angle from centerPt to targetPt.
*/
public static double calcRotationAngleInDegrees(Atom centerPt, Atom targetPt) {
// calculate the angle theta from the deltaY and deltaX values
// (atan2 returns radians values from [-PI,PI])
// 0 currently points EAST.
// NOTE: By preserving Y and X param order to atan2, we are expecting
// a CLOCKWISE angle direction.
double theta = Math.atan2(targetPt.getY() - centerPt.getY(),
targetPt.getX() - centerPt.getX());
// rotate the theta angle clockwise by 90 degrees
// (this makes 0 point NORTH)
// NOTE: adding to an angle rotates it clockwise.
// subtracting would rotate it counter-clockwise
theta += Math.PI / 2.0;
// convert from radians to degrees
// this will give you an angle from [0->270],[-180,0]
double angle = Math.toDegrees(theta);
// convert to positive range [0-360)
// since we want to prevent negative angles, adjust them now.
// we can assume that atan2 will not return a negative value
// greater than one partial rotation
if (angle < 0) {
angle += 360;
}
return angle;
}
public static void main(String[] args) {
Atom a = new AtomImpl();
a.setX(0);
a.setY(0);
a.setZ(0);
Atom b = new AtomImpl();
b.setX(1);
b.setY(1);
b.setZ(0);
logger.info("Angle between atoms: ", calcRotationAngleInDegrees(a, b));
}
public static void rotate(Atom[] ca, Matrix matrix) {
for (Atom atom : ca)
Calc.rotate(atom, matrix);
}
/**
* Shift an array of atoms at once.
*
* @param ca
* array of Atoms to shift
* @param b
* reference Atom vector
*/
public static void shift(Atom[] ca, Atom b) {
for (Atom atom : ca)
Calc.shift(atom, b);
}
/**
* Convert JAMA rotation and translation to a Vecmath transformation matrix.
* Because the JAMA matrix is a pre-multiplication matrix and the Vecmath
* matrix is a post-multiplication one, the rotation matrix is transposed to
* ensure that the transformation they produce is the same.
*
* @param rot
* 3x3 Rotation matrix
* @param trans
* 3x1 translation vector in Atom coordinates
* @return 4x4 transformation matrix
*/
public static Matrix4d getTransformation(Matrix rot, Atom trans) {
return new Matrix4d(new Matrix3d(rot.getColumnPackedCopy()),
new Vector3d(trans.getCoordsAsPoint3d()), 1.0);
}
/**
* Extract the translational vector as an Atom of a transformation matrix.
*
* @param transform
* Matrix4d
* @return Atom shift vector
*/
public static Atom getTranslationVector(Matrix4d transform) {
Atom transl = new AtomImpl();
double[] coords = { transform.m03, transform.m13, transform.m23 };
transl.setCoords(coords);
return transl;
}
/**
* Convert an array of atoms into an array of vecmath points
*
* @param atoms
* list of atoms
* @return list of Point3ds storing the x,y,z coordinates of each atom
*/
public static Point3d[] atomsToPoints(Atom[] atoms) {
Point3d[] points = new Point3d[atoms.length];
for (int i = 0; i < atoms.length; i++) {
points[i] = atoms[i].getCoordsAsPoint3d();
}
return points;
}
/**
* Convert an array of atoms into an array of vecmath points
*
* @param atoms
* list of atoms
* @return list of Point3ds storing the x,y,z coordinates of each atom
*/
public static List<Point3d> atomsToPoints(Collection<Atom> atoms) {
ArrayList<Point3d> points = new ArrayList<>(atoms.size());
for (Atom atom : atoms) {
points.add(atom.getCoordsAsPoint3d());
}
return points;
}
/**
* Calculate the RMSD of two Atom arrays, already superposed.
*
* @param x
* array of Atoms superposed to y
* @param y
* array of Atoms superposed to x
* @return RMSD
*/
public static double rmsd(Atom[] x, Atom[] y) {
return CalcPoint.rmsd(atomsToPoints(x), atomsToPoints(y));
}
/**
* Calculate the TM-Score for the superposition.
*
* <em>Normalizes by the <strong>maximum</strong>-length structure (that is, {@code max\{len1,len2\}}) rather than the minimum.</em>
*
* Atom sets must be superposed.
*
* <p>
* Citation:<br/>
* <i>Zhang Y and Skolnick J (2004). "Scoring function for automated
* assessment of protein structure template quality". Proteins 57: 702 -
* 710.</i>
*
* @param atomSet1
* atom array 1
* @param atomSet2
* atom array 2
* @param len1
* The full length of the protein supplying atomSet1
* @param len2
* The full length of the protein supplying atomSet2
* @return The TM-Score
* @throws StructureException
* @see {@link #getTMScore(Atom[], Atom[], int, int)}, which normalizes by
* the minimum length
*/
public static double getTMScoreAlternate(Atom[] atomSet1, Atom[] atomSet2,
int len1, int len2) throws StructureException {
if (atomSet1.length != atomSet2.length) {
throw new StructureException(
"The two atom sets are not of same length!");
}
if (atomSet1.length > len1) {
throw new StructureException(
"len1 must be greater or equal to the alignment length!");
}
if (atomSet2.length > len2) {
throw new StructureException(
"len2 must be greater or equal to the alignment length!");
}
int Lmax = Math.max(len1, len2);
int Laln = atomSet1.length;
double d0 = 1.24 * Math.cbrt(Lmax - 15.) - 1.8;
double d0sq = d0 * d0;
double sum = 0;
for (int i = 0; i < Laln; i++) {
double d = Calc.getDistance(atomSet1[i], atomSet2[i]);
sum += 1. / (1 + d * d / d0sq);
}
return sum / Lmax;
}
/**
* Calculate the TM-Score for the superposition.
*
* <em>Normalizes by the <strong>minimum</strong>-length structure (that is, {@code min\{len1,len2\}}).</em>
*
* Atom sets must be pre-rotated.
*
* <p>
* Citation:<br/>
* <i>Zhang Y and Skolnick J (2004). "Scoring function for automated
* assessment of protein structure template quality". Proteins 57: 702 -
* 710.</i>
*
* @param atomSet1
* atom array 1
* @param atomSet2
* atom array 2
* @param len1
* The full length of the protein supplying atomSet1
* @param len2
* The full length of the protein supplying atomSet2
* @return The TM-Score
* @throws StructureException
*/
public static double getTMScore(Atom[] atomSet1, Atom[] atomSet2, int len1,
int len2) throws StructureException {
if (atomSet1.length != atomSet2.length) {
throw new StructureException(
"The two atom sets are not of same length!");
}
if (atomSet1.length > len1) {
throw new StructureException(
"len1 must be greater or equal to the alignment length!");
}
if (atomSet2.length > len2) {
throw new StructureException(
"len2 must be greater or equal to the alignment length!");
}
int Lmin = Math.min(len1, len2);
int Laln = atomSet1.length;
double d0 = 1.24 * Math.cbrt(Lmin - 15.) - 1.8;
double d0sq = d0 * d0;
double sum = 0;
for (int i = 0; i < Laln; i++) {
double d = Calc.getDistance(atomSet1[i], atomSet2[i]);
sum += 1. / (1 + d * d / d0sq);
}
return sum / Lmin;
}
}
| biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java | /*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* Created on 08.05.2004
*
*/
package org.biojava.nbio.structure;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.vecmath.Matrix3d;
import javax.vecmath.Matrix4d;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;
import org.biojava.nbio.structure.geometry.CalcPoint;
import org.biojava.nbio.structure.geometry.Matrices;
import org.biojava.nbio.structure.geometry.SuperPositionSVD;
import org.biojava.nbio.structure.jama.Matrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility operations on Atoms, AminoAcids, Matrices, Point3d, etc.
* <p>
* Currently the coordinates of an Atom are stored as an array of size 3
* (double[3]). It would be more powerful to use Point3d from javax.vecmath.
* Overloaded methods for Point3d operations exist in the {@link CalcPoint}
* Class.
*
* @author Andreas Prlic
* @author Aleix Lafita
* @since 1.4
* @version %I% %G%
*/
public class Calc {
private final static Logger logger = LoggerFactory.getLogger(Calc.class);
/**
* calculate distance between two atoms.
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return a double
*/
public static final double getDistance(Atom a, Atom b) {
double x = a.getX() - b.getX();
double y = a.getY() - b.getY();
double z = a.getZ() - b.getZ();
double s = x * x + y * y + z * z;
return Math.sqrt(s);
}
/**
* Will calculate the square of distances between two atoms. This will be
* faster as it will not perform the final square root to get the actual
* distance. Use this if doing large numbers of distance comparisons - it is
* marginally faster than getDistance().
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return a double
*/
public static double getDistanceFast(Atom a, Atom b) {
double x = a.getX() - b.getX();
double y = a.getY() - b.getY();
double z = a.getZ() - b.getZ();
return x * x + y * y + z * z;
}
public static final Atom invert(Atom a) {
double[] coords = new double[] { 0.0, 0.0, 0.0 };
Atom zero = new AtomImpl();
zero.setCoords(coords);
return subtract(zero, a);
}
/**
* add two atoms ( a + b).
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return an Atom object
*/
public static final Atom add(Atom a, Atom b) {
Atom c = new AtomImpl();
c.setX(a.getX() + b.getX());
c.setY(a.getY() + b.getY());
c.setZ(a.getZ() + b.getZ());
return c;
}
/**
* subtract two atoms ( a - b).
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return n new Atom object representing the difference
*/
public static final Atom subtract(Atom a, Atom b) {
Atom c = new AtomImpl();
c.setX(a.getX() - b.getX());
c.setY(a.getY() - b.getY());
c.setZ(a.getZ() - b.getZ());
return c;
}
/**
* Vector product (cross product).
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return an Atom object
*/
public static final Atom vectorProduct(Atom a, Atom b) {
Atom c = new AtomImpl();
c.setX(a.getY() * b.getZ() - a.getZ() * b.getY());
c.setY(a.getZ() * b.getX() - a.getX() * b.getZ());
c.setZ(a.getX() * b.getY() - a.getY() * b.getX());
return c;
}
/**
* Scalar product (dot product).
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return a double
*/
public static final double scalarProduct(Atom a, Atom b) {
return a.getX() * b.getX() + a.getY() * b.getY() + a.getZ() * b.getZ();
}
/**
* Gets the length of the vector (2-norm)
*
* @param a
* an Atom object
* @return Square root of the sum of the squared elements
*/
public static final double amount(Atom a) {
return Math.sqrt(scalarProduct(a, a));
}
/**
* Gets the angle between two vectors
*
* @param a
* an Atom object
* @param b
* an Atom object
* @return Angle between a and b in degrees, in range [0,180]. If either
* vector has length 0 then angle is not defined and NaN is returned
*/
public static final double angle(Atom a, Atom b) {
Vector3d va = new Vector3d(a.getCoordsAsPoint3d());
Vector3d vb = new Vector3d(b.getCoordsAsPoint3d());
return Math.toDegrees(va.angle(vb));
}
/**
* Returns the unit vector of vector a .
*
* @param a
* an Atom object
* @return an Atom object
*/
public static final Atom unitVector(Atom a) {
double amount = amount(a);
double[] coords = new double[3];
coords[0] = a.getX() / amount;
coords[1] = a.getY() / amount;
coords[2] = a.getZ() / amount;
a.setCoords(coords);
return a;
}
/**
* Calculate the torsion angle, i.e. the angle between the normal vectors of
* the two plains a-b-c and b-c-d. See
* http://en.wikipedia.org/wiki/Dihedral_angle
*
* @param a
* an Atom object
* @param b
* an Atom object
* @param c
* an Atom object
* @param d
* an Atom object
* @return the torsion angle in degrees, in range +-[0,180]. If either first
* 3 or last 3 atoms are colinear then torsion angle is not defined
* and NaN is returned
*/
public static final double torsionAngle(Atom a, Atom b, Atom c, Atom d) {
Atom ab = subtract(a, b);
Atom cb = subtract(c, b);
Atom bc = subtract(b, c);
Atom dc = subtract(d, c);
Atom abc = vectorProduct(ab, cb);
Atom bcd = vectorProduct(bc, dc);
double angl = angle(abc, bcd);
/* calc the sign: */
Atom vecprod = vectorProduct(abc, bcd);
double val = scalarProduct(cb, vecprod);
if (val < 0.0)
angl = -angl;
return angl;
}
/**
* Calculate the phi angle.
*
* @param a
* an AminoAcid object
* @param b
* an AminoAcid object
* @return a double
* @throws StructureException
* if aminoacids not connected or if any of the 4 needed atoms
* missing
*/
public static final double getPhi(AminoAcid a, AminoAcid b)
throws StructureException {
if (!isConnected(a, b)) {
throw new StructureException(
"can not calc Phi - AminoAcids are not connected!");
}
Atom a_C = a.getC();
Atom b_N = b.getN();
Atom b_CA = b.getCA();
Atom b_C = b.getC();
// C and N were checked in isConnected already
if (b_CA == null)
throw new StructureException(
"Can not calculate Phi, CA atom is missing");
return torsionAngle(a_C, b_N, b_CA, b_C);
}
/**
* Calculate the psi angle.
*
* @param a
* an AminoAcid object
* @param b
* an AminoAcid object
* @return a double
* @throws StructureException
* if aminoacids not connected or if any of the 4 needed atoms
* missing
*/
public static final double getPsi(AminoAcid a, AminoAcid b)
throws StructureException {
if (!isConnected(a, b)) {
throw new StructureException(
"can not calc Psi - AminoAcids are not connected!");
}
Atom a_N = a.getN();
Atom a_CA = a.getCA();
Atom a_C = a.getC();
Atom b_N = b.getN();
// C and N were checked in isConnected already
if (a_CA == null)
throw new StructureException(
"Can not calculate Psi, CA atom is missing");
return torsionAngle(a_N, a_CA, a_C, b_N);
}
/**
* Test if two amino acids are connected, i.e. if the distance from C to N <
* 2.5 Angstrom.
*
* If one of the AminoAcids has an atom missing, returns false.
*
* @param a
* an AminoAcid object
* @param b
* an AminoAcid object
* @return true if ...
*/
public static final boolean isConnected(AminoAcid a, AminoAcid b) {
Atom C = null;
Atom N = null;
C = a.getC();
N = b.getN();
if (C == null || N == null)
return false;
// one could also check if the CA atoms are < 4 A...
double distance = getDistance(C, N);
return distance < 2.5;
}
/**
* Rotate a single Atom aroud a rotation matrix. The rotation Matrix must be
* a pre-multiplication 3x3 Matrix.
*
* If the matrix is indexed m[row][col], then the matrix will be
* pre-multiplied (y=atom*M)
*
* @param atom
* atom to be rotated
* @param m
* a rotation matrix represented as a double[3][3] array
*/
public static final void rotate(Atom atom, double[][] m) {
double x = atom.getX();
double y = atom.getY();
double z = atom.getZ();
double nx = m[0][0] * x + m[0][1] * y + m[0][2] * z;
double ny = m[1][0] * x + m[1][1] * y + m[1][2] * z;
double nz = m[2][0] * x + m[2][1] * y + m[2][2] * z;
atom.setX(nx);
atom.setY(ny);
atom.setZ(nz);
}
/**
* Rotate a structure. The rotation Matrix must be a pre-multiplication
* Matrix.
*
* @param structure
* a Structure object
* @param rotationmatrix
* an array (3x3) of double representing the rotation matrix.
* @throws StructureException
* ...
*/
public static final void rotate(Structure structure,
double[][] rotationmatrix) throws StructureException {
if (rotationmatrix.length != 3) {
throw new StructureException("matrix does not have size 3x3 !");
}
AtomIterator iter = new AtomIterator(structure);
while (iter.hasNext()) {
Atom atom = iter.next();
Calc.rotate(atom, rotationmatrix);
}
}
/**
* Rotate a Group. The rotation Matrix must be a pre-multiplication Matrix.
*
* @param group
* a group object
* @param rotationmatrix
* an array (3x3) of double representing the rotation matrix.
* @throws StructureException
* ...
*/
public static final void rotate(Group group, double[][] rotationmatrix)
throws StructureException {
if (rotationmatrix.length != 3) {
throw new StructureException("matrix does not have size 3x3 !");
}
AtomIterator iter = new AtomIterator(group);
while (iter.hasNext()) {
Atom atom = null;
atom = iter.next();
rotate(atom, rotationmatrix);
}
}
/**
* Rotate an Atom around a Matrix object. The rotation Matrix must be a
* pre-multiplication Matrix.
*
* @param atom
* atom to be rotated
* @param m
* rotation matrix to be applied to the atom
*/
public static final void rotate(Atom atom, Matrix m) {
double x = atom.getX();
double y = atom.getY();
double z = atom.getZ();
double[][] ad = new double[][] { { x, y, z } };
Matrix am = new Matrix(ad);
Matrix na = am.times(m);
atom.setX(na.get(0, 0));
atom.setY(na.get(0, 1));
atom.setZ(na.get(0, 2));
}
/**
* Rotate a group object. The rotation Matrix must be a pre-multiplication
* Matrix.
*
* @param group
* a group to be rotated
* @param m
* a Matrix object representing the rotation matrix
*/
public static final void rotate(Group group, Matrix m) {
AtomIterator iter = new AtomIterator(group);
while (iter.hasNext()) {
Atom atom = iter.next();
rotate(atom, m);
}
}
/**
* Rotate a structure object. The rotation Matrix must be a
* pre-multiplication Matrix.
*
* @param structure
* the structure to be rotated
* @param m
* rotation matrix to be applied
*/
public static final void rotate(Structure structure, Matrix m) {
AtomIterator iter = new AtomIterator(structure);
while (iter.hasNext()) {
Atom atom = iter.next();
rotate(atom, m);
}
}
/**
* Transform an array of atoms at once. The transformation Matrix must be a
* post-multiplication Matrix.
*
* @param ca
* array of Atoms to shift
* @param t
* transformation Matrix4d
*/
public static void transform(Atom[] ca, Matrix4d t) {
for (Atom atom : ca)
Calc.transform(atom, t);
}
/**
* Transforms an atom object, given a Matrix4d (i.e. the vecmath library
* double-precision 4x4 rotation+translation matrix). The transformation
* Matrix must be a post-multiplication Matrix.
*
* @param atom
* @param m
*/
public static final void transform(Atom atom, Matrix4d m) {
Point3d p = new Point3d(atom.getX(), atom.getY(), atom.getZ());
m.transform(p);
atom.setX(p.x);
atom.setY(p.y);
atom.setZ(p.z);
}
/**
* Transforms a group object, given a Matrix4d (i.e. the vecmath library
* double-precision 4x4 rotation+translation matrix). The transformation
* Matrix must be a post-multiplication Matrix.
*
* @param group
* @param m
*/
public static final void transform(Group group, Matrix4d m) {
for (Atom atom : group.getAtoms()) {
transform(atom, m);
}
for (Group altG : group.getAltLocs()) {
for (Atom atom : altG.getAtoms()) {
transform(atom, m);
}
}
}
/**
* Transforms a structure object, given a Matrix4d (i.e. the vecmath library
* double-precision 4x4 rotation+translation matrix). The transformation
* Matrix must be a post-multiplication Matrix.
*
* @param structure
* @param m
*/
public static final void transform(Structure structure, Matrix4d m) {
for (int n=0; n<structure.nrModels();n++) {
for (Chain c : structure.getChains(n)) {
transform(c, m);
}
}
}
/**
* Transforms a chain object, given a Matrix4d (i.e. the vecmath library
* double-precision 4x4 rotation+translation matrix). The transformation
* Matrix must be a post-multiplication Matrix.
*
* @param chain
* @param m
*/
public static final void transform(Chain chain, Matrix4d m) {
for (Group g : chain.getAtomGroups()) {
transform(g, m);
}
}
/**
* Translates an atom object, given a Vector3d (i.e. the vecmath library
* double-precision 3-d vector)
*
* @param atom
* @param v
*/
public static final void translate(Atom atom, Vector3d v) {
atom.setX(atom.getX() + v.x);
atom.setY(atom.getY() + v.y);
atom.setZ(atom.getZ() + v.z);
}
/**
* Translates a group object, given a Vector3d (i.e. the vecmath library
* double-precision 3-d vector)
*
* @param group
* @param v
*/
public static final void translate(Group group, Vector3d v) {
for (Atom atom : group.getAtoms()) {
translate(atom, v);
}
for (Group altG : group.getAltLocs()) {
for (Atom atom : altG.getAtoms()) {
translate(atom, v);
}
}
}
/**
* Translates a chain object, given a Vector3d (i.e. the vecmath library
* double-precision 3-d vector)
*
* @param chain
* @param v
*/
public static final void translate(Chain chain, Vector3d v) {
for (Group g : chain.getAtomGroups()) {
translate(g, v);
}
}
/**
* Translates a Structure object, given a Vector3d (i.e. the vecmath library
* double-precision 3-d vector)
*
* @param structure
* @param v
*/
public static final void translate(Structure structure, Vector3d v) {
for (int n=0; n<structure.nrModels();n++) {
for (Chain c : structure.getChains(n)) {
translate(c, v);
}
}
}
/**
* calculate structure + Matrix coodinates ...
*
* @param s
* the structure to operate on
* @param matrix
* a Matrix object
*/
public static final void plus(Structure s, Matrix matrix) {
AtomIterator iter = new AtomIterator(s);
Atom oldAtom = null;
Atom rotOldAtom = null;
while (iter.hasNext()) {
Atom atom = null;
atom = iter.next();
try {
if (oldAtom != null) {
logger.debug("before {}", getDistance(oldAtom, atom));
}
} catch (Exception e) {
logger.error("Exception: ", e);
}
oldAtom = (Atom) atom.clone();
double x = atom.getX();
double y = atom.getY();
double z = atom.getZ();
double[][] ad = new double[][] { { x, y, z } };
Matrix am = new Matrix(ad);
Matrix na = am.plus(matrix);
double[] coords = new double[3];
coords[0] = na.get(0, 0);
coords[1] = na.get(0, 1);
coords[2] = na.get(0, 2);
atom.setCoords(coords);
try {
if (rotOldAtom != null) {
logger.debug("after {}", getDistance(rotOldAtom, atom));
}
} catch (Exception e) {
logger.error("Exception: ", e);
}
rotOldAtom = (Atom) atom.clone();
}
}
/**
* shift a structure with a vector.
*
* @param structure
* a Structure object
* @param a
* an Atom object representing a shift vector
*/
public static final void shift(Structure structure, Atom a) {
AtomIterator iter = new AtomIterator(structure);
while (iter.hasNext()) {
Atom atom = null;
atom = iter.next();
Atom natom = add(atom, a);
double x = natom.getX();
double y = natom.getY();
double z = natom.getZ();
atom.setX(x);
atom.setY(y);
atom.setZ(z);
}
}
/**
* Shift a vector.
*
* @param a
* vector a
* @param b
* vector b
*/
public static final void shift(Atom a, Atom b) {
Atom natom = add(a, b);
double x = natom.getX();
double y = natom.getY();
double z = natom.getZ();
a.setX(x);
a.setY(y);
a.setZ(z);
}
/**
* Shift a Group with a vector.
*
* @param group
* a group object
* @param a
* an Atom object representing a shift vector
*/
public static final void shift(Group group, Atom a) {
AtomIterator iter = new AtomIterator(group);
while (iter.hasNext()) {
Atom atom = null;
atom = iter.next();
Atom natom = add(atom, a);
double x = natom.getX();
double y = natom.getY();
double z = natom.getZ();
atom.setX(x);
atom.setY(y);
atom.setZ(z);
}
}
/**
* Returns the centroid of the set of atoms.
*
* @param atomSet
* a set of Atoms
* @return an Atom representing the Centroid of the set of atoms
*/
public static final Atom getCentroid(Atom[] atomSet) {
// if we don't catch this case, the centroid returned is (NaN,NaN,NaN), which can cause lots of problems down the line
if (atomSet.length==0)
throw new IllegalArgumentException("Atom array has length 0, can't calculate centroid!");
// if we don't catch this case, the centroid returned is (NaN,NaN,NaN), which can cause lots of problems down the line
if (atomSet.length==0)
throw new IllegalArgumentException("Atom array has length 0, can't calculate centroid!");
double[] coords = new double[3];
coords[0] = 0;
coords[1] = 0;
coords[2] = 0;
for (Atom a : atomSet) {
coords[0] += a.getX();
coords[1] += a.getY();
coords[2] += a.getZ();
}
int n = atomSet.length;
coords[0] = coords[0] / n;
coords[1] = coords[1] / n;
coords[2] = coords[2] / n;
Atom vec = new AtomImpl();
vec.setCoords(coords);
return vec;
}
/**
* Returns the center of mass of the set of atoms. Atomic masses of the
* Atoms are used.
*
* @param atomSet
* a set of Atoms
* @return an Atom representing the center of mass
*/
public static Atom centerOfMass(Atom[] points) {
Atom center = new AtomImpl();
float totalMass = 0.0f;
for (Atom a : points) {
float mass = a.getElement().getAtomicMass();
totalMass += mass;
center = scaleAdd(mass, a, center);
}
center = scaleEquals(center, 1.0f / totalMass);
return center;
}
/**
* Multiply elements of a by s (in place)
*
* @param a
* @param s
* @return the modified a
*/
public static Atom scaleEquals(Atom a, double s) {
double x = a.getX();
double y = a.getY();
double z = a.getZ();
x *= s;
y *= s;
z *= s;
// Atom b = new AtomImpl();
a.setX(x);
a.setY(y);
a.setZ(z);
return a;
}
/**
* Multiply elements of a by s
*
* @param a
* @param s
* @return A new Atom with s*a
*/
public static Atom scale(Atom a, double s) {
double x = a.getX();
double y = a.getY();
double z = a.getZ();
Atom b = new AtomImpl();
b.setX(x * s);
b.setY(y * s);
b.setZ(z * s);
return b;
}
/**
* Perform linear transformation s*X+B, and store the result in b
*
* @param s
* Amount to scale x
* @param x
* Input coordinate
* @param b
* Vector to translate (will be modified)
* @return b, after modification
*/
public static Atom scaleAdd(double s, Atom x, Atom b) {
double xc = s * x.getX() + b.getX();
double yc = s * x.getY() + b.getY();
double zc = s * x.getZ() + b.getZ();
// Atom a = new AtomImpl();
b.setX(xc);
b.setY(yc);
b.setZ(zc);
return b;
}
/**
* Returns the Vector that needs to be applied to shift a set of atoms to
* the Centroid.
*
* @param atomSet
* array of Atoms
* @return the vector needed to shift the set of atoms to its geometric
* center
*/
public static final Atom getCenterVector(Atom[] atomSet) {
Atom centroid = getCentroid(atomSet);
return getCenterVector(atomSet, centroid);
}
/**
* Returns the Vector that needs to be applied to shift a set of atoms to
* the Centroid, if the centroid is already known
*
* @param atomSet
* array of Atoms
* @return the vector needed to shift the set of atoms to its geometric
* center
*/
public static final Atom getCenterVector(Atom[] atomSet, Atom centroid) {
double[] coords = new double[3];
coords[0] = 0 - centroid.getX();
coords[1] = 0 - centroid.getY();
coords[2] = 0 - centroid.getZ();
Atom shiftVec = new AtomImpl();
shiftVec.setCoords(coords);
return shiftVec;
}
/**
* Center the atoms at the Centroid.
*
* @param atomSet
* a set of Atoms
* @return an Atom representing the Centroid of the set of atoms
* @throws StructureException
* */
public static final Atom[] centerAtoms(Atom[] atomSet)
throws StructureException {
Atom centroid = getCentroid(atomSet);
return centerAtoms(atomSet, centroid);
}
/**
* Center the atoms at the Centroid, if the centroid is already know.
*
* @param atomSet
* a set of Atoms
* @return an Atom representing the Centroid of the set of atoms
* @throws StructureException
* */
public static final Atom[] centerAtoms(Atom[] atomSet, Atom centroid)
throws StructureException {
Atom shiftVector = getCenterVector(atomSet, centroid);
Atom[] newAtoms = new AtomImpl[atomSet.length];
for (int i = 0; i < atomSet.length; i++) {
Atom a = atomSet[i];
Atom n = add(a, shiftVector);
newAtoms[i] = n;
}
return newAtoms;
}
/**
* creates a virtual C-beta atom. this might be needed when working with GLY
*
* thanks to Peter Lackner for a python template of this method.
*
* @param amino
* the amino acid for which a "virtual" CB atom should be
* calculated
* @return a "virtual" CB atom
* @throws StructureException
*/
public static final Atom createVirtualCBAtom(AminoAcid amino)
throws StructureException {
AminoAcid ala = StandardAminoAcid.getAminoAcid("ALA");
Atom aN = ala.getN();
Atom aCA = ala.getCA();
Atom aC = ala.getC();
Atom aCB = ala.getCB();
Atom[] arr1 = new Atom[3];
arr1[0] = aN;
arr1[1] = aCA;
arr1[2] = aC;
Atom[] arr2 = new Atom[3];
arr2[0] = amino.getN();
arr2[1] = amino.getCA();
arr2[2] = amino.getC();
// ok now we got the two arrays, do a Superposition:
SuperPositionSVD svd = new SuperPositionSVD(false);
Matrix4d transform = svd.superpose(Calc.atomsToPoints(arr1), Calc.atomsToPoints(arr2));
Matrix rotMatrix = Matrices.getRotationJAMA(transform);
Atom tranMatrix = getTranslationVector(transform);
Calc.rotate(aCB, rotMatrix);
Atom virtualCB = Calc.add(aCB, tranMatrix);
virtualCB.setName("CB");
return virtualCB;
}
/**
* Gets euler angles for a matrix given in ZYZ convention. (as e.g. used by
* Jmol)
*
* @param m
* the rotation matrix
* @return the euler values for a rotation around Z, Y, Z in degrees...
*/
public static final double[] getZYZEuler(Matrix m) {
double m22 = m.get(2, 2);
double rY = Math.toDegrees(Math.acos(m22));
double rZ1, rZ2;
if (m22 > .999d || m22 < -.999d) {
rZ1 = Math.toDegrees(Math.atan2(m.get(1, 0), m.get(1, 1)));
rZ2 = 0;
} else {
rZ1 = Math.toDegrees(Math.atan2(m.get(2, 1), -m.get(2, 0)));
rZ2 = Math.toDegrees(Math.atan2(m.get(1, 2), m.get(0, 2)));
}
return new double[] { rZ1, rY, rZ2 };
}
/**
* Convert a rotation Matrix to Euler angles. This conversion uses
* conventions as described on page:
* http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm
* Coordinate System: right hand Positive angle: right hand Order of euler
* angles: heading first, then attitude, then bank
*
* @param m
* the rotation matrix
* @return a array of three doubles containing the three euler angles in
* radians
*/
public static final double[] getXYZEuler(Matrix m) {
double heading, attitude, bank;
// Assuming the angles are in radians.
if (m.get(1, 0) > 0.998) { // singularity at north pole
heading = Math.atan2(m.get(0, 2), m.get(2, 2));
attitude = Math.PI / 2;
bank = 0;
} else if (m.get(1, 0) < -0.998) { // singularity at south pole
heading = Math.atan2(m.get(0, 2), m.get(2, 2));
attitude = -Math.PI / 2;
bank = 0;
} else {
heading = Math.atan2(-m.get(2, 0), m.get(0, 0));
bank = Math.atan2(-m.get(1, 2), m.get(1, 1));
attitude = Math.asin(m.get(1, 0));
}
return new double[] { heading, attitude, bank };
}
/**
* This conversion uses NASA standard aeroplane conventions as described on
* page:
* http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm
* Coordinate System: right hand Positive angle: right hand Order of euler
* angles: heading first, then attitude, then bank. matrix row column
* ordering: [m00 m01 m02] [m10 m11 m12] [m20 m21 m22]
*
* @param heading
* in radians
* @param attitude
* in radians
* @param bank
* in radians
* @return the rotation matrix
*/
public static final Matrix matrixFromEuler(double heading, double attitude,
double bank) {
// Assuming the angles are in radians.
double ch = Math.cos(heading);
double sh = Math.sin(heading);
double ca = Math.cos(attitude);
double sa = Math.sin(attitude);
double cb = Math.cos(bank);
double sb = Math.sin(bank);
Matrix m = new Matrix(3, 3);
m.set(0, 0, ch * ca);
m.set(0, 1, sh * sb - ch * sa * cb);
m.set(0, 2, ch * sa * sb + sh * cb);
m.set(1, 0, sa);
m.set(1, 1, ca * cb);
m.set(1, 2, -ca * sb);
m.set(2, 0, -sh * ca);
m.set(2, 1, sh * sa * cb + ch * sb);
m.set(2, 2, -sh * sa * sb + ch * cb);
return m;
}
/**
* Calculates the angle from centerPt to targetPt in degrees. The return
* should range from [0,360), rotating CLOCKWISE, 0 and 360 degrees
* represents NORTH, 90 degrees represents EAST, etc...
*
* Assumes all points are in the same coordinate space. If they are not, you
* will need to call SwingUtilities.convertPointToScreen or equivalent on
* all arguments before passing them to this function.
*
* @param centerPt
* Point we are rotating around.
* @param targetPt
* Point we want to calculate the angle to.
* @return angle in degrees. This is the angle from centerPt to targetPt.
*/
public static double calcRotationAngleInDegrees(Atom centerPt, Atom targetPt) {
// calculate the angle theta from the deltaY and deltaX values
// (atan2 returns radians values from [-PI,PI])
// 0 currently points EAST.
// NOTE: By preserving Y and X param order to atan2, we are expecting
// a CLOCKWISE angle direction.
double theta = Math.atan2(targetPt.getY() - centerPt.getY(),
targetPt.getX() - centerPt.getX());
// rotate the theta angle clockwise by 90 degrees
// (this makes 0 point NORTH)
// NOTE: adding to an angle rotates it clockwise.
// subtracting would rotate it counter-clockwise
theta += Math.PI / 2.0;
// convert from radians to degrees
// this will give you an angle from [0->270],[-180,0]
double angle = Math.toDegrees(theta);
// convert to positive range [0-360)
// since we want to prevent negative angles, adjust them now.
// we can assume that atan2 will not return a negative value
// greater than one partial rotation
if (angle < 0) {
angle += 360;
}
return angle;
}
public static void main(String[] args) {
Atom a = new AtomImpl();
a.setX(0);
a.setY(0);
a.setZ(0);
Atom b = new AtomImpl();
b.setX(1);
b.setY(1);
b.setZ(0);
logger.info("Angle between atoms: ", calcRotationAngleInDegrees(a, b));
}
public static void rotate(Atom[] ca, Matrix matrix) {
for (Atom atom : ca)
Calc.rotate(atom, matrix);
}
/**
* Shift an array of atoms at once.
*
* @param ca
* array of Atoms to shift
* @param b
* reference Atom vector
*/
public static void shift(Atom[] ca, Atom b) {
for (Atom atom : ca)
Calc.shift(atom, b);
}
/**
* Convert JAMA rotation and translation to a Vecmath transformation matrix.
* Because the JAMA matrix is a pre-multiplication matrix and the Vecmath
* matrix is a post-multiplication one, the rotation matrix is transposed to
* ensure that the transformation they produce is the same.
*
* @param rot
* 3x3 Rotation matrix
* @param trans
* 3x1 translation vector in Atom coordinates
* @return 4x4 transformation matrix
*/
public static Matrix4d getTransformation(Matrix rot, Atom trans) {
return new Matrix4d(new Matrix3d(rot.getColumnPackedCopy()),
new Vector3d(trans.getCoordsAsPoint3d()), 1.0);
}
/**
* Extract the translational vector as an Atom of a transformation matrix.
*
* @param transform
* Matrix4d
* @return Atom shift vector
*/
public static Atom getTranslationVector(Matrix4d transform) {
Atom transl = new AtomImpl();
double[] coords = { transform.m03, transform.m13, transform.m23 };
transl.setCoords(coords);
return transl;
}
/**
* Convert an array of atoms into an array of vecmath points
*
* @param atoms
* list of atoms
* @return list of Point3ds storing the x,y,z coordinates of each atom
*/
public static Point3d[] atomsToPoints(Atom[] atoms) {
Point3d[] points = new Point3d[atoms.length];
for (int i = 0; i < atoms.length; i++) {
points[i] = atoms[i].getCoordsAsPoint3d();
}
return points;
}
/**
* Convert an array of atoms into an array of vecmath points
*
* @param atoms
* list of atoms
* @return list of Point3ds storing the x,y,z coordinates of each atom
*/
public static List<Point3d> atomsToPoints(Collection<Atom> atoms) {
ArrayList<Point3d> points = new ArrayList<>(atoms.size());
for (Atom atom : atoms) {
points.add(atom.getCoordsAsPoint3d());
}
return points;
}
/**
* Calculate the RMSD of two Atom arrays, already superposed.
*
* @param x
* array of Atoms superposed to y
* @param y
* array of Atoms superposed to x
* @return RMSD
*/
public static double rmsd(Atom[] x, Atom[] y) {
return CalcPoint.rmsd(atomsToPoints(x), atomsToPoints(y));
}
/**
* Calculate the TM-Score for the superposition.
*
* <em>Normalizes by the <strong>maximum</strong>-length structure (that is, {@code max\{len1,len2\}}) rather than the minimum.</em>
*
* Atom sets must be superposed.
*
* <p>
* Citation:<br/>
* <i>Zhang Y and Skolnick J (2004). "Scoring function for automated
* assessment of protein structure template quality". Proteins 57: 702 -
* 710.</i>
*
* @param atomSet1
* atom array 1
* @param atomSet2
* atom array 2
* @param len1
* The full length of the protein supplying atomSet1
* @param len2
* The full length of the protein supplying atomSet2
* @return The TM-Score
* @throws StructureException
* @see {@link #getTMScore(Atom[], Atom[], int, int)}, which normalizes by
* the minimum length
*/
public static double getTMScoreAlternate(Atom[] atomSet1, Atom[] atomSet2,
int len1, int len2) throws StructureException {
if (atomSet1.length != atomSet2.length) {
throw new StructureException(
"The two atom sets are not of same length!");
}
if (atomSet1.length > len1) {
throw new StructureException(
"len1 must be greater or equal to the alignment length!");
}
if (atomSet2.length > len2) {
throw new StructureException(
"len2 must be greater or equal to the alignment length!");
}
int Lmax = Math.max(len1, len2);
int Laln = atomSet1.length;
double d0 = 1.24 * Math.cbrt(Lmax - 15.) - 1.8;
double d0sq = d0 * d0;
double sum = 0;
for (int i = 0; i < Laln; i++) {
double d = Calc.getDistance(atomSet1[i], atomSet2[i]);
sum += 1. / (1 + d * d / d0sq);
}
return sum / Lmax;
}
/**
* Calculate the TM-Score for the superposition.
*
* <em>Normalizes by the <strong>minimum</strong>-length structure (that is, {@code min\{len1,len2\}}).</em>
*
* Atom sets must be pre-rotated.
*
* <p>
* Citation:<br/>
* <i>Zhang Y and Skolnick J (2004). "Scoring function for automated
* assessment of protein structure template quality". Proteins 57: 702 -
* 710.</i>
*
* @param atomSet1
* atom array 1
* @param atomSet2
* atom array 2
* @param len1
* The full length of the protein supplying atomSet1
* @param len2
* The full length of the protein supplying atomSet2
* @return The TM-Score
* @throws StructureException
*/
public static double getTMScore(Atom[] atomSet1, Atom[] atomSet2, int len1,
int len2) throws StructureException {
if (atomSet1.length != atomSet2.length) {
throw new StructureException(
"The two atom sets are not of same length!");
}
if (atomSet1.length > len1) {
throw new StructureException(
"len1 must be greater or equal to the alignment length!");
}
if (atomSet2.length > len2) {
throw new StructureException(
"len2 must be greater or equal to the alignment length!");
}
int Lmin = Math.min(len1, len2);
int Laln = atomSet1.length;
double d0 = 1.24 * Math.cbrt(Lmin - 15.) - 1.8;
double d0sq = d0 * d0;
double sum = 0;
for (int i = 0; i < Laln; i++) {
double d = Calc.getDistance(atomSet1[i], atomSet2[i]);
sum += 1. / (1 + d * d / d0sq);
}
return sum / Lmin;
}
}
| Recursive transform for group
| biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java | Recursive transform for group | <ide><path>iojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java
<ide> transform(atom, m);
<ide> }
<ide> for (Group altG : group.getAltLocs()) {
<del> for (Atom atom : altG.getAtoms()) {
<del> transform(atom, m);
<del> }
<add> transform(altG, m);
<ide> }
<ide> }
<ide>
<ide> translate(atom, v);
<ide> }
<ide> for (Group altG : group.getAltLocs()) {
<del> for (Atom atom : altG.getAtoms()) {
<del> translate(atom, v);
<del> }
<add> translate(altG, v);
<ide> }
<ide> }
<ide> |
|
Java | mpl-2.0 | 24bc9946db8ad194834ed8853610e3638c6b2de6 | 0 | kovaloid/infoarchive-sip-sdk,Enterprise-Content-Management/infoarchive-sip-sdk | /*
* Copyright (c) 2016 EMC Corporation. All Rights Reserved.
* EMC Confidential: Restricted Internal Distribution
*/
package com.emc.ia.sdk.support.datetime;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;
import org.junit.Test;
import com.emc.ia.sdk.support.RandomData;
public class WhenWorkingWithDates {
private final RandomData random = new RandomData();
@Test
public void shouldFormatXsdDateTime() {
Date dateTime = randomDate();
TimeZone timeZone = TimeZone.getDefault();
int offset = timeZone.getOffset(dateTime.getTime()) / 1000;
String sign = Arrays.asList("-", "", "+").get(1 + (int)Math.signum(offset));
offset = Math.abs(offset);
int tzHour = offset / 60 / 60;
int tzMinute = offset / 60 % 60;
String expected = String.format("%1$tY-%1$tm-%1$tdT%1$tH:%1$tM:%1$tS%2$s", dateTime, sign);
if (tzHour == 0 && tzMinute == 0) {
expected += "Z";
} else {
expected += String.format("%02d:%02d", tzHour, tzMinute);
}
String actual = Dates.toIso(dateTime);
assertEquals("Date time", expected, actual);
}
@SuppressWarnings("deprecation")
private Date randomDate() {
int year = random.integer(1945, 2045);
int month = random.integer(1, 12);
int day = random.integer(1, 28);
int hour = random.integer(0, 23);
int minute = random.integer(0, 59);
int second = random.integer(0, 29) * 2;
return new Date(year - 1900, month - 1, day, hour, minute, second);
}
@Test
public void shouldReturnNullOnMissingDateTime() {
assertNull("To ISO", Dates.toIso(null));
assertNull("From ISO", Dates.fromIso(null));
}
@Test
public void shouldParseXsdDateTime() {
Date expected = randomDate();
Date actual = Dates.fromIso(Dates.toIso(expected));
long deltaSeconds = Math.abs(actual.getTime() - expected.getTime()) / 1000;
assertEquals("Date time", 0, deltaSeconds);
}
}
| core/src/test/java/com/emc/ia/sdk/support/datetime/WhenWorkingWithDates.java | /*
* Copyright (c) 2016 EMC Corporation. All Rights Reserved.
* EMC Confidential: Restricted Internal Distribution
*/
package com.emc.ia.sdk.support.datetime;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;
import org.junit.Test;
import com.emc.ia.sdk.support.RandomData;
public class WhenWorkingWithDates {
private final RandomData random = new RandomData();
@Test
public void shouldFormatXsdDateTime() {
Date dateTime = randomDate();
TimeZone timeZone = TimeZone.getDefault();
int offset = timeZone.getOffset(dateTime.getTime()) / 1000;
String sign = Arrays.asList("-", "", "+").get(1 + (int)Math.signum(offset));
offset = Math.abs(offset);
int tzHour = offset / 60 / 60;
int tzMinute = offset / 60 % 60;
String expected = String.format("%1$tY-%1$tm-%1$tdT%1$tH:%1$tM:%1$tS%2$s%3$02d:%4$02d",
dateTime, sign, tzHour, tzMinute);
String actual = Dates.toIso(dateTime);
assertEquals("Date time", expected, actual);
}
@SuppressWarnings("deprecation")
private Date randomDate() {
int year = random.integer(1945, 2045);
int month = random.integer(1, 12);
int day = random.integer(1, 28);
int hour = random.integer(0, 23);
int minute = random.integer(0, 59);
int second = random.integer(0, 29) * 2;
return new Date(year - 1900, month - 1, day, hour, minute, second);
}
@Test
public void shouldReturnNullOnMissingDateTime() {
assertNull("To ISO", Dates.toIso(null));
assertNull("From ISO", Dates.fromIso(null));
}
@Test
public void shouldParseXsdDateTime() {
Date expected = randomDate();
Date actual = Dates.fromIso(Dates.toIso(expected));
long deltaSeconds = Math.abs(actual.getTime() - expected.getTime()) / 1000;
assertEquals("Date time", 0, deltaSeconds);
}
}
| Attempt to fix test that fails on Travis | core/src/test/java/com/emc/ia/sdk/support/datetime/WhenWorkingWithDates.java | Attempt to fix test that fails on Travis | <ide><path>ore/src/test/java/com/emc/ia/sdk/support/datetime/WhenWorkingWithDates.java
<ide> offset = Math.abs(offset);
<ide> int tzHour = offset / 60 / 60;
<ide> int tzMinute = offset / 60 % 60;
<del> String expected = String.format("%1$tY-%1$tm-%1$tdT%1$tH:%1$tM:%1$tS%2$s%3$02d:%4$02d",
<del> dateTime, sign, tzHour, tzMinute);
<add> String expected = String.format("%1$tY-%1$tm-%1$tdT%1$tH:%1$tM:%1$tS%2$s", dateTime, sign);
<add> if (tzHour == 0 && tzMinute == 0) {
<add> expected += "Z";
<add> } else {
<add> expected += String.format("%02d:%02d", tzHour, tzMinute);
<add> }
<ide>
<ide> String actual = Dates.toIso(dateTime);
<ide> |
|
Java | apache-2.0 | 63d06664dd92cd0f9e4310fc003046da5671c9a1 | 0 | vdbaan/zap-extensions,ccgreen13/zap-extensions,ccgreen13/zap-extensions,schoeth/zap-extensions,schoeth/zap-extensions,schoeth/zap-extensions,JordanGS/zap-extensions,rnehra01/zap-extensions,AndiDog/zap-extensions,zaproxy/zap-extensions,zapbot/zap-extensions,secdec/zap-extensions,JordanGS/zap-extensions,secdec/zap-extensions,denniskniep/zap-extensions,zapbot/zap-extensions,veggiespam/zap-extensions,veggiespam/zap-extensions,kamiNaranjo/zap-extensions,thc202/zap-extensions,ccgreen13/zap-extensions,veggiespam/zap-extensions,zaproxy/zap-extensions,thc202/zap-extensions,psiinon/zap-extensions,msrader/zap-extensions,vdbaan/zap-extensions,schoeth/zap-extensions,surikato/zap-extensions,zapbot/zap-extensions,kingthorin/zap-extensions,JordanGS/zap-extensions,kingthorin/zap-extensions,denniskniep/zap-extensions,AndiDog/zap-extensions,hn3000/zap-extensions,vdbaan/zap-extensions,kingthorin/zap-extensions,secdec/zap-extensions,msrader/zap-extensions,AndiDog/zap-extensions,psiinon/zap-extensions,zaproxy/zap-extensions,rnehra01/zap-extensions,thc202/zap-extensions,JordanGS/zap-extensions,amuntner/zap-extensions,thc202/zap-extensions,mabdi/zap-extensions,veggiespam/zap-extensions,psiinon/zap-extensions,JordanGS/zap-extensions,amuntner/zap-extensions,psiinon/zap-extensions,veggiespam/zap-extensions,amuntner/zap-extensions,surikato/zap-extensions,secdec/zap-extensions,vdbaan/zap-extensions,brunoqc/zap-extensions,thc202/zap-extensions,amuntner/zap-extensions,schoeth/zap-extensions,surikato/zap-extensions,vdbaan/zap-extensions,rnehra01/zap-extensions,schoeth/zap-extensions,zapbot/zap-extensions,zaproxy/zap-extensions,hn3000/zap-extensions,mabdi/zap-extensions,psiinon/zap-extensions,JordanGS/zap-extensions,rnehra01/zap-extensions,brunoqc/zap-extensions,rnehra01/zap-extensions,denniskniep/zap-extensions,schoeth/zap-extensions,rnehra01/zap-extensions,msrader/zap-extensions,kingthorin/zap-extensions,denniskniep/zap-extensions,zaproxy/zap-extensions,zaproxy/zap-extensions,kingthorin/zap-extensions,denniskniep/zap-extensions,veggiespam/zap-extensions,secdec/zap-extensions,psiinon/zap-extensions,zapbot/zap-extensions,hn3000/zap-extensions,denniskniep/zap-extensions,amuntner/zap-extensions,mabdi/zap-extensions,amuntner/zap-extensions,kamiNaranjo/zap-extensions,secdec/zap-extensions,rnehra01/zap-extensions,thc202/zap-extensions,vdbaan/zap-extensions,brunoqc/zap-extensions,kingthorin/zap-extensions,vdbaan/zap-extensions,kamiNaranjo/zap-extensions,zapbot/zap-extensions,JordanGS/zap-extensions,secdec/zap-extensions | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* 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.zaproxy.zap.extension.pscanrules;
import net.htmlparser.jericho.Source;
import org.apache.commons.httpclient.HttpStatus;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;
import org.zaproxy.zap.extension.pscanrules.utils.ContentMatcher;
/**
* Plugin able to analyze the content for Application Error messages. The plugin
* find the first occurrence of an exact match or a regex pattern matching
* accordding to an external file definition. The vulnerability can be included
* innside the Information Leakage family (WASC-13)
*
* @author yhawke 2013
*/
public class ApplicationErrorScanner extends PluginPassiveScanner {
// Name of the file related to pattern's definition list
private static final String APP_ERRORS_FILE = "/org/zaproxy/zap/extension/pscanrules/resources/application_errors.xml";
// Evidence used for Internal Server Error doccurrence
private static final String EVIDENCE_INTERNAL_SERVER_ERROR = "HTTP 500 Internal server error";
// Inner Content Matcher component with pattern definitions
private static final ContentMatcher matcher = ContentMatcher.getInstance(APP_ERRORS_FILE);
// Inner Thread Parent variable
private PassiveScanThread parent = null;
/**
* Get this plugin id
*
* @return the ZAP id
*/
@Override
public int getPluginId() {
return 90022;
}
/**
* Get the plugin name
*
* @return the plugin name
*/
@Override
public String getName() {
return "Application Error Disclosure";
}
private String getDescription() {
return "This page contains an error/warning message that may disclose sensitive information like "
+ "the location of the file that produced the unhandled exception. "
+ "This information can be used to launch further attacks against the web application."
+ "The alert could be a false positive if the error message is found inside a documentation page.";
}
private String getSolution() {
return "Review the source code of this page";
}
private String getReference() {
return null;
}
private int getRisk() {
return Alert.RISK_MEDIUM;
}
private int getCweId() {
return 200;
}
private int getWascId() {
return 13;
}
/**
* Set the Scanner thred parent object
*
* @param parent the PassiveScanThread parent object
*/
@Override
public void setParent(PassiveScanThread parent) {
this.parent = parent;
}
/**
* Scan the request. Currently it does nothing.
*
* @param msg the HTTP message
* @param id the id of the request
*/
@Override
public void scanHttpRequestSend(HttpMessage msg, int id) {
// Do Nothing it's related to response managed
}
/**
* Perform the passive scanning of application errors inside the response
* content
*
* @param msg the message that need to be checked
* @param id the id of the session
* @param source the source code of the response
*/
@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
// First check if it's an INTERNAL SERVER ERROR
int status = msg.getResponseHeader().getStatusCode();
if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
// We found it!
// The AS raise an Internal Error
// so a possible disclosure can be found
raiseAlert(msg, id, EVIDENCE_INTERNAL_SERVER_ERROR);
} else if (status != HttpStatus.SC_NOT_FOUND) {
String evidence = matcher.findInContent(msg.getResponseBody().toString());
if (evidence != null) {
// We found it!
// There exists a positive match of an
// application error occurrence
raiseAlert(msg, id, evidence);
}
}
}
// Internal service method for alert management
private void raiseAlert(HttpMessage msg, int id, String evidence) {
// Raise an alert according to Passive Scan Rule model
// description, uri, param, attack, otherInfo,
// solution, reference, evidence, cweId, wascId, msg
Alert alert = new Alert(getPluginId(), getRisk(), Alert.CONFIRMED, getName());
alert.setDetail(
getDescription(),
msg.getRequestHeader().getURI().toString(),
"N/A",
"",
"",
getSolution(),
getReference(),
evidence, // evidence
getCweId(), // CWE Id
getWascId(), // WASC Id - Info leakage
msg);
parent.raiseAlert(id, alert);
}
}
| src/org/zaproxy/zap/extension/pscanrules/ApplicationErrorScanner.java | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* 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.zaproxy.zap.extension.pscanrules;
import net.htmlparser.jericho.Source;
import org.apache.commons.httpclient.HttpStatus;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;
import org.zaproxy.zap.extension.pscanrules.utils.ContentMatcher;
/**
* Plugin able to analyze the content for Application Error messages. The plugin
* find the first occurrence of an exact match or a regex pattern matching
* accordding to an external file definition. The vulnerability can be included
* innside the Information Leakage family (WASC-13)
*
* @author yhawke 2013
*/
public class ApplicationErrorScanner extends PluginPassiveScanner {
// Name of the file related to pattern's definition list
private static final String APP_ERRORS_FILE = "/org/zaproxy/zap/extension/pscanrules/resources/application_errors.xml";
// Evidence used for Internal Server Error doccurrence
private static final String EVIDENCE_INTERNAL_SERVER_ERROR = "HTTP 500 Internal server error";
// Inner Content Matcher component with pattern definitions
private static final ContentMatcher matcher = ContentMatcher.getInstance(APP_ERRORS_FILE);
// Inner Thread Parent variable
private PassiveScanThread parent = null;
/**
* Get this plugin id
*
* @return the ZAP id
*/
@Override
public int getPluginId() {
return 90022;
}
/**
* Get the plugin name
*
* @return the plugin name
*/
@Override
public String getName() {
return "Application Error Disclosure";
}
private String getDescription() {
return "This page contains an error/warning message that may disclose sensitive information like "
+ "the location of the file that produced the unhandled exception. "
+ "This information can be used to launch further attacks against the web application."
+ "The alert could be a false positive if the error message is found inside a documentation page.";
}
private String getSolution() {
return "Review the source code of this page";
}
private String getReference() {
return null;
}
private int getRisk() {
return Alert.RISK_MEDIUM;
}
private int getCweId() {
return 200;
}
private int getWascId() {
return 13;
}
/**
* Set the Scanner thred parent object
*
* @param parent the PassiveScanThread parent object
*/
@Override
public void setParent(PassiveScanThread parent) {
this.parent = parent;
}
/**
* Scan the request. Currently it does nothing.
*
* @param msg the HTTP message
* @param id the id of the request
*/
@Override
public void scanHttpRequestSend(HttpMessage msg, int id) {
// Do Nothing it's related to response managed
}
/**
* Perform the passive scanning of application errors inside the response
* content
*
* @param msg the message that need to be checked
* @param id the id of the session
* @param source the source code of the response
*/
@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
// First check if it's an INTERNAL SERVER ERROR
int status = msg.getResponseHeader().getStatusCode();
if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
// We found it!
// The AS raise an Internal Error
// so a possible disclosure can be found
raiseAlert(msg, id, EVIDENCE_INTERNAL_SERVER_ERROR);
} else if (status != HttpStatus.SC_NOT_FOUND) {
String evidence = matcher.findInContent(msg.getResponseBody().toString());
if (evidence != null) {
// We found it!
// There exists a positive match of an
// application error occurrence
raiseAlert(msg, id, evidence);
}
}
}
// Internal service method for alert management
private void raiseAlert(HttpMessage msg, int id, String evidence) {
// Raise an alert according to Passive Scan Rule model
// description, uri, param, attack, otherInfo,
// solution, reference, evidence, cweId, wascId, msg
Alert alert = new Alert(getPluginId(), getRisk(), Alert.WARNING, getName());
alert.setDetail(
getDescription(),
msg.getRequestHeader().getURI().toString(),
"N/A",
"",
"",
getSolution(),
getReference(),
evidence, // evidence
getCweId(), // CWE Id
getWascId(), // WASC Id - Info leakage
msg);
parent.raiseAlert(id, alert);
}
}
| Update from deprecated Alert.WARNING | src/org/zaproxy/zap/extension/pscanrules/ApplicationErrorScanner.java | Update from deprecated Alert.WARNING | <ide><path>rc/org/zaproxy/zap/extension/pscanrules/ApplicationErrorScanner.java
<ide> // Raise an alert according to Passive Scan Rule model
<ide> // description, uri, param, attack, otherInfo,
<ide> // solution, reference, evidence, cweId, wascId, msg
<del> Alert alert = new Alert(getPluginId(), getRisk(), Alert.WARNING, getName());
<add> Alert alert = new Alert(getPluginId(), getRisk(), Alert.CONFIRMED, getName());
<ide> alert.setDetail(
<ide> getDescription(),
<ide> msg.getRequestHeader().getURI().toString(), |
|
Java | apache-2.0 | 36f3cda2504a7b8daab7f7e0024355d7f3b077f8 | 0 | mpage23/flyway,CristianUrbainski/flyway,brennan-collins/flyway,Dispader/flyway,wuschi/flyway,jack-luj/flyway,jmahonin/flyway,cdedie/flyway,togusafish/lnial-_-flyway,nathanvick/flyway,FulcrumTechnologies/flyway,chrsoo/flyway,FulcrumTechnologies/flyway,pauxus/flyway,kevinc0825/flyway,murdos/flyway,mpage23/flyway,Muni10/flyway,wuschi/flyway,chrsoo/flyway,CristianUrbainski/flyway,flyway/flyway,super132/flyway,Dispader/flyway,Muni10/flyway,IAops/flyway,ysobj/flyway,Dispader/flyway,IAops/flyway,cdedie/flyway,ysobj/flyway,jack-luj/flyway,jmahonin/flyway,michaelyaakoby/flyway,CristianUrbainski/flyway,fdefalco/flyway,nathanvick/flyway,kevinc0825/flyway,super132/flyway,livingobjects/flyway,livingobjects/flyway,nathanvick/flyway,togusafish/lnial-_-flyway,flyway/flyway,super132/flyway,pauxus/flyway,fdefalco/flyway,kevinc0825/flyway,wuschi/flyway,FulcrumTechnologies/flyway,brennan-collins/flyway,Muni10/flyway,murdos/flyway,mpage23/flyway,livingobjects/flyway,IAops/flyway,ysobj/flyway,fdefalco/flyway,michaelyaakoby/flyway,Muni10/flyway,pauxus/flyway,brennan-collins/flyway,murdos/flyway,krishofmans/flyway,togusafish/lnial-_-flyway,jack-luj/flyway,pauxus/flyway,krishofmans/flyway,cdedie/flyway,krishofmans/flyway,chrsoo/flyway | /**
* Copyright (C) 2010-2012 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 com.googlecode.flyway.core.dbsupport.oracle;
import com.googlecode.flyway.core.api.FlywayException;
import com.googlecode.flyway.core.dbsupport.DbSupport;
import com.googlecode.flyway.core.dbsupport.SqlScript;
import com.googlecode.flyway.core.dbsupport.SqlStatement;
import com.googlecode.flyway.core.dbsupport.SqlStatementBuilder;
import com.googlecode.flyway.core.util.logging.Log;
import com.googlecode.flyway.core.util.logging.LogFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Oracle-specific support.
*/
public class OracleDbSupport extends DbSupport {
/**
* Logger.
*/
private static final Log LOG = LogFactory.getLog(OracleDbSupport.class);
/**
* Creates a new instance.
*
* @param connection The connection to use.
*/
public OracleDbSupport(Connection connection) {
super(new OracleJdbcTemplate(connection));
}
public String getScriptLocation() {
return "com/googlecode/flyway/core/dbsupport/oracle/";
}
public String getCurrentUserFunction() {
return "USER";
}
public String getCurrentSchema() throws SQLException {
return jdbcTemplate.queryForString("SELECT USER FROM dual");
}
@Override
public void setCurrentSchema(String schema) throws SQLException {
jdbcTemplate.execute("ALTER SESSION SET CURRENT_SCHEMA=" + quote(schema));
}
public boolean isSchemaEmpty(String schema) throws SQLException {
int objectCount = jdbcTemplate.queryForInt("SELECT count(*) FROM all_objects WHERE owner = ?", schema);
return objectCount == 0;
}
public boolean tableExistsNoQuotes(final String schema, final String table) throws SQLException {
return jdbcTemplate.tableExists(null, schema.toUpperCase(), table.toUpperCase());
}
public boolean tableExists(String schema, String table) throws SQLException {
return jdbcTemplate.tableExists(null, schema, table);
}
public boolean columnExists(String schema, String table, String column) throws SQLException {
return jdbcTemplate.columnExists(null, schema, table, column);
}
public boolean supportsDdlTransactions() {
return false;
}
public void lockTable(String schema, String table) throws SQLException {
jdbcTemplate.execute("select * from " + quote(schema, table) + " for update");
}
public String getBooleanTrue() {
return "1";
}
public String getBooleanFalse() {
return "0";
}
public SqlStatementBuilder createSqlStatementBuilder() {
return new OracleSqlStatementBuilder();
}
public SqlScript createCleanScript(String schema) throws SQLException {
if ("SYSTEM".equals(schema.toUpperCase())) {
throw new FlywayException("Clean not supported on Oracle for user 'SYSTEM'! You should NEVER add your own objects to the SYSTEM schema!");
}
final List<String> allDropStatements = new ArrayList<String>();
allDropStatements.add("PURGE RECYCLEBIN");
allDropStatements.addAll(generateDropStatementsForSpatialExtensions(schema));
allDropStatements.addAll(generateDropStatementsForObjectType("SEQUENCE", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("FUNCTION", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("MATERIALIZED VIEW", "PRESERVE TABLE", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("PACKAGE", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("PROCEDURE", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("SYNONYM", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("TRIGGER", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("VIEW", "CASCADE CONSTRAINTS", schema));
allDropStatements.addAll(generateDropStatementsForTables(schema));
allDropStatements.addAll(generateDropStatementsForXmlTables(schema));
allDropStatements.addAll(generateDropStatementsForObjectType("TYPE", "FORCE", schema));
List<SqlStatement> sqlStatements = new ArrayList<SqlStatement>();
int lineNumber = 1;
for (String dropStatement : allDropStatements) {
sqlStatements.add(new SqlStatement(lineNumber, dropStatement));
lineNumber++;
}
return new SqlScript(sqlStatements, this);
}
/**
* Generates the drop statements for all tables.
*
* @param schema The schema for which to generate the statements.
* @return The complete drop statements, ready to execute.
* @throws SQLException when the drop statements could not be generated.
*/
private List<String> generateDropStatementsForTables(String schema) throws SQLException {
String query = "SELECT table_name FROM all_tables WHERE owner = ?"
// Ignore Recycle bin objects
+ " AND table_name NOT LIKE 'BIN$%'"
// Ignore Spatial Index Tables as they get dropped automatically when the index gets dropped.
+ " AND table_name NOT LIKE 'MDRT_%$'"
// Ignore Materialized View Logs
+ " AND table_name NOT LIKE 'MLOG$%' AND table_name NOT LIKE 'RUPD$%'"
// Ignore Oracle Text Index Tables
+ " AND table_name NOT LIKE 'DR$%'"
// Ignore Index Organized Tables
+ " AND table_name NOT LIKE 'SYS_IOT_OVER_%'"
// Ignore Nested Tables
+ " AND nested != 'YES'"
// Ignore Nested Tables
+ " AND secondary != 'Y'";
List<String> objectNames = jdbcTemplate.queryForStringList(query, schema);
List<String> dropStatements = new ArrayList<String>();
for (String objectName : objectNames) {
dropStatements.add("DROP TABLE " + quote(schema, objectName) + " CASCADE CONSTRAINTS PURGE");
}
return dropStatements;
}
/**
* Generates the drop statements for all xml tables.
*
* @param schema The schema for which to generate the statements.
* @return The complete drop statements, ready to execute.
* @throws SQLException when the drop statements could not be generated.
*/
private List<String> generateDropStatementsForXmlTables(String schema) throws SQLException {
String query = "SELECT table_name FROM all_xml_tables WHERE owner = ?";
List<String> objectNames = jdbcTemplate.queryForStringList(query, schema);
List<String> dropStatements = new ArrayList<String>();
for (String objectName : objectNames) {
dropStatements.add("DROP TABLE " + quote(schema, objectName) + " PURGE");
}
return dropStatements;
}
/**
* Generates the drop statements for all database objects of this type.
*
* @param objectType The type of database object to drop.
* @param extraArguments The extra arguments to add to the drop statement.
* @param schema The schema for which to generate the statements.
* @return The complete drop statements, ready to execute.
* @throws SQLException when the drop statements could not be generated.
*/
private List<String> generateDropStatementsForObjectType(String objectType, String extraArguments, String schema) throws SQLException {
String query = "SELECT object_name FROM all_objects WHERE object_type = ? AND owner = ?"
// Ignore Spatial Index Sequences as they get dropped automatically when the index gets dropped.
+ " AND object_name NOT LIKE 'MDRS_%$'";
List<String> objectNames = jdbcTemplate.queryForStringList(query, objectType, schema);
List<String> dropStatements = new ArrayList<String>();
for (String objectName : objectNames) {
dropStatements.add("DROP " + objectType + " " + quote(schema, objectName) + " " + extraArguments);
}
return dropStatements;
}
/**
* Generates the drop statements for Oracle Spatial Extensions-related database objects.
*
* @param schema The schema for which to generate the statements.
* @return The complete drop statements, ready to execute.
* @throws SQLException when the drop statements could not be generated.
*/
private List<String> generateDropStatementsForSpatialExtensions(String schema) throws SQLException {
List<String> statements = new ArrayList<String>();
if (!spatialExtensionsAvailable()) {
LOG.debug("Oracle Spatial Extensions are not available. No cleaning of MDSYS tables and views.");
return statements;
}
if (!getCurrentSchema().equalsIgnoreCase(schema)) {
int count = jdbcTemplate.queryForInt("SELECT COUNT (*) FROM all_sdo_geom_metadata WHERE owner=?", schema);
count += jdbcTemplate.queryForInt("SELECT COUNT (*) FROM all_sdo_index_info WHERE sdo_index_owner=?", schema);
if (count > 0) {
LOG.warn("Unable to clean Oracle Spatial objects for schema '" + schema + "' as they do not belong to the default schema for this connection!");
}
return statements;
}
statements.add("DELETE FROM mdsys.user_sdo_geom_metadata");
List<String> indexNames = jdbcTemplate.queryForStringList("select INDEX_NAME from USER_SDO_INDEX_INFO");
for (String indexName : indexNames) {
statements.add("DROP INDEX \"" + indexName + "\"");
}
return statements;
}
/**
* Checks whether Oracle Spatial extensions are available or not.
*
* @return {@code true} if they are available, {@code false} if not.
* @throws SQLException when checking availability of the spatial extensions failed.
*/
private boolean spatialExtensionsAvailable() throws SQLException {
return jdbcTemplate.queryForInt("SELECT COUNT(*) FROM all_views WHERE owner = 'MDSYS' AND view_name = 'USER_SDO_GEOM_METADATA'") > 0;
}
@Override
public String doQuote(String identifier) {
return "\"" + identifier + "\"";
}
}
| flyway-core/src/main/java/com/googlecode/flyway/core/dbsupport/oracle/OracleDbSupport.java | /**
* Copyright (C) 2010-2012 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 com.googlecode.flyway.core.dbsupport.oracle;
import com.googlecode.flyway.core.api.FlywayException;
import com.googlecode.flyway.core.dbsupport.DbSupport;
import com.googlecode.flyway.core.dbsupport.SqlScript;
import com.googlecode.flyway.core.dbsupport.SqlStatement;
import com.googlecode.flyway.core.dbsupport.SqlStatementBuilder;
import com.googlecode.flyway.core.util.logging.Log;
import com.googlecode.flyway.core.util.logging.LogFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Oracle-specific support.
*/
public class OracleDbSupport extends DbSupport {
/**
* Logger.
*/
private static final Log LOG = LogFactory.getLog(OracleDbSupport.class);
/**
* Creates a new instance.
*
* @param connection The connection to use.
*/
public OracleDbSupport(Connection connection) {
super(new OracleJdbcTemplate(connection));
}
public String getScriptLocation() {
return "com/googlecode/flyway/core/dbsupport/oracle/";
}
public String getCurrentUserFunction() {
return "USER";
}
public String getCurrentSchema() throws SQLException {
return jdbcTemplate.queryForString("SELECT USER FROM dual");
}
@Override
public void setCurrentSchema(String schema) throws SQLException {
jdbcTemplate.execute("ALTER SESSION SET CURRENT_SCHEMA=" + quote(schema));
}
public boolean isSchemaEmpty(String schema) throws SQLException {
int objectCount = jdbcTemplate.queryForInt("SELECT count(*) FROM all_objects WHERE owner = ?", schema);
return objectCount == 0;
}
public boolean tableExistsNoQuotes(final String schema, final String table) throws SQLException {
return jdbcTemplate.tableExists(null, schema.toUpperCase(), table.toUpperCase());
}
public boolean tableExists(String schema, String table) throws SQLException {
return jdbcTemplate.tableExists(null, schema, table);
}
public boolean columnExists(String schema, String table, String column) throws SQLException {
return jdbcTemplate.columnExists(null, schema, table, column);
}
public boolean supportsDdlTransactions() {
return false;
}
public void lockTable(String schema, String table) throws SQLException {
jdbcTemplate.update("select * from " + quote(schema) + "." + quote(table) + " for update");
}
public String getBooleanTrue() {
return "1";
}
public String getBooleanFalse() {
return "0";
}
public SqlStatementBuilder createSqlStatementBuilder() {
return new OracleSqlStatementBuilder();
}
public SqlScript createCleanScript(String schema) throws SQLException {
if ("SYSTEM".equals(schema.toUpperCase())) {
throw new FlywayException("Clean not supported on Oracle for user 'SYSTEM'! You should NEVER add your own objects to the SYSTEM schema!");
}
final List<String> allDropStatements = new ArrayList<String>();
allDropStatements.add("PURGE RECYCLEBIN");
allDropStatements.addAll(generateDropStatementsForSpatialExtensions(schema));
allDropStatements.addAll(generateDropStatementsForObjectType("SEQUENCE", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("FUNCTION", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("MATERIALIZED VIEW", "PRESERVE TABLE", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("PACKAGE", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("PROCEDURE", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("SYNONYM", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("TRIGGER", "", schema));
allDropStatements.addAll(generateDropStatementsForObjectType("VIEW", "CASCADE CONSTRAINTS", schema));
allDropStatements.addAll(generateDropStatementsForTables(schema));
allDropStatements.addAll(generateDropStatementsForXmlTables(schema));
allDropStatements.addAll(generateDropStatementsForObjectType("TYPE", "FORCE", schema));
List<SqlStatement> sqlStatements = new ArrayList<SqlStatement>();
int lineNumber = 1;
for (String dropStatement : allDropStatements) {
sqlStatements.add(new SqlStatement(lineNumber, dropStatement));
lineNumber++;
}
return new SqlScript(sqlStatements, this);
}
/**
* Generates the drop statements for all tables.
*
* @param schema The schema for which to generate the statements.
* @return The complete drop statements, ready to execute.
* @throws SQLException when the drop statements could not be generated.
*/
private List<String> generateDropStatementsForTables(String schema) throws SQLException {
String query = "SELECT table_name FROM all_tables WHERE owner = ?"
// Ignore Recycle bin objects
+ " AND table_name NOT LIKE 'BIN$%'"
// Ignore Spatial Index Tables as they get dropped automatically when the index gets dropped.
+ " AND table_name NOT LIKE 'MDRT_%$'"
// Ignore Materialized View Logs
+ " AND table_name NOT LIKE 'MLOG$%' AND table_name NOT LIKE 'RUPD$%'"
// Ignore Oracle Text Index Tables
+ " AND table_name NOT LIKE 'DR$%'"
// Ignore Index Organized Tables
+ " AND table_name NOT LIKE 'SYS_IOT_OVER_%'"
// Ignore Nested Tables
+ " AND nested != 'YES'"
// Ignore Nested Tables
+ " AND secondary != 'Y'";
List<String> objectNames = jdbcTemplate.queryForStringList(query, schema);
List<String> dropStatements = new ArrayList<String>();
for (String objectName : objectNames) {
dropStatements.add("DROP TABLE " + quote(schema, objectName) + " CASCADE CONSTRAINTS PURGE");
}
return dropStatements;
}
/**
* Generates the drop statements for all xml tables.
*
* @param schema The schema for which to generate the statements.
* @return The complete drop statements, ready to execute.
* @throws SQLException when the drop statements could not be generated.
*/
private List<String> generateDropStatementsForXmlTables(String schema) throws SQLException {
String query = "SELECT table_name FROM all_xml_tables WHERE owner = ?";
List<String> objectNames = jdbcTemplate.queryForStringList(query, schema);
List<String> dropStatements = new ArrayList<String>();
for (String objectName : objectNames) {
dropStatements.add("DROP TABLE " + quote(schema, objectName) + " PURGE");
}
return dropStatements;
}
/**
* Generates the drop statements for all database objects of this type.
*
* @param objectType The type of database object to drop.
* @param extraArguments The extra arguments to add to the drop statement.
* @param schema The schema for which to generate the statements.
* @return The complete drop statements, ready to execute.
* @throws SQLException when the drop statements could not be generated.
*/
private List<String> generateDropStatementsForObjectType(String objectType, String extraArguments, String schema) throws SQLException {
String query = "SELECT object_name FROM all_objects WHERE object_type = ? AND owner = ?"
// Ignore Spatial Index Sequences as they get dropped automatically when the index gets dropped.
+ " AND object_name NOT LIKE 'MDRS_%$'";
List<String> objectNames = jdbcTemplate.queryForStringList(query, objectType, schema);
List<String> dropStatements = new ArrayList<String>();
for (String objectName : objectNames) {
dropStatements.add("DROP " + objectType + " " + quote(schema, objectName) + " " + extraArguments);
}
return dropStatements;
}
/**
* Generates the drop statements for Oracle Spatial Extensions-related database objects.
*
* @param schema The schema for which to generate the statements.
* @return The complete drop statements, ready to execute.
* @throws SQLException when the drop statements could not be generated.
*/
private List<String> generateDropStatementsForSpatialExtensions(String schema) throws SQLException {
List<String> statements = new ArrayList<String>();
if (!spatialExtensionsAvailable()) {
LOG.debug("Oracle Spatial Extensions are not available. No cleaning of MDSYS tables and views.");
return statements;
}
if (!getCurrentSchema().equalsIgnoreCase(schema)) {
int count = jdbcTemplate.queryForInt("SELECT COUNT (*) FROM all_sdo_geom_metadata WHERE owner=?", schema);
count += jdbcTemplate.queryForInt("SELECT COUNT (*) FROM all_sdo_index_info WHERE sdo_index_owner=?", schema);
if (count > 0) {
LOG.warn("Unable to clean Oracle Spatial objects for schema '" + schema + "' as they do not belong to the default schema for this connection!");
}
return statements;
}
statements.add("DELETE FROM mdsys.user_sdo_geom_metadata");
List<String> indexNames = jdbcTemplate.queryForStringList("select INDEX_NAME from USER_SDO_INDEX_INFO");
for (String indexName : indexNames) {
statements.add("DROP INDEX \"" + indexName + "\"");
}
return statements;
}
/**
* Checks whether Oracle Spatial extensions are available or not.
*
* @return {@code true} if they are available, {@code false} if not.
* @throws SQLException when checking availability of the spatial extensions failed.
*/
private boolean spatialExtensionsAvailable() throws SQLException {
return jdbcTemplate.queryForInt("SELECT COUNT(*) FROM all_views WHERE owner = 'MDSYS' AND view_name = 'USER_SDO_GEOM_METADATA'") > 0;
}
@Override
public String doQuote(String identifier) {
return "\"" + identifier + "\"";
}
}
| Attempt to fix "SQL string is not a DML statement" for Oracle table locking
| flyway-core/src/main/java/com/googlecode/flyway/core/dbsupport/oracle/OracleDbSupport.java | Attempt to fix "SQL string is not a DML statement" for Oracle table locking | <ide><path>lyway-core/src/main/java/com/googlecode/flyway/core/dbsupport/oracle/OracleDbSupport.java
<ide> }
<ide>
<ide> public void lockTable(String schema, String table) throws SQLException {
<del> jdbcTemplate.update("select * from " + quote(schema) + "." + quote(table) + " for update");
<add> jdbcTemplate.execute("select * from " + quote(schema, table) + " for update");
<ide> }
<ide>
<ide> public String getBooleanTrue() { |
|
Java | apache-2.0 | a48bd9e68f06824c2596244c2c7e3a7bfb12b229 | 0 | gathreya/rice-kc,cniesen/rice,bhutchinson/rice,kuali/kc-rice,kuali/kc-rice,shahess/rice,rojlarge/rice-kc,shahess/rice,ewestfal/rice-svn2git-test,ewestfal/rice,geothomasp/kualico-rice-kc,smith750/rice,ewestfal/rice-svn2git-test,bsmith83/rice-1,ewestfal/rice,jwillia/kc-rice1,ewestfal/rice,smith750/rice,geothomasp/kualico-rice-kc,kuali/kc-rice,cniesen/rice,smith750/rice,bsmith83/rice-1,UniversityOfHawaiiORS/rice,ewestfal/rice-svn2git-test,shahess/rice,sonamuthu/rice-1,bhutchinson/rice,kuali/kc-rice,shahess/rice,ewestfal/rice,geothomasp/kualico-rice-kc,rojlarge/rice-kc,jwillia/kc-rice1,bhutchinson/rice,gathreya/rice-kc,bsmith83/rice-1,rojlarge/rice-kc,sonamuthu/rice-1,UniversityOfHawaiiORS/rice,gathreya/rice-kc,cniesen/rice,geothomasp/kualico-rice-kc,ewestfal/rice,bhutchinson/rice,bsmith83/rice-1,smith750/rice,sonamuthu/rice-1,cniesen/rice,jwillia/kc-rice1,shahess/rice,UniversityOfHawaiiORS/rice,geothomasp/kualico-rice-kc,smith750/rice,ewestfal/rice-svn2git-test,kuali/kc-rice,bhutchinson/rice,jwillia/kc-rice1,UniversityOfHawaiiORS/rice,gathreya/rice-kc,jwillia/kc-rice1,cniesen/rice,rojlarge/rice-kc,rojlarge/rice-kc,UniversityOfHawaiiORS/rice,sonamuthu/rice-1,gathreya/rice-kc | /**
* Copyright 2005-2013 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.demo.uif.library.widgets;
import org.junit.Test;
import org.kuali.rice.krad.demo.uif.library.DemoLibraryBase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
/**
* @author Kuali Rice Team ([email protected])
*/
public class DemoWidgetsDisclosureAft extends DemoLibraryBase {
/**
* /kr-krad/kradsampleapp?viewId=Demo-Disclosure-View&methodToCall=start
*/
public static final String BOOKMARK_URL = "/kr-krad/kradsampleapp?viewId=Demo-Disclosure-View&methodToCall=start";
@Override
protected String getBookmarkUrl() {
return BOOKMARK_URL;
}
@Override
protected void navigate() throws Exception {
navigateToLibraryDemo("Widgets", "Disclosure");
}
protected void testWidgetsDisclosureDefault() throws Exception {
waitAndClickByLinkText("Default");
if (!isElementPresentByXpath("//a/span[contains(text(),'Disclosure Section')]") && !isElementPresentByXpath("//a/span[contains(text(),'Predefined Disclosure Section')]")) {
fail("First disclosure not displayed");
}
waitAndClickByLinkText("Disclosure Section");
Thread.sleep(1000);
waitAndClickByLinkText("Predefined Disclosure Section");
Thread.sleep(1000);
if (isElementPresentByXpath("//div[@id='Demo-Disclosure-Example1']/div[@class='uif-verticalBoxLayout clearfix']/div/div[@data-open='true']")) {
fail("First disclosure did not close");
}
}
protected void testWidgetsDisclosureClosed() throws Exception {
waitAndClickByLinkText("Closed");
WebElement exampleDiv = navigateToExample("Demo-Disclosure-Example2");
WebElement disclosure = findElement(By.cssSelector(".uif-disclosureContent"), exampleDiv);
if (disclosure.isDisplayed()) {
fail("Disclosure did not default closed");
}
waitAndClickByLinkText("Default Closed Section");
Thread.sleep(1000);
if (!disclosure.isDisplayed()) {
fail("Disclosure did not open");
}
}
@Test
public void testWidgetsDisclosureBookmark() throws Exception {
testWidgetsDisclosureDefault();
testWidgetsDisclosureClosed();
driver.close();
passed();
}
@Test
public void testWidgetsDisclosureNav() throws Exception {
testWidgetsDisclosureDefault();
testWidgetsDisclosureClosed();
driver.close();
passed();
}
}
| rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/uif/library/widgets/DemoWidgetsDisclosureAft.java | /**
* Copyright 2005-2013 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.demo.uif.library.widgets;
import org.junit.Test;
import org.kuali.rice.krad.demo.uif.library.DemoLibraryBase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
/**
* @author Kuali Rice Team ([email protected])
*/
public class DemoWidgetsDisclosureAft extends DemoLibraryBase {
/**
* /kr-krad/kradsampleapp?viewId=Demo-Disclosure-View&methodToCall=start
*/
public static final String BOOKMARK_URL = "/kr-krad/kradsampleapp?viewId=Demo-Disclosure-View&methodToCall=start";
@Override
protected String getBookmarkUrl() {
return BOOKMARK_URL;
}
@Override
protected void navigate() throws Exception {
navigateToLibraryDemo("Widgets", "Disclosure");
}
protected void testWidgetsDisclosureDefault() throws Exception {
waitAndClickByLinkText("Default");
WebElement exampleDiv = navigateToExample("Demo-Disclosure-Example1");
//first example
WebElement disclosure1 = findElement(By.id("u100085_disclosureContent"), exampleDiv);
if (!disclosure1.isDisplayed()) {
fail("First disclosure not displayed");
}
waitAndClickByLinkText("Disclosure Section");
Thread.sleep(1000);
if (disclosure1.isDisplayed()) {
fail("First disclosure did not close");
}
//second example
WebElement disclosure2 = findElement(By.id("u100105_disclosureContent"), exampleDiv);
if (!disclosure2.isDisplayed()) {
fail("Second disclosure not displayed");
}
waitAndClickByLinkText("Predefined Disclosure Section");
Thread.sleep(1000);
if (disclosure2.isDisplayed()) {
fail("Second disclosure did not close");
}
}
protected void testWidgetsDisclosureClosed() throws Exception {
waitAndClickByLinkText("Closed");
WebElement exampleDiv = navigateToExample("Demo-Disclosure-Example2");
WebElement disclosure = findElement(By.cssSelector(".uif-disclosureContent"), exampleDiv);
if (disclosure.isDisplayed()) {
fail("Disclosure did not default closed");
}
waitAndClickByLinkText("Default Closed Section");
Thread.sleep(1000);
if (!disclosure.isDisplayed()) {
fail("Disclosure did not open");
}
}
@Test
public void testWidgetsDisclosureBookmark() throws Exception {
testWidgetsDisclosureDefault();
testWidgetsDisclosureClosed();
driver.close();
passed();
}
@Test
public void testWidgetsDisclosureNav() throws Exception {
testWidgetsDisclosureDefault();
testWidgetsDisclosureClosed();
driver.close();
passed();
}
}
| KULRICE-11106 : Update DemoWidgetsDisclosureAft to not use ids Completed
| rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/uif/library/widgets/DemoWidgetsDisclosureAft.java | KULRICE-11106 : Update DemoWidgetsDisclosureAft to not use ids Completed | <ide><path>ice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/uif/library/widgets/DemoWidgetsDisclosureAft.java
<ide>
<ide> protected void testWidgetsDisclosureDefault() throws Exception {
<ide> waitAndClickByLinkText("Default");
<del> WebElement exampleDiv = navigateToExample("Demo-Disclosure-Example1");
<del>
<del> //first example
<del> WebElement disclosure1 = findElement(By.id("u100085_disclosureContent"), exampleDiv);
<del>
<del> if (!disclosure1.isDisplayed()) {
<add> if (!isElementPresentByXpath("//a/span[contains(text(),'Disclosure Section')]") && !isElementPresentByXpath("//a/span[contains(text(),'Predefined Disclosure Section')]")) {
<ide> fail("First disclosure not displayed");
<ide> }
<ide>
<ide> waitAndClickByLinkText("Disclosure Section");
<ide> Thread.sleep(1000);
<del>
<del> if (disclosure1.isDisplayed()) {
<del> fail("First disclosure did not close");
<del> }
<del>
<del> //second example
<del> WebElement disclosure2 = findElement(By.id("u100105_disclosureContent"), exampleDiv);
<del>
<del> if (!disclosure2.isDisplayed()) {
<del> fail("Second disclosure not displayed");
<del> }
<del>
<ide> waitAndClickByLinkText("Predefined Disclosure Section");
<ide> Thread.sleep(1000);
<ide>
<del> if (disclosure2.isDisplayed()) {
<del> fail("Second disclosure did not close");
<add> if (isElementPresentByXpath("//div[@id='Demo-Disclosure-Example1']/div[@class='uif-verticalBoxLayout clearfix']/div/div[@data-open='true']")) {
<add> fail("First disclosure did not close");
<ide> }
<ide> }
<ide>
<ide> public void testWidgetsDisclosureBookmark() throws Exception {
<ide> testWidgetsDisclosureDefault();
<ide> testWidgetsDisclosureClosed();
<del>
<ide> driver.close();
<ide> passed();
<ide> }
<ide> public void testWidgetsDisclosureNav() throws Exception {
<ide> testWidgetsDisclosureDefault();
<ide> testWidgetsDisclosureClosed();
<del>
<ide> driver.close();
<ide> passed();
<ide> } |
|
JavaScript | mit | 9d4a4b35abcd6404efe5ff36eb6cbcc6ddaa1986 | 0 | studentinsights/studentinsights,jhilde/studentinsights,studentinsights/studentinsights,studentinsights/studentinsights,jhilde/studentinsights,jhilde/studentinsights,studentinsights/studentinsights,jhilde/studentinsights | (function() {
window.shared || (window.shared = {});
var dom = window.shared.ReactHelpers.dom;
var createEl = window.shared.ReactHelpers.createEl;
var merge = window.shared.ReactHelpers.merge;
var PropTypes = window.shared.PropTypes;
var HelpBubble = window.shared.HelpBubble;
var styles = {
caption: {
marginRight: 5
},
value: {
fontWeight: 'bold'
},
sparklineContainer: {
paddingLeft: 15,
paddingRight: 15
},
textContainer: {
paddingBottom: 5
},
table: {
border: 1,
borderStyle: 'solid',
borderColor: 'black',
paddingLeft: 5,
paddingRight: 5
},
core: {
backgroundColor: '#b3ffb3'
},
strategic: {
backgroundColor: '#ffffb3'
},
intensive: {
backgroundColor: '#ff9999'
}
};
var AcademicSummary = window.shared.AcademicSummary = React.createClass({
displayName: 'AcademicSummary',
propTypes: {
caption: React.PropTypes.string.isRequired,
value: PropTypes.nullable(React.PropTypes.number.isRequired),
sparkline: React.PropTypes.element.isRequired
},
render: function() {
return dom.div({ className: 'AcademicSummary' },
dom.div({ style: styles.textContainer },
dom.span({ style: styles.caption }, this.props.caption + ':'),
dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value)
),
dom.div({ style: styles.sparklineContainer }, this.props.sparkline)
);
}
});
var SummaryWithoutSparkline = window.shared.SummaryWithoutSparkline = React.createClass({
displayName: 'SummaryWithoutSparkline',
propTypes: {
caption: React.PropTypes.string.isRequired,
value: PropTypes.nullable(React.PropTypes.string.isRequired)
},
getDibelsHelpContent: function(){
return dom.div({},
dom.p({}, dom.b({ style: styles.core }, 'CORE:'), ' Student needs CORE (or basic) support to reach literacy goals.'),
dom.br({}),
dom.p({}, dom.b({ style: styles.strategic }, 'STRATEGIC:'), ' Student needs STRATEGIC (or intermediate-level) support to reach literacy goals.'),
dom.br({}),
dom.p({}, dom.b({ style: styles.intensive }, 'INTENSIVE:'), ' Student needs INTENSIVE (or high-level) support to reach literacy goals.'),
dom.br({}),
dom.h2({}, 'DIBELS LEVELS BY GRADE:'),
dom.table({ style: styles.table },
dom.thead({},
dom.tr({},
dom.th({ style: styles.table, maxWidth: 30 }, 'Assessment'),
dom.th({ style: styles.table, colSpan: 3 }, 'K - Beg'),
dom.th({ style: styles.table, colSpan: 3 }, 'K - Mid'),
dom.th({ style: styles.table, colSpan: 3 }, 'K - End'),
dom.th({ style: styles.table, colSpan: 3 }, '1 - Beg'),
dom.th({ style: styles.table, colSpan: 3 }, '1 - Mid'),
dom.th({ style: styles.table, colSpan: 3 }, '1 - End'),
dom.th({ style: styles.table, colSpan: 3 }, '2 - Beg'),
dom.th({ style: styles.table, colSpan: 3 }, '2 - Mid'),
dom.th({ style: styles.table, colSpan: 3 }, '2 - End'),
dom.th({ style: styles.table, colSpan: 3 }, '3 - Beg'),
dom.th({ style: styles.table, colSpan: 3 }, '3 - Mid'),
dom.th({ style: styles.table, colSpan: 3 }, '3 - End')
),
dom.tr({})
),
dom.tbody({},
dom.tr({},
dom.td({}, 'First Sound Fluency'),
dom.td({ style: styles.core }, '18'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '7'),
dom.td({ style: styles.core }, '44'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '31')
),
dom.tr({},
dom.td({}, 'Letter Naming Fluency'),
dom.td({ style: styles.core }, '22 '),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '10'),
dom.td({ style: styles.core }, '42'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '19'),
dom.td({ style: styles.core }, '52'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '38'),
dom.td({ style: styles.core }, '50'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '36')
),
dom.tr({},
dom.td({}, 'Phoneme Segmentation Fluency'),
dom.td({ colSpan: 3 }, ' '),
dom.td({ style: styles.core }, '27'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '12'),
dom.td({ style: styles.core }, '45'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '30')
),
dom.tr({}),
dom.tr({},
dom.td({}, 'Nonsense Word Fluency-Correct Sounds'),
dom.td({ colSpan: 3 }, ' '),
dom.td({ style: styles.core }, '25'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '15'),
dom.td({ style: styles.core }, '37'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '27'),
dom.td({ style: styles.core }, '33'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '19'),
dom.td({ style: styles.core }, '50'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '30'),
dom.td({ style: styles.core }, '78'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '42'),
dom.td({ style: styles.core }, '62'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '45')
),
dom.tr({},
dom.td({}, 'Nonsense Word Fluency-Whole Words'),
dom.td({ colSpan: 6 }, ' '),
dom.td({ style: styles.core }, '4'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '0'),
dom.td({ style: styles.core }, '4'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '1'),
dom.td({ style: styles.core }, '12'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '5'),
dom.td({ style: styles.core }, '18'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '9'),
dom.td({ style: styles.core }, '18'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '9')
),
dom.tr({}),
dom.tr({},
dom.td({}, 'Developing Reading Fluency'),
dom.td({ colSpan: 12 }, ' '),
dom.td({ style: styles.core }, '30'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '18'),
dom.td({ style: styles.core }, '63'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '36'),
dom.td({ style: styles.core }, '68'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '46'),
dom.td({ style: styles.core }, '84'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '67'),
dom.td({ style: styles.core }, '100'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '82'),
dom.td({ style: styles.core }, '93'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '72'),
dom.td({ style: styles.core }, '108'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '88'),
dom.td({ style: styles.core }, '123'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '100')
),
dom.tr({},
dom.td({}, 'Developing Reading Fluency - Percentage'),
dom.td({ colSpan: 12 }, ' '),
dom.td({ style: styles.core }, '85%'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '73%'),
dom.td({ style: styles.core }, '92%'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '84%'),
dom.td({ style: styles.core }, '93%'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '84%'),
dom.td({ style: styles.core }, '95%'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '91%'),
dom.td({ style: styles.core }, '97%'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '93%'),
dom.td({ style: styles.core }, '96%'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '91%'),
dom.td({ style: styles.core }, '97%'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '93%'),
dom.td({ style: styles.core }, '98%'),
dom.td({ style: styles.strategic }, ' '),
dom.td({ style: styles.intensive }, '95%')
)
)
)
);
},
render: function() {
return dom.div({ className: 'AcademicSummary' },
dom.div({ style: styles.textContainer },
dom.span({ style: styles.caption }, this.props.caption + ':'),
dom.br(),
dom.br(),
dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value),
createEl(HelpBubble, {
title: 'What do DIBELS levels mean?',
teaserText: '(what is this?)',
content: this.getDibelsHelpContent()
})
)
);
}
});
})();
| app/assets/javascripts/student_profile/academic_summary.js | (function() {
window.shared || (window.shared = {});
var dom = window.shared.ReactHelpers.dom;
var createEl = window.shared.ReactHelpers.createEl;
var merge = window.shared.ReactHelpers.merge;
var PropTypes = window.shared.PropTypes;
var styles = {
caption: {
marginRight: 5
},
value: {
fontWeight: 'bold'
},
sparklineContainer: {
paddingLeft: 15,
paddingRight: 15
},
textContainer: {
paddingBottom: 5
}
};
var AcademicSummary = window.shared.AcademicSummary = React.createClass({
displayName: 'AcademicSummary',
propTypes: {
caption: React.PropTypes.string.isRequired,
value: PropTypes.nullable(React.PropTypes.number.isRequired),
sparkline: React.PropTypes.element.isRequired
},
render: function() {
return dom.div({ className: 'AcademicSummary' },
dom.div({ style: styles.textContainer },
dom.span({ style: styles.caption }, this.props.caption + ':'),
dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value)
),
dom.div({ style: styles.sparklineContainer }, this.props.sparkline)
);
}
});
var SummaryWithoutSparkline = window.shared.SummaryWithoutSparkline = React.createClass({
displayName: 'SummaryWithoutSparkline',
propTypes: {
caption: React.PropTypes.string.isRequired,
value: PropTypes.nullable(React.PropTypes.string.isRequired)
},
render: function() {
return dom.div({ className: 'AcademicSummary' },
dom.div({ style: styles.textContainer },
dom.span({ style: styles.caption }, this.props.caption + ':'),
dom.br(),
dom.br(),
dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value)
)
);
}
});
})();
| Add table to dibels info window
| app/assets/javascripts/student_profile/academic_summary.js | Add table to dibels info window | <ide><path>pp/assets/javascripts/student_profile/academic_summary.js
<ide> var createEl = window.shared.ReactHelpers.createEl;
<ide> var merge = window.shared.ReactHelpers.merge;
<ide> var PropTypes = window.shared.PropTypes;
<add> var HelpBubble = window.shared.HelpBubble;
<add>
<ide>
<ide> var styles = {
<ide> caption: {
<ide> },
<ide> textContainer: {
<ide> paddingBottom: 5
<add> },
<add> table: {
<add> border: 1,
<add> borderStyle: 'solid',
<add> borderColor: 'black',
<add> paddingLeft: 5,
<add> paddingRight: 5
<add> },
<add> core: {
<add> backgroundColor: '#b3ffb3'
<add> },
<add> strategic: {
<add> backgroundColor: '#ffffb3'
<add> },
<add> intensive: {
<add> backgroundColor: '#ff9999'
<ide> }
<ide> };
<ide>
<ide> value: PropTypes.nullable(React.PropTypes.string.isRequired)
<ide> },
<ide>
<add> getDibelsHelpContent: function(){
<add> return dom.div({},
<add> dom.p({}, dom.b({ style: styles.core }, 'CORE:'), ' Student needs CORE (or basic) support to reach literacy goals.'),
<add> dom.br({}),
<add> dom.p({}, dom.b({ style: styles.strategic }, 'STRATEGIC:'), ' Student needs STRATEGIC (or intermediate-level) support to reach literacy goals.'),
<add> dom.br({}),
<add> dom.p({}, dom.b({ style: styles.intensive }, 'INTENSIVE:'), ' Student needs INTENSIVE (or high-level) support to reach literacy goals.'),
<add> dom.br({}),
<add> dom.h2({}, 'DIBELS LEVELS BY GRADE:'),
<add> dom.table({ style: styles.table },
<add> dom.thead({},
<add> dom.tr({},
<add> dom.th({ style: styles.table, maxWidth: 30 }, 'Assessment'),
<add> dom.th({ style: styles.table, colSpan: 3 }, 'K - Beg'),
<add> dom.th({ style: styles.table, colSpan: 3 }, 'K - Mid'),
<add> dom.th({ style: styles.table, colSpan: 3 }, 'K - End'),
<add> dom.th({ style: styles.table, colSpan: 3 }, '1 - Beg'),
<add> dom.th({ style: styles.table, colSpan: 3 }, '1 - Mid'),
<add> dom.th({ style: styles.table, colSpan: 3 }, '1 - End'),
<add> dom.th({ style: styles.table, colSpan: 3 }, '2 - Beg'),
<add> dom.th({ style: styles.table, colSpan: 3 }, '2 - Mid'),
<add> dom.th({ style: styles.table, colSpan: 3 }, '2 - End'),
<add> dom.th({ style: styles.table, colSpan: 3 }, '3 - Beg'),
<add> dom.th({ style: styles.table, colSpan: 3 }, '3 - Mid'),
<add> dom.th({ style: styles.table, colSpan: 3 }, '3 - End')
<add> ),
<add> dom.tr({})
<add> ),
<add> dom.tbody({},
<add> dom.tr({},
<add> dom.td({}, 'First Sound Fluency'),
<add> dom.td({ style: styles.core }, '18'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '7'),
<add> dom.td({ style: styles.core }, '44'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '31')
<add> ),
<add> dom.tr({},
<add> dom.td({}, 'Letter Naming Fluency'),
<add> dom.td({ style: styles.core }, '22 '),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '10'),
<add> dom.td({ style: styles.core }, '42'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '19'),
<add> dom.td({ style: styles.core }, '52'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '38'),
<add> dom.td({ style: styles.core }, '50'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '36')
<add> ),
<add> dom.tr({},
<add> dom.td({}, 'Phoneme Segmentation Fluency'),
<add> dom.td({ colSpan: 3 }, ' '),
<add> dom.td({ style: styles.core }, '27'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '12'),
<add> dom.td({ style: styles.core }, '45'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '30')
<add> ),
<add> dom.tr({}),
<add> dom.tr({},
<add> dom.td({}, 'Nonsense Word Fluency-Correct Sounds'),
<add> dom.td({ colSpan: 3 }, ' '),
<add> dom.td({ style: styles.core }, '25'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '15'),
<add> dom.td({ style: styles.core }, '37'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '27'),
<add> dom.td({ style: styles.core }, '33'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '19'),
<add> dom.td({ style: styles.core }, '50'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '30'),
<add> dom.td({ style: styles.core }, '78'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '42'),
<add> dom.td({ style: styles.core }, '62'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '45')
<add> ),
<add> dom.tr({},
<add> dom.td({}, 'Nonsense Word Fluency-Whole Words'),
<add> dom.td({ colSpan: 6 }, ' '),
<add> dom.td({ style: styles.core }, '4'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '0'),
<add> dom.td({ style: styles.core }, '4'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '1'),
<add> dom.td({ style: styles.core }, '12'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '5'),
<add> dom.td({ style: styles.core }, '18'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '9'),
<add> dom.td({ style: styles.core }, '18'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '9')
<add> ),
<add> dom.tr({}),
<add> dom.tr({},
<add> dom.td({}, 'Developing Reading Fluency'),
<add> dom.td({ colSpan: 12 }, ' '),
<add> dom.td({ style: styles.core }, '30'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '18'),
<add> dom.td({ style: styles.core }, '63'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '36'),
<add> dom.td({ style: styles.core }, '68'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '46'),
<add> dom.td({ style: styles.core }, '84'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '67'),
<add> dom.td({ style: styles.core }, '100'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '82'),
<add> dom.td({ style: styles.core }, '93'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '72'),
<add> dom.td({ style: styles.core }, '108'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '88'),
<add> dom.td({ style: styles.core }, '123'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '100')
<add> ),
<add> dom.tr({},
<add> dom.td({}, 'Developing Reading Fluency - Percentage'),
<add> dom.td({ colSpan: 12 }, ' '),
<add> dom.td({ style: styles.core }, '85%'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '73%'),
<add> dom.td({ style: styles.core }, '92%'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '84%'),
<add> dom.td({ style: styles.core }, '93%'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '84%'),
<add> dom.td({ style: styles.core }, '95%'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '91%'),
<add> dom.td({ style: styles.core }, '97%'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '93%'),
<add> dom.td({ style: styles.core }, '96%'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '91%'),
<add> dom.td({ style: styles.core }, '97%'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '93%'),
<add> dom.td({ style: styles.core }, '98%'),
<add> dom.td({ style: styles.strategic }, ' '),
<add> dom.td({ style: styles.intensive }, '95%')
<add> )
<add> )
<add> )
<add> );
<add> },
<add>
<ide> render: function() {
<ide> return dom.div({ className: 'AcademicSummary' },
<ide> dom.div({ style: styles.textContainer },
<ide> dom.span({ style: styles.caption }, this.props.caption + ':'),
<ide> dom.br(),
<ide> dom.br(),
<del> dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value)
<add> dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value),
<add> createEl(HelpBubble, {
<add> title: 'What do DIBELS levels mean?',
<add> teaserText: '(what is this?)',
<add> content: this.getDibelsHelpContent()
<add> })
<ide> )
<ide> );
<ide> } |
|
Java | mit | 43530b31ef9ab9c6c0271dcd648c297cea859f34 | 0 | jenkinsci/sbt-plugin,ziggystar/sbt-plugin,coacoas/sbt-plugin,ziggystar/sbt-plugin,coacoas/sbt-plugin,jenkinsci/sbt-plugin | package org.jvnet.hudson.plugins;
import hudson.CopyOnWrite;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.EnvironmentSpecific;
import hudson.model.JDK;
import hudson.model.Node;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.remoting.Callable;
import hudson.slaves.NodeSpecific;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.tools.DownloadFromUrlInstaller;
import hudson.tools.ToolDescriptor;
import hudson.tools.ToolInstallation;
import hudson.tools.ToolInstaller;
import hudson.tools.ToolProperty;
import hudson.util.ArgumentListBuilder;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* sbt plugin {@link Builder}.
* <p/>
* <p/>
* When the user configures the project and enables this builder,
* {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked and a new
* {@link SbtPluginBuilder} is created. The created instance is persisted to the
* project configuration XML by using XStream, so this allows you to use
* instance fields (like {@link #name}) to remember the configuration.
* <p/>
* <p/>
* When a build is performed, the
* {@link #perform(AbstractBuild, Launcher, BuildListener)} method will be
* invoked.
*
* @author Uzi Landsmann
*/
public class SbtPluginBuilder extends Builder {
public static final Logger LOGGER = Logger.getLogger(SbtPluginBuilder.class
.getName());
private final String name;
private final String jvmFlags;
private final String sbtFlags;
private final String actions;
private String subdirPath;
// Fields in config.jelly must match the parameter names in the
// "DataBoundConstructor"
@DataBoundConstructor
public SbtPluginBuilder(String name, String jvmFlags, String sbtFlags,
String actions, String subdirPath) {
this.name = name;
this.jvmFlags = jvmFlags;
this.sbtFlags = sbtFlags;
this.actions = actions;
this.subdirPath = subdirPath;
}
public String getName() {
return name;
}
public String getJvmFlags() {
return jvmFlags;
}
public String getSbtFlags() {
return sbtFlags;
}
public String getActions() {
return actions;
}
public String getSubdirPath() {
return subdirPath;
}
/**
* Perform the sbt build. Interpret the command arguments and create a
* command line, then run it.
*/
@Override
public boolean perform(AbstractBuild build, Launcher launcher,
BuildListener listener) {
EnvVars env = null;
FilePath workDir = build.getModuleRoot();
try {
ArgumentListBuilder cmdLine = buildCmdLine(build, launcher,
listener);
String[] cmds = cmdLine.toCommandArray();
env = build.getEnvironment(listener);
if (subdirPath != null && subdirPath.length() > 0) {
workDir = new FilePath(workDir, subdirPath);
}
int exitValue = launcher.launch().cmds(cmds).envs(env)
.stdout(listener).pwd(workDir).join();
boolean success = (exitValue == 0);
build.setResult(success ? Result.SUCCESS : Result.FAILURE);
return success;
} catch (IllegalArgumentException e) {
// Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed: "
+ e.getMessage()));
build.setResult(Result.FAILURE);
return false;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed: "
+ e.getMessage()));
build.setResult(Result.FAILURE);
return false;
} catch (InterruptedException e) {
// Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed: "
+ e.getMessage()));
build.setResult(Result.ABORTED);
return false;
}
}
/**
* Create an {@link ArgumentListBuilder} to run the build, given command
* arguments.
*/
private ArgumentListBuilder buildCmdLine(AbstractBuild build,
Launcher launcher, BuildListener listener)
throws IllegalArgumentException, InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
// DescriptorImpl descriptor = (DescriptorImpl) getDescriptor();
EnvVars env = build.getEnvironment(listener);
env.overrideAll(build.getBuildVariables());
SbtInstallation sbt = getSbt();
if (sbt == null) {
throw new IllegalArgumentException("sbt-launch.jar not found");
} else {
sbt = sbt.forNode(Computer.currentComputer().getNode(), listener);
sbt = sbt.forEnvironment(env);
String launcherPath = sbt.getSbtLaunchJar(launcher);
if (launcherPath == null) {
throw new IllegalArgumentException("sbt-launch.jar not found");
}
if (!launcher.isUnix()) {
args.add("cmd.exe", "/C");
}
// java
String javaExePath;
JDK jdk = build.getProject().getJDK();
Computer computer = Computer.currentComputer();
if (computer != null && jdk != null) { // just in case were not in a build
// use node specific installers, etc
jdk = jdk.forNode(computer.getNode(), listener);
}
if (jdk != null) {
javaExePath = jdk.getHome() + "/bin/java";
} else {
javaExePath = "java";
}
args.add(javaExePath);
splitAndAddArgs(jvmFlags, args);
splitAndAddArgs(sbtFlags, args);
args.add("-jar");
args.add(launcherPath);
for (String action : split(actions)) {
args.add(action);
}
}
return args;
}
private SbtInstallation getSbt() {
for (SbtInstallation sbtInstallation : getDescriptor().getInstallations()) {
if (name != null && name.equals(sbtInstallation.getName())) {
return sbtInstallation;
}
}
return null;
}
/**
* Split arguments and add them to the args list
*
* @param argsToSplit the arguments to split
* @param args java/sbt command arguments
*/
private void splitAndAddArgs(String argsToSplit, ArgumentListBuilder args) {
if (StringUtils.isBlank(argsToSplit)) {
return;
}
String[] split = argsToSplit.split(" ");
for (String flag : split) {
args.add(flag);
}
}
/*
* Splits by whitespace except if surrounded by quotes. See
* http://stackoverflow
* .com/questions/366202/regex-for-splitting-a-string-using
* -space-when-not-surrounded-by-single-or-double/366532#366532
*/
private List<String> split(String s) {
List<String> result = new ArrayList<String>();
Matcher matcher = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'")
.matcher(s);
while (matcher.find()) {
if (matcher.group(1) != null)
result.add(matcher.group(1));
else if (matcher.group(2) != null)
result.add(matcher.group(2));
else
result.add(matcher.group());
}
return result;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
/**
* Descriptor for {@link SbtPluginBuilder}. Used as a singleton. The class
* is marked as public so that it can be accessed from views.
* <p/>
* <p/>
* See <tt>SbtPluginBuilder/*.jelly</tt> for the actual HTML fragment for
* the configuration screen.
*/
@Extension
// this marker indicates Hudson that this is an implementation of an
// extension point.
public static final class DescriptorImpl extends
BuildStepDescriptor<Builder> {
// private volatile Jar[] jars = new Jar[0];
@CopyOnWrite
private volatile SbtInstallation[] installations = new SbtInstallation[0];
public DescriptorImpl() {
super(SbtPluginBuilder.class);
load();
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
@Override
public String getDisplayName() {
return "Build using sbt";
}
/*public Jar getJar(String name) {
for (Jar jar : jars) {
if (jar.getName().equals(name)) {
return jar;
}
}
return null;
}*/
/*@Override
public boolean configure(StaplerRequest req, JSONObject formData)
throws FormException {
try {
jars = req.bindJSONToList(Jar.class,
req.getSubmittedForm().get("jar")).toArray(new Jar[0]);
save();
return true;
} catch (ServletException e) {
LOGGER.severe(String.format("Couldn't save jars beacause %s",
e.getMessage()));
LOGGER.severe(String.format("Stacktrace %s", e.getStackTrace()
.toString()));
return false;
}
}*/
/*public Jar[] getJars() {
return jars;
}*/
public SbtInstallation.DescriptorImpl getToolDescriptor() {
return ToolInstallation.all().get(SbtInstallation.DescriptorImpl.class);
}
public SbtInstallation[] getInstallations() {
return installations;
}
public void setInstallations(SbtInstallation... sbtInstallations) {
this.installations = sbtInstallations;
save();
}
}
/**
* Representation of an sbt launcher. Several such launchers can be defined
* in Jenkins properties to choose among when running a project.
*/
/*public static final class Jar implements Serializable {
private static final long serialVersionUID = 1L;
*/
/** The human-friendly name of this launcher */
// private String name;
/**
* The path to the launcher
*/
// private String path;
/*
@DataBoundConstructor
public Jar(String name, String path) {
this.name = name;
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
} */
public static final class SbtInstallation extends ToolInstallation implements
EnvironmentSpecific<SbtInstallation>, NodeSpecific<SbtInstallation>, Serializable {
private static final long serialVersionUID = -2281774135009218882L;
private String sbtLaunchJar;
@DataBoundConstructor
public SbtInstallation(String name, String home, List<? extends ToolProperty<?>> properties) {
super(name, launderHome(home), properties);
}
private static String launderHome(String home) {
if (home.endsWith("/") || home.endsWith("\\")) {
// see https://issues.apache.org/bugzilla/show_bug.cgi?id=26947
// Ant doesn't like the trailing slash, especially on Windows
return home.substring(0, home.length() - 1);
} else {
return home;
}
}
public String getSbtLaunchJar(Launcher launcher) throws IOException, InterruptedException {
return launcher.getChannel().call(new Callable<String, IOException>() {
public String call() throws IOException {
File sbtLaunchJarFile = getSbtLaunchJarFile();
if(sbtLaunchJarFile.exists())
return sbtLaunchJarFile.getPath();
return getHome();
}
});
}
private File getSbtLaunchJarFile() {
String home = Util.replaceMacro(getHome(), EnvVars.masterEnvVars);
return new File(home, "bin/sbt-launch.jar");
}
public SbtInstallation forEnvironment(EnvVars environment) {
return new SbtInstallation(getName(), environment.expand(getHome()), getProperties().toList());
}
public SbtInstallation forNode(Node node, TaskListener log) throws IOException, InterruptedException {
return new SbtInstallation(getName(), translateFor(node, log), getProperties().toList());
}
@Extension
public static class DescriptorImpl extends ToolDescriptor<SbtInstallation> {
@Override
public SbtInstallation[] getInstallations() {
return Jenkins.getInstance().getDescriptorByType(SbtPluginBuilder.DescriptorImpl.class)
.getInstallations();
}
@Override
public void setInstallations(SbtInstallation... installations) {
Jenkins.getInstance().getDescriptorByType(SbtPluginBuilder.DescriptorImpl.class)
.setInstallations(installations);
}
@Override
public List<? extends ToolInstaller> getDefaultInstallers() {
return Collections.singletonList(new SbtInstaller(null));
}
@Override
public String getDisplayName() {
return "Sbt";
}
/**
* Checks if the sbt-launch.jar is exist.
*/
public FormValidation doCheckHome(@QueryParameter File value) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return FormValidation.ok();
}
// allow empty input
if(value.getPath().equals(""))
return FormValidation.ok();
if (!value.exists() || !value.isFile()) {
return FormValidation.error("sbt-launch.jar not found");
}
return FormValidation.ok();
}
}
}
/**
* Automatic Sbt installer from scala-sbt.org
*/
public static class SbtInstaller extends DownloadFromUrlInstaller {
@DataBoundConstructor
public SbtInstaller(String id) {
super(id);
}
@Extension
public static final class DescriptorImpl extends DownloadFromUrlInstaller.DescriptorImpl<SbtInstaller> {
@Override
public String getDisplayName() {
return "Install from scala-sbt.org";
}
@Override
public boolean isApplicable(Class<? extends ToolInstallation> toolType) {
return toolType == SbtInstallation.class;
}
}
}
}
| src/main/java/org/jvnet/hudson/plugins/SbtPluginBuilder.java | package org.jvnet.hudson.plugins;
import hudson.CopyOnWrite;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.EnvironmentSpecific;
import hudson.model.JDK;
import hudson.model.Node;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.remoting.Callable;
import hudson.slaves.NodeSpecific;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.tools.DownloadFromUrlInstaller;
import hudson.tools.ToolDescriptor;
import hudson.tools.ToolInstallation;
import hudson.tools.ToolInstaller;
import hudson.tools.ToolProperty;
import hudson.util.ArgumentListBuilder;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* sbt plugin {@link Builder}.
* <p/>
* <p/>
* When the user configures the project and enables this builder,
* {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked and a new
* {@link SbtPluginBuilder} is created. The created instance is persisted to the
* project configuration XML by using XStream, so this allows you to use
* instance fields (like {@link #name}) to remember the configuration.
* <p/>
* <p/>
* When a build is performed, the
* {@link #perform(AbstractBuild, Launcher, BuildListener)} method will be
* invoked.
*
* @author Uzi Landsmann
*/
public class SbtPluginBuilder extends Builder {
public static final Logger LOGGER = Logger.getLogger(SbtPluginBuilder.class
.getName());
private final String name;
private final String jvmFlags;
private final String sbtFlags;
private final String actions;
private String subdirPath;
// Fields in config.jelly must match the parameter names in the
// "DataBoundConstructor"
@DataBoundConstructor
public SbtPluginBuilder(String name, String jvmFlags, String sbtFlags,
String actions, String subdirPath) {
this.name = name;
this.jvmFlags = jvmFlags;
this.sbtFlags = sbtFlags;
this.actions = actions;
this.subdirPath = subdirPath;
}
public String getName() {
return name;
}
public String getJvmFlags() {
return jvmFlags;
}
public String getSbtFlags() {
return sbtFlags;
}
public String getActions() {
return actions;
}
public String getSubdirPath() {
return subdirPath;
}
/**
* Perform the sbt build. Interpret the command arguments and create a
* command line, then run it.
*/
@Override
public boolean perform(AbstractBuild build, Launcher launcher,
BuildListener listener) {
EnvVars env = null;
FilePath workDir = build.getModuleRoot();
try {
ArgumentListBuilder cmdLine = buildCmdLine(build, launcher,
listener);
String[] cmds = cmdLine.toCommandArray();
env = build.getEnvironment(listener);
if (subdirPath != null && subdirPath.length() > 0) {
workDir = new FilePath(workDir, subdirPath);
}
int exitValue = launcher.launch().cmds(cmds).envs(env)
.stdout(listener).pwd(workDir).join();
boolean success = (exitValue == 0);
build.setResult(success ? Result.SUCCESS : Result.FAILURE);
return success;
} catch (IllegalArgumentException e) {
// Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed: "
+ e.getMessage()));
build.setResult(Result.FAILURE);
return false;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed: "
+ e.getMessage()));
build.setResult(Result.FAILURE);
return false;
} catch (InterruptedException e) {
// Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed: "
+ e.getMessage()));
build.setResult(Result.ABORTED);
return false;
}
}
/**
* Create an {@link ArgumentListBuilder} to run the build, given command
* arguments.
*/
private ArgumentListBuilder buildCmdLine(AbstractBuild build,
Launcher launcher, BuildListener listener)
throws IllegalArgumentException, InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
// DescriptorImpl descriptor = (DescriptorImpl) getDescriptor();
EnvVars env = build.getEnvironment(listener);
env.overrideAll(build.getBuildVariables());
SbtInstallation sbt = getSbt();
if (sbt == null) {
throw new IllegalArgumentException("sbt-launch.jar not found");
} else {
sbt = sbt.forNode(Computer.currentComputer().getNode(), listener);
sbt = sbt.forEnvironment(env);
String launcherPath = sbt.getSbtLaunchJar(launcher);
if (launcherPath == null) {
throw new IllegalArgumentException("sbt-launch.jar not found");
}
if (!launcher.isUnix()) {
args.add("cmd.exe", "/C");
}
// java
String javaExePath;
JDK jdk = build.getProject().getJDK();
Computer computer = Computer.currentComputer();
if (computer != null && jdk != null) { // just in case were not in a build
// use node specific installers, etc
jdk = jdk.forNode(computer.getNode(), listener);
}
if (jdk != null) {
javaExePath = new File(jdk.getBinDir()
+ "/java").getAbsolutePath();
} else {
javaExePath = "java";
}
args.add(javaExePath);
splitAndAddArgs(jvmFlags, args);
splitAndAddArgs(sbtFlags, args);
args.add("-jar");
args.add(launcherPath);
for (String action : split(actions)) {
args.add(action);
}
}
return args;
}
private SbtInstallation getSbt() {
for (SbtInstallation sbtInstallation : getDescriptor().getInstallations()) {
if (name != null && name.equals(sbtInstallation.getName())) {
return sbtInstallation;
}
}
return null;
}
/**
* Split arguments and add them to the args list
*
* @param argsToSplit the arguments to split
* @param args java/sbt command arguments
*/
private void splitAndAddArgs(String argsToSplit, ArgumentListBuilder args) {
if (StringUtils.isBlank(argsToSplit)) {
return;
}
String[] split = argsToSplit.split(" ");
for (String flag : split) {
args.add(flag);
}
}
/*
* Splits by whitespace except if surrounded by quotes. See
* http://stackoverflow
* .com/questions/366202/regex-for-splitting-a-string-using
* -space-when-not-surrounded-by-single-or-double/366532#366532
*/
private List<String> split(String s) {
List<String> result = new ArrayList<String>();
Matcher matcher = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'")
.matcher(s);
while (matcher.find()) {
if (matcher.group(1) != null)
result.add(matcher.group(1));
else if (matcher.group(2) != null)
result.add(matcher.group(2));
else
result.add(matcher.group());
}
return result;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
/**
* Descriptor for {@link SbtPluginBuilder}. Used as a singleton. The class
* is marked as public so that it can be accessed from views.
* <p/>
* <p/>
* See <tt>SbtPluginBuilder/*.jelly</tt> for the actual HTML fragment for
* the configuration screen.
*/
@Extension
// this marker indicates Hudson that this is an implementation of an
// extension point.
public static final class DescriptorImpl extends
BuildStepDescriptor<Builder> {
// private volatile Jar[] jars = new Jar[0];
@CopyOnWrite
private volatile SbtInstallation[] installations = new SbtInstallation[0];
public DescriptorImpl() {
super(SbtPluginBuilder.class);
load();
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
@Override
public String getDisplayName() {
return "Build using sbt";
}
/*public Jar getJar(String name) {
for (Jar jar : jars) {
if (jar.getName().equals(name)) {
return jar;
}
}
return null;
}*/
/*@Override
public boolean configure(StaplerRequest req, JSONObject formData)
throws FormException {
try {
jars = req.bindJSONToList(Jar.class,
req.getSubmittedForm().get("jar")).toArray(new Jar[0]);
save();
return true;
} catch (ServletException e) {
LOGGER.severe(String.format("Couldn't save jars beacause %s",
e.getMessage()));
LOGGER.severe(String.format("Stacktrace %s", e.getStackTrace()
.toString()));
return false;
}
}*/
/*public Jar[] getJars() {
return jars;
}*/
public SbtInstallation.DescriptorImpl getToolDescriptor() {
return ToolInstallation.all().get(SbtInstallation.DescriptorImpl.class);
}
public SbtInstallation[] getInstallations() {
return installations;
}
public void setInstallations(SbtInstallation... sbtInstallations) {
this.installations = sbtInstallations;
save();
}
}
/**
* Representation of an sbt launcher. Several such launchers can be defined
* in Jenkins properties to choose among when running a project.
*/
/*public static final class Jar implements Serializable {
private static final long serialVersionUID = 1L;
*/
/** The human-friendly name of this launcher */
// private String name;
/**
* The path to the launcher
*/
// private String path;
/*
@DataBoundConstructor
public Jar(String name, String path) {
this.name = name;
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
} */
public static final class SbtInstallation extends ToolInstallation implements
EnvironmentSpecific<SbtInstallation>, NodeSpecific<SbtInstallation>, Serializable {
private static final long serialVersionUID = -2281774135009218882L;
private String sbtLaunchJar;
@DataBoundConstructor
public SbtInstallation(String name, String home, List<? extends ToolProperty<?>> properties) {
super(name, launderHome(home), properties);
}
private static String launderHome(String home) {
if (home.endsWith("/") || home.endsWith("\\")) {
// see https://issues.apache.org/bugzilla/show_bug.cgi?id=26947
// Ant doesn't like the trailing slash, especially on Windows
return home.substring(0, home.length() - 1);
} else {
return home;
}
}
public String getSbtLaunchJar(Launcher launcher) throws IOException, InterruptedException {
return launcher.getChannel().call(new Callable<String, IOException>() {
public String call() throws IOException {
File sbtLaunchJarFile = getSbtLaunchJarFile();
if(sbtLaunchJarFile.exists())
return sbtLaunchJarFile.getPath();
return getHome();
}
});
}
private File getSbtLaunchJarFile() {
String home = Util.replaceMacro(getHome(), EnvVars.masterEnvVars);
return new File(home, "bin/sbt-launch.jar");
}
public SbtInstallation forEnvironment(EnvVars environment) {
return new SbtInstallation(getName(), environment.expand(getHome()), getProperties().toList());
}
public SbtInstallation forNode(Node node, TaskListener log) throws IOException, InterruptedException {
return new SbtInstallation(getName(), translateFor(node, log), getProperties().toList());
}
@Extension
public static class DescriptorImpl extends ToolDescriptor<SbtInstallation> {
@Override
public SbtInstallation[] getInstallations() {
return Jenkins.getInstance().getDescriptorByType(SbtPluginBuilder.DescriptorImpl.class)
.getInstallations();
}
@Override
public void setInstallations(SbtInstallation... installations) {
Jenkins.getInstance().getDescriptorByType(SbtPluginBuilder.DescriptorImpl.class)
.setInstallations(installations);
}
@Override
public List<? extends ToolInstaller> getDefaultInstallers() {
return Collections.singletonList(new SbtInstaller(null));
}
@Override
public String getDisplayName() {
return "Sbt";
}
/**
* Checks if the sbt-launch.jar is exist.
*/
public FormValidation doCheckHome(@QueryParameter File value) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return FormValidation.ok();
}
// allow empty input
if(value.getPath().equals(""))
return FormValidation.ok();
if (!value.exists() || !value.isFile()) {
return FormValidation.error("sbt-launch.jar not found");
}
return FormValidation.ok();
}
}
}
/**
* Automatic Sbt installer from scala-sbt.org
*/
public static class SbtInstaller extends DownloadFromUrlInstaller {
@DataBoundConstructor
public SbtInstaller(String id) {
super(id);
}
@Extension
public static final class DescriptorImpl extends DownloadFromUrlInstaller.DescriptorImpl<SbtInstaller> {
@Override
public String getDisplayName() {
return "Install from scala-sbt.org";
}
@Override
public boolean isApplicable(Class<? extends ToolInstallation> toolType) {
return toolType == SbtInstallation.class;
}
}
}
}
| fix java path
| src/main/java/org/jvnet/hudson/plugins/SbtPluginBuilder.java | fix java path | <ide><path>rc/main/java/org/jvnet/hudson/plugins/SbtPluginBuilder.java
<ide> }
<ide>
<ide> if (jdk != null) {
<del> javaExePath = new File(jdk.getBinDir()
<del> + "/java").getAbsolutePath();
<add> javaExePath = jdk.getHome() + "/bin/java";
<ide> } else {
<ide> javaExePath = "java";
<ide> } |
|
Java | apache-2.0 | fc9d80beff26e4570d2c1c11237bb678dc13350b | 0 | HanSolo/dotmatrix | /*
* Copyright (c) 2017 by Gerrit Grunwald
*
* 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 eu.hansolo.fx.dotmatrix;
import javafx.beans.DefaultProperty;
import javafx.beans.InvalidationListener;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* User: hansolo
* Date: 19.03.17
* Time: 04:39
*/
@DefaultProperty("children")
public class DotMatrix extends Region {
public enum DotShape { ROUND, SQUARE, ROUNDED_RECT }
public static final double DEFAULT_SPACER_SIZE_FACTOR = 0.05;
private static final int RED_MASK = 255 << 16;
private static final int GREEN_MASK = 255 << 8;
private static final int BLUE_MASK = 255;
private static final int ALPHA_MASK = 255 << 24;
private static final double ALPHA_FACTOR = 1.0 / 255.0;
private double preferredWidth;
private double preferredHeight;
private double width;
private double height;
private Canvas canvas;
private GraphicsContext ctx;
private StackPane pane;
private int dotOnColor;
private int dotOffColor;
private DotShape dotShape;
private int cols;
private int rows;
private int[][] matrix;
private MatrixFont matrixFont;
private int characterWidth;
private int characterHeight;
private int characterWidthMinusOne;
private double dotSize;
private double dotWidth;
private double dotHeight;
private double spacer;
private boolean useSpacer;
private boolean squareDots;
private double spacerSizeFactor;
private double dotSizeMinusDoubleSpacer;
private double dotWidthMinusDoubleSpacer;
private double dotHeightMinusDoubleSpacer;
private InvalidationListener sizeListener;
private EventHandler<MouseEvent> clickHandler;
private CopyOnWriteArrayList<DotMatrixEventListener> listeners;
// ******************** Constructors **************************************
public DotMatrix() {
this(250, 250, 32, 32, Color.rgb(255, 55, 0), Color.rgb(51, 51, 51, 0.5), DotShape.SQUARE, MatrixFont8x8.INSTANCE);
}
public DotMatrix(final int COLS, final int ROWS) {
this(250, 250, COLS, ROWS, Color.rgb(255, 55, 0), Color.rgb(51, 51, 51, 0.5), DotShape.SQUARE, MatrixFont8x8.INSTANCE);
}
public DotMatrix(final int COLS, final int ROWS, final Color DOT_ON_COLOR) {
this(250, 250, COLS, ROWS, DOT_ON_COLOR, Color.rgb(51, 51, 51, 0.5), DotShape.SQUARE, MatrixFont8x8.INSTANCE);
}
public DotMatrix(final double PREFERRED_WIDTH, final double PREFERRED_HEIGHT, final int COLS, final int ROWS, final Color DOT_ON_COLOR, final Color DOT_OFF_COLOR, final DotShape DOT_SHAPE, final MatrixFont FONT) {
preferredWidth = PREFERRED_WIDTH;
preferredHeight = PREFERRED_HEIGHT;
dotOnColor = convertToInt(DOT_ON_COLOR);
dotOffColor = convertToInt(DOT_OFF_COLOR);
dotShape = DOT_SHAPE;
cols = COLS;
rows = ROWS;
matrix = new int[cols][rows];
matrixFont = FONT;
characterWidth = matrixFont.getCharacterWidth();
characterHeight = matrixFont.getCharacterHeight();
characterWidthMinusOne = characterWidth - 1;
useSpacer = true;
squareDots = true;
spacerSizeFactor = DEFAULT_SPACER_SIZE_FACTOR;
sizeListener = o -> resize();
clickHandler = e -> checkForClick(e);
listeners = new CopyOnWriteArrayList<>();
initGraphics();
registerListeners();
}
// ******************** Initialization ************************************
private void initGraphics() {
// prefill matrix with dotOffColor
for (int y = 0 ; y < rows ; y++) {
for (int x = 0 ; x < cols ; x++) {
matrix[x][y] = dotOffColor;
}
}
if (Double.compare(getPrefWidth(), 0.0) <= 0 || Double.compare(getPrefHeight(), 0.0) <= 0 ||
Double.compare(getWidth(), 0.0) <= 0 || Double.compare(getHeight(), 0.0) <= 0) {
if (getPrefWidth() > 0 && getPrefHeight() > 0) {
setPrefSize(getPrefWidth(), getPrefHeight());
} else {
setPrefSize(preferredWidth, preferredHeight);
}
}
canvas = new Canvas(preferredWidth, preferredHeight);
ctx = canvas.getGraphicsContext2D();
pane = new StackPane(canvas);
getChildren().setAll(pane);
}
private void registerListeners() {
widthProperty().addListener(sizeListener);
heightProperty().addListener(sizeListener);
canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, clickHandler);
}
// ******************** Methods *******************************************
@Override public ObservableList<Node> getChildren() { return super.getChildren(); }
public void setColsAndRows(final int COLS, final int ROWS) {
cols = COLS;
rows = ROWS;
matrix = new int[cols][rows];
initGraphics();
resize();
}
public Color getDotOnColor() { return convertToColor(dotOnColor); }
public void setDotOnColor(final Color COLOR) {
dotOnColor = convertToInt(COLOR);
drawMatrix();
}
public Color getDotOffColor() { return convertToColor(dotOffColor); }
public void setDotOffColor(final Color COLOR) {
dotOffColor = convertToInt(COLOR);
for (int y = 0 ; y < rows ; y++) {
for (int x = 0 ; x < cols ; x++) {
matrix[x][y] = dotOffColor;
}
}
drawMatrix();
}
public DotShape getDotShape() { return dotShape; }
public void setDotShape(final DotShape SHAPE) {
dotShape = SHAPE;
drawMatrix();
}
public MatrixFont getMatrixFont() { return matrixFont; }
public void setMatrixFont(final MatrixFont FONT) {
matrixFont = FONT;
characterWidth = matrixFont.getCharacterWidth();
characterHeight = matrixFont.getCharacterHeight();
characterWidthMinusOne = characterWidth - 1;
drawMatrix();
}
public boolean isUsingSpacer() { return useSpacer; }
public void setUseSpacer(final boolean USE) {
useSpacer = USE;
resize();
}
public boolean isSquareDots() { return squareDots; }
public void setSquareDots(final boolean SQUARE) {
squareDots = SQUARE;
resize();
}
public double getSpacerSizeFactor() { return spacerSizeFactor; }
public void setSpacerSizeFactor(final double FACTOR) {
spacerSizeFactor = clamp(0.0, 0.2, FACTOR);
spacer = useSpacer ? dotSize * spacerSizeFactor : 0;
dotSizeMinusDoubleSpacer = dotSize - spacer * 2;
drawMatrix();
}
public void setPixel(final int X, final int Y, final boolean VALUE) { setPixel(X, Y, VALUE ? dotOnColor : dotOffColor); }
public void setPixel(final int X, final int Y, final Color COLOR) { setPixel(X, Y, convertToInt(COLOR)); }
public void setPixel(final int X, final int Y, final int COLOR_VALUE) {
if (X >= cols || X < 0) return;
if (Y >= rows || Y < 0) return;
matrix[X][Y] = COLOR_VALUE;
}
public void setPixelWithRedraw(final int X, final int Y, final boolean ON) {
setPixel(X, Y, ON ? dotOnColor : dotOffColor);
drawMatrix();
}
public void setPixelWithRedraw(final int X, final int Y, final int COLOR_VALUE) {
setPixel(X, Y, COLOR_VALUE);
drawMatrix();
}
public void setCharAt(final char CHAR, final int X, final int Y) {
setCharAt(CHAR, X, Y, dotOnColor);
}
public void setCharAt(final char CHAR, final int X, final int Y, final int COLOR_VALUE) {
int[] c = matrixFont.getCharacter(CHAR);
for (int x = 0; x < characterWidth; x++) {
for (int y = 0; y < characterHeight; y++) {
setPixel(x + X, y + Y, getBitAt(characterWidthMinusOne - x, y, c) == 0 ? dotOffColor : COLOR_VALUE);
}
}
drawMatrix();
}
public void setCharAtWithBackground(final char CHAR, final int X, final int Y) {
setCharAtWithBackground(CHAR, X, Y, dotOnColor);
}
public void setCharAtWithBackground(final char CHAR, final int X, final int Y, final int COLOR_VALUE) {
int[] c = matrixFont.getCharacter(CHAR);
for (int x = 0; x < characterWidth; x++) {
for (int y = 0; y < characterHeight; y++) {
if (getBitAt(characterWidthMinusOne - x, y, c) == 0) continue;
setPixel(x + X, y + Y, COLOR_VALUE);
}
}
drawMatrix();
}
public double getDotSize() { return dotSize; }
public double getDotWidth() { return dotWidth; }
public double getDotHeight() { return dotHeight; }
public double getMatrixWidth() { return canvas.getWidth(); }
public double getMatrixHeight() { return canvas.getHeight(); }
public Bounds getMatrixLayoutBounds() { return canvas.getLayoutBounds(); }
public Bounds getMatrixBoundsInParent() { return canvas.getBoundsInParent(); }
public Bounds getMatrixBoundsInLocal() { return canvas.getBoundsInLocal(); }
public int getCols() { return cols; }
public int getRows() { return rows; }
public int[][] getMatrix() { return matrix; }
public static Color convertToColor(final int COLOR_VALUE) {
return Color.rgb((COLOR_VALUE & RED_MASK) >> 16, (COLOR_VALUE & GREEN_MASK) >> 8, (COLOR_VALUE & BLUE_MASK), ALPHA_FACTOR * ((COLOR_VALUE & ALPHA_MASK) >>> 24));
}
public static int convertToInt(final Color COLOR) {
return convertToInt((float) COLOR.getRed(), (float) COLOR.getGreen(), (float) COLOR.getBlue(), (float) COLOR.getOpacity());
}
public static int convertToInt(final float RED, final float GREEN, final float BLUE, final float ALPHA) {
int red = Math.round(255 * RED);
int green = Math.round(255 * GREEN);
int blue = Math.round(255 * BLUE);
int alpha = Math.round(255 * ALPHA);
return (alpha << 24) | (red << 16) | (green << 8) | blue;
}
public static int getBitAt(final int X, final int Y, final int[] BYTE_ARRAY) { return (BYTE_ARRAY[Y] >> X) & 1; }
public static boolean getBitAtBoolean(final int X, final int Y, final int[] BYTE_ARRAY) { return ((BYTE_ARRAY[Y] >> X) & 1) == 1; }
public int getColorValueAt(final int X, final int Y) { return matrix[X][Y]; }
public Color getColorAt(final int X, final int Y) { return convertToColor(matrix[X][Y]); }
public void shiftLeft() {
int[] firstColumn = new int[rows];
for (int y = 0 ; y < rows ; y++) { firstColumn[y] = matrix[0][y]; }
for (int y = 0 ; y < rows ; y++) {
for (int x = 1 ; x < cols ; x++) {
matrix[x - 1][y] = matrix[x][y];
}
}
for (int y = 0 ; y < rows ; y++) { matrix[cols - 1][y] = firstColumn[y]; }
drawMatrix();
}
public void shiftRight() {
int[] lastColumn = new int[rows];
for (int y = 0 ; y < rows ; y++) { lastColumn[y] = matrix[cols - 1][y]; }
for (int y = 0 ; y < rows ; y++) {
for (int x = cols - 2 ; x >= 0 ; x--) {
matrix[x + 1][y] = matrix[x][y];
}
}
for (int y = 0 ; y < rows ; y++) { matrix[0][y] = lastColumn[y]; }
drawMatrix();
}
public void shiftUp() {
int[] firstRow = new int[cols];
for (int x = 0 ; x < cols ; x++) { firstRow[x] = matrix[x][0]; }
for (int y = 1 ; y < rows ; y++) {
for (int x = 0 ; x < cols ; x++) {
matrix[x][y - 1] = matrix[x][y];
}
}
for (int x = 0 ; x < cols ; x++) { matrix[x][rows - 1] = firstRow[x]; }
drawMatrix();
}
public void shiftDown() {
int[] lastRow = new int[cols];
for (int x = 0 ; x < cols ; x++) { lastRow[x] = matrix[x][rows - 1]; }
for (int y = rows - 2 ; y >= 0 ; y--) {
for (int x = 0 ; x < cols ; x++) {
matrix[x][y + 1] = matrix[x][y];
}
}
for (int x = 0 ; x < cols ; x++) { matrix[x][0] = lastRow[x]; }
drawMatrix();
}
public void setAllDotsOn() {
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
setPixel(x, y, true);
}
}
drawMatrix();
}
public void setAllDotsOff() {
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
setPixel(x, y, false);
}
}
drawMatrix();
}
public static final double clamp(final double MIN, final double MAX, final double VALUE) {
if (Double.compare(VALUE, MIN) < 0) return MIN;
if (Double.compare(VALUE, MAX) > 0) return MAX;
return VALUE;
}
public void drawMatrix() {
ctx.clearRect(0, 0, width, height);
switch(dotShape) {
case ROUNDED_RECT:
CtxBounds bounds = new CtxBounds(dotWidthMinusDoubleSpacer, dotHeightMinusDoubleSpacer);
CtxCornerRadii cornerRadii = new CtxCornerRadii(dotSize * 0.125);
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
ctx.setFill(convertToColor(matrix[x][y]));
bounds.setX(x * dotWidth + spacer);
bounds.setY(y * dotHeight + spacer);
drawRoundedRect(ctx, bounds, cornerRadii);
ctx.fill();
}
}
break;
case ROUND:
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
ctx.setFill(convertToColor(matrix[x][y]));
ctx.fillOval(x * dotWidth + spacer, y * dotHeight + spacer, dotWidthMinusDoubleSpacer, dotHeightMinusDoubleSpacer);
}
}
break;
case SQUARE:
default :
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
ctx.setFill(convertToColor(matrix[x][y]));
ctx.fillRect(x * dotWidth + spacer, y * dotHeight + spacer, dotWidthMinusDoubleSpacer, dotHeightMinusDoubleSpacer);
}
}
break;
}
}
public void setOnDotMatrixEvent(final DotMatrixEventListener LISTENER) { addDotMatrixEventListener(LISTENER); }
public void addDotMatrixEventListener(final DotMatrixEventListener LISTENER) { if (!listeners.contains(LISTENER)) listeners.add(LISTENER); }
public void removeDotMatrixEventListener(final DotMatrixEventListener LISTENER) { if (listeners.contains(LISTENER)) listeners.remove(LISTENER); }
public void removeAllDotMatrixEventListeners() { listeners.clear(); }
public void fireDotMatrixEvent(final DotMatrixEvent EVENT) {
for (DotMatrixEventListener listener : listeners) { listener.onDotMatrixEvent(EVENT); }
}
@Override protected double computePrefWidth(final double HEIGHT) { return super.computePrefWidth(HEIGHT); }
@Override protected double computePrefHeight(final double WIDTH) { return super.computePrefHeight(WIDTH); }
public void dispose() {
listeners.clear();
widthProperty().removeListener(sizeListener);
heightProperty().removeListener(sizeListener);
canvas.removeEventHandler(MouseEvent.MOUSE_PRESSED, clickHandler);
}
private long getRed(final long COLOR_VALUE) { return (COLOR_VALUE & RED_MASK) >> 16; }
private long getGreen(final long COLOR_VALUE) { return (COLOR_VALUE & GREEN_MASK) >> 8; }
private long getBlue(final long COLOR_VALUE) { return (COLOR_VALUE & BLUE_MASK); }
private long getAlpha(final long COLOR_VALUE) { return (COLOR_VALUE & ALPHA_MASK) >>> 24; }
private void checkForClick(final MouseEvent EVT) {
double spacerPlusPixelWidthMinusDoubleSpacer = spacer + dotWidthMinusDoubleSpacer;
double spacerPlusPixelHeightMinusDoubleSpacer = spacer + dotHeightMinusDoubleSpacer;
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
if (isInRectangle(EVT.getX(), EVT.getY(), x * dotWidth + spacer, y * dotHeight + spacer, x * dotWidth + spacerPlusPixelWidthMinusDoubleSpacer, y * dotHeight + spacerPlusPixelHeightMinusDoubleSpacer)) {
fireDotMatrixEvent(new DotMatrixEvent(x, y, EVT.getScreenX(), EVT.getScreenY()));
break;
}
}
}
}
private static void drawRoundedRect(final GraphicsContext CTX, final CtxBounds BOUNDS, final CtxCornerRadii RADII) {
double x = BOUNDS.getX();
double y = BOUNDS.getY();
double width = BOUNDS.getWidth();
double height = BOUNDS.getHeight();
double xPlusWidth = x + width;
double yPlusHeight = y + height;
CTX.beginPath();
CTX.moveTo(x + RADII.getTopRight(), y);
CTX.lineTo(xPlusWidth - RADII.getTopRight(), y);
CTX.quadraticCurveTo(xPlusWidth, y, xPlusWidth, y + RADII.getTopRight());
CTX.lineTo(xPlusWidth, yPlusHeight - RADII.getBottomRight());
CTX.quadraticCurveTo(xPlusWidth, yPlusHeight, xPlusWidth - RADII.getBottomRight(), yPlusHeight);
CTX.lineTo(x + RADII.getBottomLeft(), yPlusHeight);
CTX.quadraticCurveTo(x, yPlusHeight, x, yPlusHeight - RADII.getBottomLeft());
CTX.lineTo(x, y + RADII.getTopRight());
CTX.quadraticCurveTo(x, y, x + RADII.getTopRight(), y);
CTX.closePath();
}
private static boolean isInRectangle(final double X, final double Y,
final double MIN_X, final double MIN_Y,
final double MAX_X, final double MAX_Y) {
return (Double.compare(X, MIN_X) >= 0 &&
Double.compare(X, MAX_X) <= 0 &&
Double.compare(Y, MIN_Y) >= 0 &&
Double.compare(Y, MAX_Y) <= 0);
}
// ******************** Resizing ******************************************
private void resize() {
width = getWidth() - getInsets().getLeft() - getInsets().getRight();
height = getHeight() - getInsets().getTop() - getInsets().getBottom();
dotSize = (width / cols) < (height / rows) ? (width / cols) : (height / rows);
dotWidth = (width / cols);
dotHeight = (height / rows);
spacer = useSpacer ? dotSize * getSpacerSizeFactor() : 0;
dotSizeMinusDoubleSpacer = dotSize - spacer * 2;
dotWidthMinusDoubleSpacer = dotWidth - spacer * 2;
dotHeightMinusDoubleSpacer = dotHeight - spacer * 2;
if (width > 0 && height > 0) {
pane.setMaxSize(width, height);
pane.setPrefSize(width, height);
pane.relocate((getWidth() - width) * 0.5, (getHeight() - height) * 0.5);
if (squareDots) {
dotWidth = dotSize;
dotHeight = dotSize;
dotWidthMinusDoubleSpacer = dotSizeMinusDoubleSpacer;
dotHeightMinusDoubleSpacer = dotSizeMinusDoubleSpacer;
}
canvas.setWidth(cols * dotWidth);
canvas.setHeight(rows * dotHeight);
drawMatrix();
}
}
}
| src/main/java/eu/hansolo/fx/dotmatrix/DotMatrix.java | /*
* Copyright (c) 2017 by Gerrit Grunwald
*
* 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 eu.hansolo.fx.dotmatrix;
import javafx.beans.DefaultProperty;
import javafx.beans.InvalidationListener;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* User: hansolo
* Date: 19.03.17
* Time: 04:39
*/
@DefaultProperty("children")
public class DotMatrix extends Region {
public enum DotShape { ROUND, SQUARE, ROUNDED_RECT }
public static final double DEFAULT_SPACER_SIZE_FACTOR = 0.05;
private static final int RED_MASK = 255 << 16;
private static final int GREEN_MASK = 255 << 8;
private static final int BLUE_MASK = 255;
private static final int ALPHA_MASK = 255 << 24;
private static final double ALPHA_FACTOR = 1.0 / 255.0;
private double preferredWidth;
private double preferredHeight;
private double width;
private double height;
private Canvas canvas;
private GraphicsContext ctx;
private StackPane pane;
private int dotOnColor;
private int dotOffColor;
private DotShape dotShape;
private int cols;
private int rows;
private int[][] matrix;
private MatrixFont matrixFont;
private int characterWidth;
private int characterHeight;
private int characterWidthMinusOne;
private double dotSize;
private double dotWidth;
private double dotHeight;
private double spacer;
private boolean useSpacer;
private boolean squareDots;
private double spacerSizeFactor;
private double dotSizeMinusDoubleSpacer;
private double dotWidthMinusDoubleSpacer;
private double dotHeightMinusDoubleSpacer;
private InvalidationListener sizeListener;
private EventHandler<MouseEvent> clickHandler;
private CopyOnWriteArrayList<DotMatrixEventListener> listeners;
// ******************** Constructors **************************************
public DotMatrix() {
this(250, 250, 32, 32, Color.rgb(255, 55, 0), Color.rgb(51, 51, 51, 0.5), DotShape.SQUARE, MatrixFont8x8.INSTANCE);
}
public DotMatrix(final int COLS, final int ROWS) {
this(250, 250, COLS, ROWS, Color.rgb(255, 55, 0), Color.rgb(51, 51, 51, 0.5), DotShape.SQUARE, MatrixFont8x8.INSTANCE);
}
public DotMatrix(final int COLS, final int ROWS, final Color DOT_ON_COLOR) {
this(250, 250, COLS, ROWS, DOT_ON_COLOR, Color.rgb(51, 51, 51, 0.5), DotShape.SQUARE, MatrixFont8x8.INSTANCE);
}
public DotMatrix(final double PREFERRED_WIDTH, final double PREFERRED_HEIGHT, final int COLS, final int ROWS, final Color DOT_ON_COLOR, final Color DOT_OFF_COLOR, final DotShape DOT_SHAPE, final MatrixFont FONT) {
preferredWidth = PREFERRED_WIDTH;
preferredHeight = PREFERRED_HEIGHT;
dotOnColor = convertToInt(DOT_ON_COLOR);
dotOffColor = convertToInt(DOT_OFF_COLOR);
dotShape = DOT_SHAPE;
cols = COLS;
rows = ROWS;
matrix = new int[cols][rows];
matrixFont = FONT;
characterWidth = matrixFont.getCharacterWidth();
characterHeight = matrixFont.getCharacterHeight();
characterWidthMinusOne = characterWidth - 1;
useSpacer = true;
squareDots = true;
spacerSizeFactor = DEFAULT_SPACER_SIZE_FACTOR;
sizeListener = o -> resize();
clickHandler = e -> checkForClick(e);
listeners = new CopyOnWriteArrayList<>();
initGraphics();
registerListeners();
}
// ******************** Initialization ************************************
private void initGraphics() {
// prefill matrix with dotOffColor
for (int y = 0 ; y < rows ; y++) {
for (int x = 0 ; x < cols ; x++) {
matrix[x][y] = dotOffColor;
}
}
if (Double.compare(getPrefWidth(), 0.0) <= 0 || Double.compare(getPrefHeight(), 0.0) <= 0 ||
Double.compare(getWidth(), 0.0) <= 0 || Double.compare(getHeight(), 0.0) <= 0) {
if (getPrefWidth() > 0 && getPrefHeight() > 0) {
setPrefSize(getPrefWidth(), getPrefHeight());
} else {
setPrefSize(preferredWidth, preferredHeight);
}
}
canvas = new Canvas(preferredWidth, preferredHeight);
ctx = canvas.getGraphicsContext2D();
pane = new StackPane(canvas);
getChildren().setAll(pane);
}
private void registerListeners() {
widthProperty().addListener(sizeListener);
heightProperty().addListener(sizeListener);
canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, clickHandler);
}
// ******************** Methods *******************************************
@Override public ObservableList<Node> getChildren() { return super.getChildren(); }
public void setColsAndRows(final int COLS, final int ROWS) {
cols = COLS;
rows = ROWS;
matrix = new int[cols][rows];
initGraphics();
resize();
}
public Color getDotOnColor() { return convertToColor(dotOnColor); }
public void setDotOnColor(final Color COLOR) {
dotOnColor = convertToInt(COLOR);
drawMatrix();
}
public Color getDotOffColor() { return convertToColor(dotOffColor); }
public void setDotOffColor(final Color COLOR) {
dotOffColor = convertToInt(COLOR);
for (int y = 0 ; y < rows ; y++) {
for (int x = 0 ; x < cols ; x++) {
matrix[x][y] = dotOffColor;
}
}
drawMatrix();
}
public DotShape getDotShape() { return dotShape; }
public void setDotShape(final DotShape SHAPE) {
dotShape = SHAPE;
drawMatrix();
}
public MatrixFont getMatrixFont() { return matrixFont; }
public void setMatrixFont(final MatrixFont FONT) {
matrixFont = FONT;
characterWidth = matrixFont.getCharacterWidth();
characterHeight = matrixFont.getCharacterHeight();
characterWidthMinusOne = characterWidth - 1;
drawMatrix();
}
public boolean isUsingSpacer() { return useSpacer; }
public void setUseSpacer(final boolean USE) {
useSpacer = USE;
resize();
}
public boolean isSquareDots() { return squareDots; }
public void setSquareDots(final boolean SQUARE) {
squareDots = SQUARE;
resize();
}
public double getSpacerSizeFactor() { return spacerSizeFactor; }
public void setSpacerSizeFactor(final double FACTOR) {
spacerSizeFactor = clamp(0.0, 0.2, FACTOR);
spacer = useSpacer ? dotSize * spacerSizeFactor : 0;
dotSizeMinusDoubleSpacer = dotSize - spacer * 2;
drawMatrix();
}
public void setPixel(final int X, final int Y, final boolean VALUE) { setPixel(X, Y, VALUE ? dotOnColor : dotOffColor); }
public void setPixel(final int X, final int Y, final Color COLOR) { setPixel(X, Y, convertToInt(COLOR)); }
public void setPixel(final int X, final int Y, final int COLOR_VALUE) {
if (X >= cols || X < 0) return;
if (Y >= rows || Y < 0) return;
matrix[X][Y] = COLOR_VALUE;
}
public void setPixelWithRedraw(final int X, final int Y, final boolean ON) {
setPixel(X, Y, ON ? dotOnColor : dotOffColor);
drawMatrix();
}
public void setPixelWithRedraw(final int X, final int Y, final int COLOR_VALUE) {
setPixel(X, Y, COLOR_VALUE);
drawMatrix();
}
public void setCharAt(final char CHAR, final int X, final int Y) {
setCharAt(CHAR, X, Y, dotOnColor);
}
public void setCharAt(final char CHAR, final int X, final int Y, final int COLOR_VALUE) {
int[] c = matrixFont.getCharacter(CHAR);
for (int x = 0; x < characterWidth; x++) {
for (int y = 0; y < characterHeight; y++) {
setPixel(x + X, y + Y, getBitAt(characterWidthMinusOne - x, y, c) == 0 ? dotOffColor : COLOR_VALUE);
}
}
drawMatrix();
}
public void setCharAtWithBackground(final char CHAR, final int X, final int Y) {
setCharAtWithBackground(CHAR, X, Y, dotOnColor);
}
public void setCharAtWithBackground(final char CHAR, final int X, final int Y, final int COLOR_VALUE) {
int[] c = matrixFont.getCharacter(CHAR);
for (int x = 0; x < characterWidth; x++) {
for (int y = 0; y < characterHeight; y++) {
if (getBitAt(characterWidthMinusOne - x, y, c) == 0) continue;
setPixel(x + X, y + Y, COLOR_VALUE);
}
}
drawMatrix();
}
public double getDotSize() { return dotSize; }
public double getDotWidth() { return dotWidth; }
public double getDotHeight() { return dotHeight; }
public double getMatrixWidth() { return canvas.getWidth(); }
public double getMatrixHeight() { return canvas.getHeight(); }
public Bounds getMatrixLayoutBounds() { return canvas.getLayoutBounds(); }
public Bounds getMatrixBoundsInParent() { return canvas.getBoundsInParent(); }
public Bounds getMatrixBoundsInLocal() { return canvas.getBoundsInLocal(); }
public int getCols() { return cols; }
public int getRows() { return rows; }
public int[][] getMatrix() { return matrix; }
public static Color convertToColor(final int COLOR_VALUE) {
return Color.rgb((COLOR_VALUE & RED_MASK) >> 16, (COLOR_VALUE & GREEN_MASK) >> 8, (COLOR_VALUE & BLUE_MASK), ALPHA_FACTOR * ((COLOR_VALUE & ALPHA_MASK) >>> 24));
}
public static int convertToInt(final Color COLOR) {
return convertToInt((float) COLOR.getRed(), (float) COLOR.getGreen(), (float) COLOR.getBlue(), (float) COLOR.getOpacity());
}
public static int convertToInt(final float RED, final float GREEN, final float BLUE, final float ALPHA) {
int red = Math.round(255 * RED);
int green = Math.round(255 * GREEN);
int blue = Math.round(255 * BLUE);
int alpha = Math.round(255 * ALPHA);
return (alpha << 24) | (red << 16) | (green << 8) | blue;
}
public static int getBitAt(final int X, final int Y, final int[] BYTE_ARRAY) { return (BYTE_ARRAY[Y] >> X) & 1; }
public static boolean getBitAtBoolean(final int X, final int Y, final int[] BYTE_ARRAY) { return ((BYTE_ARRAY[Y] >> X) & 1) == 1; }
public int getColorValueAt(final int X, final int Y) { return matrix[X][Y]; }
public Color getColorAt(final int X, final int Y) { return convertToColor(matrix[X][Y]); }
public void shiftLeft() {
int[] firstColumn = new int[rows];
for (int y = 0 ; y < rows ; y++) { firstColumn[y] = matrix[0][y]; }
for (int y = 0 ; y < rows ; y++) {
for (int x = 1 ; x < cols ; x++) {
matrix[x - 1][y] = matrix[x][y];
}
}
for (int y = 0 ; y < rows ; y++) { matrix[cols - 1][y] = firstColumn[y]; }
drawMatrix();
}
public void shiftRight() {
int[] lastColumn = new int[rows];
for (int y = 0 ; y < rows ; y++) { lastColumn[y] = matrix[cols - 1][y]; }
for (int y = 0 ; y < rows ; y++) {
for (int x = cols - 2 ; x >= 0 ; x--) {
matrix[x + 1][y] = matrix[x][y];
}
}
for (int y = 0 ; y < rows ; y++) { matrix[0][y] = lastColumn[y]; }
drawMatrix();
}
public void shiftUp() {
int[] firstRow = new int[cols];
for (int x = 0 ; x < cols ; x++) { firstRow[x] = matrix[x][0]; }
for (int y = 1 ; y < rows ; y++) {
for (int x = 0 ; x < cols ; x++) {
matrix[x][y - 1] = matrix[x][y];
}
}
for (int x = 0 ; x < cols ; x++) { matrix[x][rows - 1] = firstRow[x]; }
drawMatrix();
}
public void shiftDown() {
int[] lastRow = new int[cols];
for (int x = 0 ; x < cols ; x++) { lastRow[x] = matrix[x][rows - 1]; }
for (int y = rows - 2 ; y >= 0 ; y--) {
for (int x = 0 ; x < cols ; x++) {
matrix[x][y + 1] = matrix[x][y];
}
}
for (int x = 0 ; x < cols ; x++) { matrix[x][0] = lastRow[x]; }
drawMatrix();
}
public void setAllDotsOn() {
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
setPixel(x, y, true);
}
}
drawMatrix();
}
public void setAllDotsOff() {
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
setPixel(x, y, false);
}
}
drawMatrix();
}
public static final double clamp(final double MIN, final double MAX, final double VALUE) {
if (Double.compare(VALUE, MIN) < 0) return MIN;
if (Double.compare(VALUE, MAX) > 0) return MAX;
return VALUE;
}
public void drawMatrix() {
ctx.clearRect(0, 0, width, height);
switch(dotShape) {
case ROUNDED_RECT:
CtxBounds bounds = new CtxBounds(dotWidthMinusDoubleSpacer, dotHeightMinusDoubleSpacer);
CtxCornerRadii cornerRadii = new CtxCornerRadii(dotSize * 0.125);
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
ctx.setFill(convertToColor(matrix[x][y]));
bounds.setX(x * dotWidth + spacer);
bounds.setY(y * dotHeight + spacer);
drawRoundedRect(ctx, bounds, cornerRadii);
ctx.fill();
}
}
break;
case ROUND:
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
ctx.setFill(convertToColor(matrix[x][y]));
ctx.fillOval(x * dotWidth + spacer, y * dotHeight + spacer, dotWidthMinusDoubleSpacer, dotHeightMinusDoubleSpacer);
}
}
break;
case SQUARE:
default :
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
ctx.setFill(convertToColor(matrix[x][y]));
ctx.fillRect(x * dotWidth + spacer, y * dotHeight + spacer, dotWidthMinusDoubleSpacer, dotHeightMinusDoubleSpacer);
}
}
break;
}
}
public void setOnDotMatrixEvent(final DotMatrixEventListener LISTENER) { addDotMatrixEventListener(LISTENER); }
public void addDotMatrixEventListener(final DotMatrixEventListener LISTENER) { if (!listeners.contains(LISTENER)) listeners.add(LISTENER); }
public void removeDotMatrixEventListener(final DotMatrixEventListener LISTENER) { if (listeners.contains(LISTENER)) listeners.remove(LISTENER); }
public void removeAllDotMatrixEventListeners() { listeners.clear(); }
public void fireDotMatrixEvent(final DotMatrixEvent EVENT) {
for (DotMatrixEventListener listener : listeners) { listener.onDotMatrixEvent(EVENT); }
}
@Override protected double computePrefWidth(final double HEIGHT) { return super.computePrefWidth(HEIGHT); }
@Override protected double computePrefHeight(final double WIDTH) { return super.computePrefHeight(WIDTH); }
public void dispose() {
listeners.clear();
widthProperty().removeListener(sizeListener);
heightProperty().removeListener(sizeListener);
canvas.removeEventHandler(MouseEvent.MOUSE_PRESSED, clickHandler);
}
private long getRed(final long COLOR_VALUE) { return (COLOR_VALUE & RED_MASK) >> 16; }
private long getGreen(final long COLOR_VALUE) { return (COLOR_VALUE & GREEN_MASK) >> 8; }
private long getBlue(final long COLOR_VALUE) { return (COLOR_VALUE & BLUE_MASK); }
private long getAlpha(final long COLOR_VALUE) { return (COLOR_VALUE & ALPHA_MASK) >>> 24; }
private void checkForClick(final MouseEvent EVT) {
double spacerPlusDotSizeMinusDoubleSpacer = spacer + dotSizeMinusDoubleSpacer;
for (int y = 0; y < rows; y++) {
for (int x = 0; x < cols; x++) {
if (isInRectangle(EVT.getX(), EVT.getY(), x * dotSize + spacer, y * dotSize + spacer, x * dotSize + spacerPlusDotSizeMinusDoubleSpacer, y * dotSize + spacerPlusDotSizeMinusDoubleSpacer)) {
fireDotMatrixEvent(new DotMatrixEvent(x, y, EVT.getScreenX(), EVT.getScreenY()));
break;
}
}
}
}
private static void drawRoundedRect(final GraphicsContext CTX, final CtxBounds BOUNDS, final CtxCornerRadii RADII) {
double x = BOUNDS.getX();
double y = BOUNDS.getY();
double width = BOUNDS.getWidth();
double height = BOUNDS.getHeight();
double xPlusWidth = x + width;
double yPlusHeight = y + height;
CTX.beginPath();
CTX.moveTo(x + RADII.getTopRight(), y);
CTX.lineTo(xPlusWidth - RADII.getTopRight(), y);
CTX.quadraticCurveTo(xPlusWidth, y, xPlusWidth, y + RADII.getTopRight());
CTX.lineTo(xPlusWidth, yPlusHeight - RADII.getBottomRight());
CTX.quadraticCurveTo(xPlusWidth, yPlusHeight, xPlusWidth - RADII.getBottomRight(), yPlusHeight);
CTX.lineTo(x + RADII.getBottomLeft(), yPlusHeight);
CTX.quadraticCurveTo(x, yPlusHeight, x, yPlusHeight - RADII.getBottomLeft());
CTX.lineTo(x, y + RADII.getTopRight());
CTX.quadraticCurveTo(x, y, x + RADII.getTopRight(), y);
CTX.closePath();
}
private static boolean isInRectangle(final double X, final double Y,
final double MIN_X, final double MIN_Y,
final double MAX_X, final double MAX_Y) {
return (Double.compare(X, MIN_X) >= 0 &&
Double.compare(X, MAX_X) <= 0 &&
Double.compare(Y, MIN_Y) >= 0 &&
Double.compare(Y, MAX_Y) <= 0);
}
// ******************** Resizing ******************************************
private void resize() {
width = getWidth() - getInsets().getLeft() - getInsets().getRight();
height = getHeight() - getInsets().getTop() - getInsets().getBottom();
dotSize = (width / cols) < (height / rows) ? (width / cols) : (height / rows);
dotWidth = (width / cols);
dotHeight = (height / rows);
spacer = useSpacer ? dotSize * getSpacerSizeFactor() : 0;
dotSizeMinusDoubleSpacer = dotSize - spacer * 2;
dotWidthMinusDoubleSpacer = dotWidth - spacer * 2;
dotHeightMinusDoubleSpacer = dotHeight - spacer * 2;
if (width > 0 && height > 0) {
pane.setMaxSize(width, height);
pane.setPrefSize(width, height);
pane.relocate((getWidth() - width) * 0.5, (getHeight() - height) * 0.5);
if (squareDots) {
dotWidth = dotSize;
dotHeight = dotSize;
dotWidthMinusDoubleSpacer = dotSizeMinusDoubleSpacer;
dotHeightMinusDoubleSpacer = dotSizeMinusDoubleSpacer;
}
canvas.setWidth(cols * dotWidth);
canvas.setHeight(rows * dotHeight);
drawMatrix();
}
}
}
| Adjusted click handler to dotWidth and dotHeight
| src/main/java/eu/hansolo/fx/dotmatrix/DotMatrix.java | Adjusted click handler to dotWidth and dotHeight | <ide><path>rc/main/java/eu/hansolo/fx/dotmatrix/DotMatrix.java
<ide> private long getAlpha(final long COLOR_VALUE) { return (COLOR_VALUE & ALPHA_MASK) >>> 24; }
<ide>
<ide> private void checkForClick(final MouseEvent EVT) {
<del> double spacerPlusDotSizeMinusDoubleSpacer = spacer + dotSizeMinusDoubleSpacer;
<add> double spacerPlusPixelWidthMinusDoubleSpacer = spacer + dotWidthMinusDoubleSpacer;
<add> double spacerPlusPixelHeightMinusDoubleSpacer = spacer + dotHeightMinusDoubleSpacer;
<ide> for (int y = 0; y < rows; y++) {
<ide> for (int x = 0; x < cols; x++) {
<del> if (isInRectangle(EVT.getX(), EVT.getY(), x * dotSize + spacer, y * dotSize + spacer, x * dotSize + spacerPlusDotSizeMinusDoubleSpacer, y * dotSize + spacerPlusDotSizeMinusDoubleSpacer)) {
<add> if (isInRectangle(EVT.getX(), EVT.getY(), x * dotWidth + spacer, y * dotHeight + spacer, x * dotWidth + spacerPlusPixelWidthMinusDoubleSpacer, y * dotHeight + spacerPlusPixelHeightMinusDoubleSpacer)) {
<ide> fireDotMatrixEvent(new DotMatrixEvent(x, y, EVT.getScreenX(), EVT.getScreenY()));
<ide> break;
<ide> } |
|
Java | bsd-3-clause | 3a626180a5eb95a14170a30370b9230c5550335b | 0 | Open-MBEE/MDK,Open-MBEE/MDK | package gov.nasa.jpl.mbee.generator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import gov.nasa.jpl.mbee.ems.validation.ImageValidator;
import gov.nasa.jpl.mbee.lib.Utils;
import gov.nasa.jpl.mbee.model.DocBookOutputVisitor;
import gov.nasa.jpl.mbee.model.Document;
import gov.nasa.jpl.mbee.viewedit.DBAlfrescoVisitor;
import gov.nasa.jpl.mbee.viewedit.PresentationElement;
import gov.nasa.jpl.mbee.viewedit.PresentationElement.PEType;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBBook;
import gov.nasa.jpl.mgss.mbee.docgen.validation.ValidationRule;
import gov.nasa.jpl.mgss.mbee.docgen.validation.ValidationRuleViolation;
import gov.nasa.jpl.mgss.mbee.docgen.validation.ValidationSuite;
import gov.nasa.jpl.mgss.mbee.docgen.validation.ViolationSeverity;
import com.nomagic.magicdraw.core.Application;
import com.nomagic.magicdraw.core.ProjectUtilities;
import com.nomagic.magicdraw.openapi.uml.SessionManager;
import com.nomagic.uml2.ext.jmi.helpers.ModelHelper;
import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper;
import com.nomagic.uml2.ext.magicdraw.classes.mddependencies.Dependency;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.AggregationKind;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.AggregationKindEnum;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Association;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Classifier;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Constraint;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ElementValue;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Expression;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceSpecification;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceValue;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.LiteralString;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.NamedElement;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Package;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Property;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Relationship;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Slot;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Type;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.TypedElement;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ValueSpecification;
import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype;
import com.nomagic.uml2.impl.ElementsFactory;
import com.nomagic.task.ProgressStatus;
import com.nomagic.task.RunnableWithProgress;
public class ViewPresentationGenerator implements RunnableWithProgress {
private ValidationSuite suite = new ValidationSuite("View Instance Generation");
private ValidationRule uneditableContent = new ValidationRule("Uneditable", "uneditable", ViolationSeverity.ERROR);
private ValidationRule uneditableOwner = new ValidationRule("Uneditable owner", "uneditable owner", ViolationSeverity.WARNING);
private ValidationRule docPackage = new ValidationRule("docPackage", "docPackage", ViolationSeverity.ERROR);
private ValidationRule viewInProject = new ValidationRule("viewInProject", "viewInProject", ViolationSeverity.WARNING);
private ValidationRule viewParent = new ValidationRule("viewParent", "viewParent", ViolationSeverity.WARNING);
private Classifier paraC = Utils.getOpaqueParaClassifier();
private Classifier tableC = Utils.getOpaqueTableClassifier();
private Classifier listC = Utils.getOpaqueListClassifier();
private Classifier imageC = Utils.getOpaqueImageClassifier();
private Classifier sectionC = Utils.getSectionClassifier();
private Property generatedFromView = Utils.getGeneratedFromViewProperty();
private Property generatedFromElement = Utils.getGeneratedFromElementProperty();
private Stereotype presentsS = Utils.getPresentsStereotype();
private Stereotype viewS = Utils.getViewClassStereotype();
private Stereotype productS = Utils.getProductStereotype();
private ElementsFactory ef = Application.getInstance().getProject().getElementsFactory();
private Package viewInstancesPackage = null;
private Package unusedPackage = null;
private boolean recurse;
private Element view;
// use these prefixes then add project_id to form the view instances id and unused view id respectively
private String viewInstPrefix = "View_Instances";
private String unusedInstPrefix = "Unused_View_Instances";
// this suffix is appended to the name of each particular package
private String genericInstSuffix = " Instances";
private boolean cancelSession = false;
private Map<Element, Package> view2pac = new HashMap<Element, Package>();
public ViewPresentationGenerator(Element view, boolean recursive) {
this.view = view;
this.recurse = recursive;
}
@Override
public void run(ProgressStatus ps) {
suite.addValidationRule(uneditableContent);
suite.addValidationRule(uneditableOwner);
suite.addValidationRule(docPackage);
suite.addValidationRule(viewInProject);
suite.addValidationRule(viewParent);
DocumentValidator dv = new DocumentValidator(view);
dv.validateDocument();
if (dv.isFatal()) {
dv.printErrors(false);
return;
}
// first run a local generation of the view model to get the current model view structure
DocumentGenerator dg = new DocumentGenerator(view, dv, null);
Document dge = dg.parseDocument(true, recurse, false);
(new PostProcessor()).process(dge);
DocBookOutputVisitor visitor = new DocBookOutputVisitor(true);
DBAlfrescoVisitor visitor2 = new DBAlfrescoVisitor(recurse, true);
dge.accept(visitor);
DBBook book = visitor.getBook();
if (book == null)
return;
book.accept(visitor2);
Map<Element, List<PresentationElement>> view2pe = visitor2.getView2Pe();
Map<Element, List<PresentationElement>> view2unused = visitor2.getView2Unused();
Map<Element, JSONArray> view2elements = visitor2.getView2Elements();
// this initializes and checks if both reserved packages are editable
viewInstancesPackage = createViewInstancesPackage();
unusedPackage = createUnusedInstancesPackage();
SessionManager.getInstance().createSession("view instance gen");
try {
viewInstanceBuilder(view2pe, view2unused);
for (Element v : view2elements.keySet()) {
JSONArray es = view2elements.get(v);
if (v.isEditable())
StereotypesHelper.setStereotypePropertyValue(v, Utils.getViewClassStereotype(), "elements", es.toJSONString());
}
if (cancelSession) {
SessionManager.getInstance().cancelSession();
Utils.guilog("[ERROR] View Generation canceled because some elements that require updates are not editable. See validation window.");
} else {
SessionManager.getInstance().closeSession();
Utils.guilog("[INFO] View Generation completed.");
}
} catch (Exception e) {
Utils.printException(e);
SessionManager.getInstance().cancelSession();
}
ImageValidator iv = new ImageValidator(visitor2.getImages());
// this checks images generated from the local generation against what's on the web based on checksum
iv.validate();
if (!iv.getRule().getViolations().isEmpty() || suite.hasErrors()) {
ValidationSuite imageSuite = iv.getSuite();
List<ValidationSuite> vss = new ArrayList<ValidationSuite>();
vss.add(imageSuite);
vss.add(suite);
Utils.displayValidationWindow(vss, "View Generation and Images Validation");
}
}
private void viewInstanceBuilder( Map<Element, List<PresentationElement>> view2pe, Map<Element, List<PresentationElement>> view2unused) {
// first pass through all the views and presentation elements to handle them
Set<Element> skippedViews = new HashSet<Element>();
for (Element v : view2pe.keySet()) {
// only worry about the views in the current module, output to log if they aren't there
if (!ProjectUtilities.isElementInAttachedProject(v)) {
handleViewOrSection(v, null, view2pe.get(v));
} else {
ValidationRuleViolation violation = new ValidationRuleViolation(v, "[IN MODULE] This view is in a module and was not processed.");
viewInProject.addViolation(violation);
skippedViews.add(v);
//Application.getInstance().getGUILog().log("[INFO] View " + view.getID() + " not in current project.");
}
}
if (cancelSession)
return;
//by now all views should have their instance package available
setPackageHierarchy(skippedViews);
// then, pass through all the unused PresentationElements and move their particular InstanceSpecification to the unused InstSpec package
for (List<PresentationElement> presElems : view2unused.values()) {
// only can worry about the presElems in the current project
for (PresentationElement presentationElement : presElems) {
// but we only really care about these instances, since that's all that we can ask about
InstanceSpecification is = presentationElement.getInstance();
if (!ProjectUtilities.isElementInAttachedProject(is) && is.isEditable()) {
is.setOwner(unusedPackage);
}
}
}
}
public void handleViewOrSection(Element view, InstanceSpecification section, List<PresentationElement> pes) {
// check for manual instances (thought that was in dependencies)
Package owner = getViewTargetPackage(view, true);
view2pac.put(view, owner);
List<InstanceValue> list = new ArrayList<InstanceValue>();
boolean created = false;
for (PresentationElement pe : pes) {
if (pe.isManual()) {
InstanceValue iv = ef.createInstanceValueInstance();
InstanceSpecification inst = pe.getInstance();
iv.setInstance(inst);
list.add(iv);
// lets do some testing on the instance owner
Element instOwner = inst.getOwner();
boolean touchMe = true;
for (Relationship r : instOwner.get_relationshipOfRelatedElement()) {
if (r instanceof Dependency && StereotypesHelper.hasStereotype(r, presentsS)) {
// we ignore inst and leave the owner untouched if owner
// has a presents stereotype
touchMe = false;
break;
}
}
// if the owner doesn't have the presents stereotype, it resets
// the owner to the correct one
if (touchMe) {
if (inst.isEditable())
inst.setOwner(owner);
else {
ValidationRuleViolation vrv = new ValidationRuleViolation(inst, "[NOT EDITABLE (OWNER)] This instance cannot be moved into a view instance package.");
uneditableOwner.addViolation(vrv);
}
}
continue;
}
InstanceSpecification is = pe.getInstance();
if (is == null) {
created = true;
is = ef.createInstanceSpecificationInstance();
is.setName(pe.getName());
if (pe.getType() == PEType.PARA)
is.getClassifier().add(paraC);
else if (pe.getType() == PEType.TABLE)
is.getClassifier().add(tableC);
else if (pe.getType() == PEType.LIST)
is.getClassifier().add(listC);
else if (pe.getType() == PEType.IMAGE)
is.getClassifier().add(imageC);
else if (pe.getType() == PEType.SECTION)
is.getClassifier().add(sectionC);
Slot s = ef.createSlotInstance();
s.setOwner(is);
s.setDefiningFeature(generatedFromView);
ElementValue ev = ef.createElementValueInstance();
ev.setElement(view);
s.getValue().add(ev);
if (pe.getType() == PEType.SECTION && pe.getLoopElement() != null) {
Slot ss = ef.createSlotInstance();
ss.setOwner(is);
ss.setDefiningFeature(generatedFromElement);
ElementValue ev2 = ef.createElementValueInstance();
ev2.setElement(pe.getLoopElement());
ss.getValue().add(ev2);
}
}
if (is.isEditable()) {
is.setOwner(owner);
if (pe.getNewspec() != null) {
LiteralString ls = ef.createLiteralStringInstance();
ls.setOwner(is);
ls.setValue(pe.getNewspec().toJSONString());
is.setSpecification(ls);
}
is.setName(pe.getName());
if (is.getName() == null || is.getName().isEmpty()) {
is.setName("<>");
}
} else {
//check if this really needs to be edited
boolean needEdit = false;
ValueSpecification oldvs = is.getSpecification();
if (pe.getNewspec() != null && !pe.getNewspec().get("type").equals("Section")) {
if (oldvs instanceof LiteralString && ((LiteralString)oldvs).getValue() != null) {
JSONObject oldob = (JSONObject)JSONValue.parse(((LiteralString)oldvs).getValue());
if (!oldob.equals(pe.getNewspec()))
needEdit = true;
} else
needEdit = true;
}
if (is.getOwner() != owner) {
ValidationRuleViolation vrv = new ValidationRuleViolation(is, "[NOT EDITABLE (OWNER)] This presentation element instance's owning view instance package can't be updated.");
uneditableOwner.addViolation(vrv);
}
if (needEdit) {
ValidationRuleViolation vrv = new ValidationRuleViolation(is, "[NOT EDITABLE (CONTENT)] This presentation element instance can't be updated.");
uneditableContent.addViolation(vrv);
cancelSession = true;
}
}
InstanceValue iv = ef.createInstanceValueInstance();
iv.setInstance(is);
list.add(iv);
if (pe.getType() == PEType.SECTION) {
handleViewOrSection(view, is, pe.getChildren());
}
pe.setInstance(is);
}
if (section != null) {
if (!section.isEditable()) {
boolean needEdit = false;
if (section.getSpecification() != null && section.getSpecification() instanceof Expression) {
List<ValueSpecification> model = ((Expression)section.getSpecification()).getOperand();
if (model.size() != list.size())
needEdit = true;
else {
for (int i = 0; i < model.size(); i++) {
ValueSpecification modelvs = model.get(i);
if (!(modelvs instanceof InstanceValue) || ((InstanceValue)modelvs).getInstance() != list.get(i).getInstance()) {
needEdit = true;
break;
}
}
}
} else
needEdit = true;
if (needEdit) {
ValidationRuleViolation vrv = new ValidationRuleViolation(section, "[NOT EDITABLE (SECTION CONTENT)] This section instance can't be updated.");
uneditableContent.addViolation(vrv);
if (created)
cancelSession = true;
}
} else {
Expression ex = ef.createExpressionInstance();
ex.setOwner(section);
ex.getOperand().addAll(list);
section.setSpecification(ex);
}
} else {
Constraint c = getViewConstraint(view);
if (!c.isEditable()) {
boolean needEdit = false;
if (c.getSpecification() != null && c.getSpecification() instanceof Expression) {
List<ValueSpecification> model = ((Expression)c.getSpecification()).getOperand();
if (model.size() != list.size())
needEdit = true;
else {
for (int i = 0; i < model.size(); i++) {
ValueSpecification modelvs = model.get(i);
if (!(modelvs instanceof InstanceValue) || ((InstanceValue)modelvs).getInstance() != list.get(i).getInstance()) {
needEdit = true;
break;
}
}
}
} else
needEdit = true;
if (needEdit) {
ValidationRuleViolation vrv = new ValidationRuleViolation(c, "[NOT EDITABLE (VIEW CONTENT)] This view constraint can't be updated.");
uneditableContent.addViolation(vrv);
if (created)
cancelSession = true;
}
} else {
Expression ex = ef.createExpressionInstance();
ex.setOwner(c);
ex.getOperand().addAll(list);
c.setSpecification(ex);
}
}
}
//get or create view constraint
private Constraint getViewConstraint(Element view) {
Constraint c = Utils.getViewConstraint(view);
if (c != null)
return c;
c = ef.createConstraintInstance();
c.setOwner(view);
c.getConstrainedElement().add(view);
return c;
}
//get or create view instance package
private Package getViewTargetPackage(Element view, boolean create) {
// if you can find the folder with this Utils, just go ahead and return it
// consider setting folder id?
List<Element> results = Utils.collectDirectedRelatedElementsByRelationshipStereotype(view, presentsS, 1, false, 1);
if (!results.isEmpty() && results.get(0) instanceof Package) {
final Package p = (Package) results.get(0);
//setPackageHierarchy(view, viewInst, p);
//p.setName(getViewTargetPackageName(view));
return p;
}
if (create) {
Package viewTarget = ef.createPackageInstance();
String viewName = ((NamedElement)view).getName();
viewTarget.setName(((viewName == null || viewName.isEmpty()) ? view.getID() : viewName) + " " + genericInstSuffix);
viewTarget.setOwner(viewInstancesPackage);
Dependency d = ef.createDependencyInstance();
d.setOwner(viewTarget);
ModelHelper.setSupplierElement(d, viewTarget);
ModelHelper.setClientElement(d, view);
StereotypesHelper.addStereotype(d, presentsS);
return viewTarget;
}
return null;
}
private void setPackageHierarchy(Set<Element> skipped) {
for (Element view: view2pac.keySet()) {
Type viewt = (Type)view;
Element parentView = null;
Package parentPack = null;
if (StereotypesHelper.hasStereotypeOrDerived(view, productS)) {
if (!(view.getOwner() instanceof Package)) {
ValidationRuleViolation vrv = new ValidationRuleViolation(view, "[DOCUMENT OWNER] A document should be owned by a package.");
docPackage.addViolation(vrv);
Element owner = view.getOwner();
while (!(owner instanceof Package)) {
owner = owner.getOwner();
}
parentPack = (Package)owner;
} else
parentPack = (Package)view.getOwner();
} else {
for (TypedElement t: viewt.get_typedElementOfType()) {
if (t instanceof Property && ((Property)t).getAggregation().equals(AggregationKindEnum.COMPOSITE) &&
StereotypesHelper.hasStereotypeOrDerived(t.getOwner(), viewS)) {
if (parentView != null) {
ValidationRuleViolation vrv = new ValidationRuleViolation(view, "[CANONICAL PARENT] This view has multiple parent views that uses composition");
viewParent.addViolation(vrv);
break;
}
parentView = t.getOwner();
}
}
}
if (parentPack == null) {
if (parentView != null) {
if (view2pac.containsKey(parentView))
parentPack = view2pac.get(parentView);
else {
List<Element> results = Utils.collectDirectedRelatedElementsByRelationshipStereotype(parentView, presentsS, 1, false, 1);
if (!results.isEmpty() && results.get(0) instanceof Package && !ProjectUtilities.isElementInAttachedProject(results.get(0))) {
parentPack = (Package)results.get(0);
} else
parentPack = viewInstancesPackage;
}
} else {
parentPack = viewInstancesPackage;
}
}
Package currentPack = view2pac.get(view);
if (currentPack.getOwner() != parentPack) {
if (currentPack.isEditable())
currentPack.setOwner(parentPack);
else {
ValidationRuleViolation vrv = new ValidationRuleViolation(currentPack, "[NOT EDITABLE (OWNER)] View instance package cannot be moved to right hierarchy");
uneditableOwner.addViolation(vrv);
}
}
}
}
private Package createViewInstancesPackage() {
// fix root element, set it to project instead
return createParticularPackage(Utils.getRootElement(), viewInstPrefix, "View Instances");
}
private Package createUnusedInstancesPackage() {
Package rootPackage = createParticularPackage(Utils.getRootElement(), viewInstPrefix, "View Instances");
return createParticularPackage(rootPackage, unusedInstPrefix, "Unused View Instances");
}
//get or create package with id
private Package createParticularPackage(Package owner, String packIDPrefix, String name) {
// fix root element, set it to project replace PROJECT with the packIDPrefix
String viewInstID = Utils.getProject().getPrimaryProject() .getProjectID().replace("PROJECT", packIDPrefix);
Package viewInst = (Package)Application.getInstance().getProject().getElementByID(viewInstID);
if (viewInst == null) {
Application.getInstance().getProject().getCounter().setCanResetIDForObject(true);
viewInst = ef.createPackageInstance();
viewInst.setID(viewInstID);
viewInst.setName(name);
}
// either way, set the owner to the owner we passed in
if (viewInst.isEditable() && viewInst.getOwner() != owner)
viewInst.setOwner(owner);
else if (viewInst.getOwner() != owner) {
//vlaidation error of trying to change owner but can't?
}
return viewInst;
}
}
| src/main/java/gov/nasa/jpl/mbee/generator/ViewPresentationGenerator.java | package gov.nasa.jpl.mbee.generator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import gov.nasa.jpl.mbee.ems.validation.ImageValidator;
import gov.nasa.jpl.mbee.lib.Utils;
import gov.nasa.jpl.mbee.model.DocBookOutputVisitor;
import gov.nasa.jpl.mbee.model.Document;
import gov.nasa.jpl.mbee.viewedit.DBAlfrescoVisitor;
import gov.nasa.jpl.mbee.viewedit.PresentationElement;
import gov.nasa.jpl.mbee.viewedit.PresentationElement.PEType;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBBook;
import gov.nasa.jpl.mgss.mbee.docgen.validation.ValidationRule;
import gov.nasa.jpl.mgss.mbee.docgen.validation.ValidationRuleViolation;
import gov.nasa.jpl.mgss.mbee.docgen.validation.ValidationSuite;
import gov.nasa.jpl.mgss.mbee.docgen.validation.ViolationSeverity;
import com.nomagic.magicdraw.core.Application;
import com.nomagic.magicdraw.core.ProjectUtilities;
import com.nomagic.magicdraw.openapi.uml.SessionManager;
import com.nomagic.uml2.ext.jmi.helpers.ModelHelper;
import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper;
import com.nomagic.uml2.ext.magicdraw.classes.mddependencies.Dependency;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.AggregationKind;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.AggregationKindEnum;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Association;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Classifier;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Constraint;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ElementValue;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Expression;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceSpecification;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceValue;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.LiteralString;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.NamedElement;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Package;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Property;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Relationship;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Slot;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Type;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.TypedElement;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ValueSpecification;
import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype;
import com.nomagic.uml2.impl.ElementsFactory;
import com.nomagic.task.ProgressStatus;
import com.nomagic.task.RunnableWithProgress;
public class ViewPresentationGenerator implements RunnableWithProgress {
private ValidationSuite suite = new ValidationSuite("View Instance Generation");
private ValidationRule uneditableContent = new ValidationRule("Uneditable", "uneditable", ViolationSeverity.ERROR);
private ValidationRule uneditableOwner = new ValidationRule("Uneditable owner", "uneditable owner", ViolationSeverity.WARNING);
private ValidationRule docPackage = new ValidationRule("docPackage", "docPackage", ViolationSeverity.ERROR);
private ValidationRule viewInProject = new ValidationRule("viewInProject", "viewInProject", ViolationSeverity.WARNING);
private ValidationRule viewParent = new ValidationRule("viewParent", "viewParent", ViolationSeverity.WARNING);
private Classifier paraC = Utils.getOpaqueParaClassifier();
private Classifier tableC = Utils.getOpaqueTableClassifier();
private Classifier listC = Utils.getOpaqueListClassifier();
private Classifier imageC = Utils.getOpaqueImageClassifier();
private Classifier sectionC = Utils.getSectionClassifier();
private Property generatedFromView = Utils.getGeneratedFromViewProperty();
private Property generatedFromElement = Utils.getGeneratedFromElementProperty();
private Stereotype presentsS = Utils.getPresentsStereotype();
private Stereotype viewS = Utils.getViewClassStereotype();
private Stereotype productS = Utils.getProductStereotype();
private ElementsFactory ef = Application.getInstance().getProject().getElementsFactory();
private Package viewInstancesPackage = null;
private Package unusedPackage = null;
private boolean recurse;
private Element view;
// use these prefixes then add project_id to form the view instances id and unused view id respectively
private String viewInstPrefix = "View_Instances";
private String unusedInstPrefix = "Unused_View_Instances";
// this suffix is appended to the name of each particular package
private String genericInstSuffix = " Instances";
private boolean cancelSession = false;
private Map<Element, Package> view2pac = new HashMap<Element, Package>();
public ViewPresentationGenerator(Element view, boolean recursive) {
this.view = view;
this.recurse = recursive;
}
@Override
public void run(ProgressStatus ps) {
suite.addValidationRule(uneditableContent);
suite.addValidationRule(uneditableOwner);
suite.addValidationRule(docPackage);
suite.addValidationRule(viewInProject);
suite.addValidationRule(viewParent);
DocumentValidator dv = new DocumentValidator(view);
dv.validateDocument();
if (dv.isFatal()) {
dv.printErrors(false);
return;
}
// first run a local generation of the view model to get the current model view structure
DocumentGenerator dg = new DocumentGenerator(view, dv, null);
Document dge = dg.parseDocument(true, recurse, false);
(new PostProcessor()).process(dge);
DocBookOutputVisitor visitor = new DocBookOutputVisitor(true);
DBAlfrescoVisitor visitor2 = new DBAlfrescoVisitor(recurse, true);
dge.accept(visitor);
DBBook book = visitor.getBook();
if (book == null)
return;
book.accept(visitor2);
Map<Element, List<PresentationElement>> view2pe = visitor2.getView2Pe();
Map<Element, List<PresentationElement>> view2unused = visitor2.getView2Unused();
Map<Element, JSONArray> view2elements = visitor2.getView2Elements();
// this initializes and checks if both reserved packages are editable
viewInstancesPackage = createViewInstancesPackage();
unusedPackage = createUnusedInstancesPackage();
SessionManager.getInstance().createSession("view instance gen");
try {
viewInstanceBuilder(view2pe, view2unused);
for (Element v : view2elements.keySet()) {
JSONArray es = view2elements.get(v);
if (v.isEditable())
StereotypesHelper.setStereotypePropertyValue(v, Utils.getViewClassStereotype(), "elements", es.toJSONString());
}
if (cancelSession) {
SessionManager.getInstance().cancelSession();
Utils.guilog("[ERROR] View Generation canceled because some elements that require updates are not editable. See validation window.");
} else {
SessionManager.getInstance().closeSession();
Utils.guilog("[INFO] View Generation completed.");
}
} catch (Exception e) {
Utils.printException(e);
SessionManager.getInstance().cancelSession();
}
ImageValidator iv = new ImageValidator(visitor2.getImages());
// this checks images generated from the local generation against what's on the web based on checksum
iv.validate();
if (!iv.getRule().getViolations().isEmpty() || suite.hasErrors()) {
ValidationSuite imageSuite = iv.getSuite();
List<ValidationSuite> vss = new ArrayList<ValidationSuite>();
vss.add(imageSuite);
vss.add(suite);
Utils.displayValidationWindow(vss, "View Generation and Images Validation");
}
}
private void viewInstanceBuilder( Map<Element, List<PresentationElement>> view2pe, Map<Element, List<PresentationElement>> view2unused) {
// first pass through all the views and presentation elements to handle them
Set<Element> skippedViews = new HashSet<Element>();
for (Element v : view2pe.keySet()) {
// only worry about the views in the current module, output to log if they aren't there
if (!ProjectUtilities.isElementInAttachedProject(v)) {
handleViewOrSection(v, null, view2pe.get(v));
} else {
ValidationRuleViolation violation = new ValidationRuleViolation(v, "[IN MODULE] This view is in a module and was not processed.");
viewInProject.addViolation(violation);
skippedViews.add(v);
//Application.getInstance().getGUILog().log("[INFO] View " + view.getID() + " not in current project.");
}
}
if (cancelSession)
return;
//by now all views should have their instance package available
setPackageHierarchy(skippedViews);
// then, pass through all the unused PresentationElements and move their particular InstanceSpecification to the unused InstSpec package
for (List<PresentationElement> presElems : view2unused.values()) {
// only can worry about the presElems in the current project
for (PresentationElement presentationElement : presElems) {
// but we only really care about these instances, since that's all that we can ask about
InstanceSpecification is = presentationElement.getInstance();
if (!ProjectUtilities.isElementInAttachedProject(is) && is.isEditable()) {
is.setOwner(unusedPackage);
}
}
}
}
public void handleViewOrSection(Element view, InstanceSpecification section, List<PresentationElement> pes) {
// check for manual instances (thought that was in dependencies)
Package owner = getViewTargetPackage(view, true);
view2pac.put(view, owner);
List<InstanceValue> list = new ArrayList<InstanceValue>();
boolean created = false;
for (PresentationElement pe : pes) {
if (pe.isManual()) {
InstanceValue iv = ef.createInstanceValueInstance();
InstanceSpecification inst = pe.getInstance();
iv.setInstance(inst);
list.add(iv);
// lets do some testing on the instance owner
Element instOwner = inst.getOwner();
boolean touchMe = true;
for (Relationship r : instOwner.get_relationshipOfRelatedElement()) {
if (r instanceof Dependency && StereotypesHelper.hasStereotype(r, presentsS)) {
// we ignore inst and leave the owner untouched if owner
// has a presents stereotype
touchMe = false;
break;
}
}
// if the owner doesn't have the presents stereotype, it resets
// the owner to the correct one
if (touchMe) {
if (inst.isEditable())
inst.setOwner(owner);
else {
ValidationRuleViolation vrv = new ValidationRuleViolation(inst, "[NOT EDITABLE (OWNER)] This instance cannot be moved into a view instance package.");
uneditableOwner.addViolation(vrv);
}
}
continue;
}
InstanceSpecification is = pe.getInstance();
if (is == null) {
created = true;
is = ef.createInstanceSpecificationInstance();
is.setName(pe.getName());
if (pe.getType() == PEType.PARA)
is.getClassifier().add(paraC);
else if (pe.getType() == PEType.TABLE)
is.getClassifier().add(tableC);
else if (pe.getType() == PEType.LIST)
is.getClassifier().add(listC);
else if (pe.getType() == PEType.IMAGE)
is.getClassifier().add(imageC);
else if (pe.getType() == PEType.SECTION)
is.getClassifier().add(sectionC);
Slot s = ef.createSlotInstance();
s.setOwner(is);
s.setDefiningFeature(generatedFromView);
ElementValue ev = ef.createElementValueInstance();
ev.setElement(view);
s.getValue().add(ev);
if (pe.getType() == PEType.SECTION && pe.getLoopElement() != null) {
Slot ss = ef.createSlotInstance();
ss.setOwner(is);
ss.setDefiningFeature(generatedFromElement);
ElementValue ev2 = ef.createElementValueInstance();
ev2.setElement(pe.getLoopElement());
ss.getValue().add(ev2);
}
}
if (is.isEditable()) {
is.setOwner(owner);
if (pe.getNewspec() != null) {
LiteralString ls = ef.createLiteralStringInstance();
ls.setOwner(is);
ls.setValue(pe.getNewspec().toJSONString());
is.setSpecification(ls);
}
is.setName(pe.getName());
if (is.getName() == null || is.getName().isEmpty()) {
is.setName("<>");
}
} else {
//check if this really needs to be edited
boolean needEdit = false;
ValueSpecification oldvs = is.getSpecification();
if (pe.getNewspec() != null && !pe.getNewspec().get("type").equals("Section")) {
if (oldvs instanceof LiteralString && ((LiteralString)oldvs).getValue() != null) {
JSONObject oldob = (JSONObject)JSONValue.parse(((LiteralString)oldvs).getValue());
if (!oldob.equals(pe.getNewspec()))
needEdit = true;
} else
needEdit = true;
}
if (needEdit) {
ValidationRuleViolation vrv = new ValidationRuleViolation(is, "[NOT EDITABLE (CONTENT)] This presentation element instance can't be updated.");
uneditableContent.addViolation(vrv);
cancelSession = true;
}
}
InstanceValue iv = ef.createInstanceValueInstance();
iv.setInstance(is);
list.add(iv);
if (pe.getType() == PEType.SECTION) {
handleViewOrSection(view, is, pe.getChildren());
}
pe.setInstance(is);
}
if (section != null) {
if (!section.isEditable()) {
boolean needEdit = false;
if (section.getSpecification() != null && section.getSpecification() instanceof Expression) {
List<ValueSpecification> model = ((Expression)section.getSpecification()).getOperand();
if (model.size() != list.size())
needEdit = true;
else {
for (int i = 0; i < model.size(); i++) {
ValueSpecification modelvs = model.get(i);
if (!(modelvs instanceof InstanceValue) || ((InstanceValue)modelvs).getInstance() != list.get(i).getInstance()) {
needEdit = true;
break;
}
}
}
} else
needEdit = true;
if (needEdit) {
ValidationRuleViolation vrv = new ValidationRuleViolation(section, "[NOT EDITABLE (SECTION CONTENT)] This section instance can't be updated.");
uneditableContent.addViolation(vrv);
if (created)
cancelSession = true;
}
} else {
Expression ex = ef.createExpressionInstance();
ex.setOwner(section);
ex.getOperand().addAll(list);
section.setSpecification(ex);
}
} else {
Constraint c = getViewConstraint(view);
if (!c.isEditable()) {
boolean needEdit = false;
if (c.getSpecification() != null && c.getSpecification() instanceof Expression) {
List<ValueSpecification> model = ((Expression)c.getSpecification()).getOperand();
if (model.size() != list.size())
needEdit = true;
else {
for (int i = 0; i < model.size(); i++) {
ValueSpecification modelvs = model.get(i);
if (!(modelvs instanceof InstanceValue) || ((InstanceValue)modelvs).getInstance() != list.get(i).getInstance()) {
needEdit = true;
break;
}
}
}
} else
needEdit = true;
if (needEdit) {
ValidationRuleViolation vrv = new ValidationRuleViolation(c, "[NOT EDITABLE (VIEW CONTENT)] This view constraint can't be updated.");
uneditableContent.addViolation(vrv);
if (created)
cancelSession = true;
}
} else {
Expression ex = ef.createExpressionInstance();
ex.setOwner(c);
ex.getOperand().addAll(list);
c.setSpecification(ex);
}
}
}
//get or create view constraint
private Constraint getViewConstraint(Element view) {
Constraint c = Utils.getViewConstraint(view);
if (c != null)
return c;
c = ef.createConstraintInstance();
c.setOwner(view);
c.getConstrainedElement().add(view);
return c;
}
//get or create view instance package
private Package getViewTargetPackage(Element view, boolean create) {
// if you can find the folder with this Utils, just go ahead and return it
// consider setting folder id?
List<Element> results = Utils.collectDirectedRelatedElementsByRelationshipStereotype(view, presentsS, 1, false, 1);
if (!results.isEmpty() && results.get(0) instanceof Package) {
final Package p = (Package) results.get(0);
//setPackageHierarchy(view, viewInst, p);
//p.setName(getViewTargetPackageName(view));
return p;
}
if (create) {
Package viewTarget = ef.createPackageInstance();
String viewName = ((NamedElement)view).getName();
viewTarget.setName(((viewName == null || viewName.isEmpty()) ? view.getID() : viewName) + " " + genericInstSuffix);
viewTarget.setOwner(viewInstancesPackage);
Dependency d = ef.createDependencyInstance();
d.setOwner(viewTarget);
ModelHelper.setSupplierElement(d, viewTarget);
ModelHelper.setClientElement(d, view);
StereotypesHelper.addStereotype(d, presentsS);
return viewTarget;
}
return null;
}
private void setPackageHierarchy(Set<Element> skipped) {
for (Element view: view2pac.keySet()) {
Type viewt = (Type)view;
Element parentView = null;
Package parentPack = null;
if (StereotypesHelper.hasStereotypeOrDerived(view, productS)) {
if (!(view.getOwner() instanceof Package)) {
ValidationRuleViolation vrv = new ValidationRuleViolation(view, "[DOCUMENT OWNER] A document should be owned by a package.");
docPackage.addViolation(vrv);
Element owner = view.getOwner();
while (!(owner instanceof Package)) {
owner = owner.getOwner();
}
parentPack = (Package)owner;
} else
parentPack = (Package)view.getOwner();
} else {
for (TypedElement t: viewt.get_typedElementOfType()) {
if (t instanceof Property && ((Property)t).getAggregation().equals(AggregationKindEnum.COMPOSITE) &&
StereotypesHelper.hasStereotypeOrDerived(t.getOwner(), viewS)) {
if (parentView != null) {
ValidationRuleViolation vrv = new ValidationRuleViolation(view, "[CANONICAL PARENT] This view has multiple parent views that uses composition");
viewParent.addViolation(vrv);
break;
}
parentView = t.getOwner();
}
}
}
if (parentPack == null) {
if (parentView != null) {
if (view2pac.containsKey(parentView))
parentPack = view2pac.get(parentView);
else {
List<Element> results = Utils.collectDirectedRelatedElementsByRelationshipStereotype(parentView, presentsS, 1, false, 1);
if (!results.isEmpty() && results.get(0) instanceof Package && !ProjectUtilities.isElementInAttachedProject(results.get(0))) {
parentPack = (Package)results.get(0);
} else
parentPack = viewInstancesPackage;
}
} else {
parentPack = viewInstancesPackage;
}
}
Package currentPack = view2pac.get(view);
if (currentPack.getOwner() != parentPack) {
if (currentPack.isEditable())
currentPack.setOwner(parentPack);
else {
ValidationRuleViolation vrv = new ValidationRuleViolation(currentPack, "[NOT EDITABLE (OWNER)] View instance package cannot be moved to right hierarchy");
uneditableOwner.addViolation(vrv);
}
}
}
}
private Package createViewInstancesPackage() {
// fix root element, set it to project instead
return createParticularPackage(Utils.getRootElement(), viewInstPrefix, "View Instances");
}
private Package createUnusedInstancesPackage() {
Package rootPackage = createParticularPackage(Utils.getRootElement(), viewInstPrefix, "View Instances");
return createParticularPackage(rootPackage, unusedInstPrefix, "Unused View Instances");
}
//get or create package with id
private Package createParticularPackage(Package owner, String packIDPrefix, String name) {
// fix root element, set it to project replace PROJECT with the packIDPrefix
String viewInstID = Utils.getProject().getPrimaryProject() .getProjectID().replace("PROJECT", packIDPrefix);
Package viewInst = (Package)Application.getInstance().getProject().getElementByID(viewInstID);
if (viewInst == null) {
Application.getInstance().getProject().getCounter().setCanResetIDForObject(true);
viewInst = ef.createPackageInstance();
viewInst.setID(viewInstID);
viewInst.setName(name);
}
// either way, set the owner to the owner we passed in
if (viewInst.isEditable() && viewInst.getOwner() != owner)
viewInst.setOwner(owner);
else if (viewInst.getOwner() != owner) {
//vlaidation error of trying to change owner but can't?
}
return viewInst;
}
}
| check for instance owner to be right view
| src/main/java/gov/nasa/jpl/mbee/generator/ViewPresentationGenerator.java | check for instance owner to be right view | <ide><path>rc/main/java/gov/nasa/jpl/mbee/generator/ViewPresentationGenerator.java
<ide> } else
<ide> needEdit = true;
<ide> }
<add> if (is.getOwner() != owner) {
<add> ValidationRuleViolation vrv = new ValidationRuleViolation(is, "[NOT EDITABLE (OWNER)] This presentation element instance's owning view instance package can't be updated.");
<add> uneditableOwner.addViolation(vrv);
<add> }
<ide> if (needEdit) {
<ide> ValidationRuleViolation vrv = new ValidationRuleViolation(is, "[NOT EDITABLE (CONTENT)] This presentation element instance can't be updated.");
<ide> uneditableContent.addViolation(vrv); |
|
Java | lgpl-2.1 | 0afd152bf56a7d41441fe375870d66ae23ed1473 | 0 | kaffe/kaffe,kaffe/kaffe,kaffe/kaffe,kaffe/kaffe,kaffe/kaffe | /*
* Java core library component.
*
* Copyright (c) 1997, 1998
* Transvirtual Technologies, Inc. All rights reserved.
*
* See the file "license.terms" for information on usage and redistribution
* of this file.
*/
package java.io;
import java.lang.String;
public class StreamTokenizer {
final public static int TT_EOF = -1;
final public static int TT_EOL = '\n';
final public static int TT_NUMBER = -2;
final public static int TT_WORD = -3;
public int ttype;
public String sval;
public double nval;
private PushbackReader pushIn;
private BufferedReader bufferedIn;
private Reader rawIn;
private TableEntry lookup[] = new TableEntry[256];
private TableEntry ordinary = new TableEntry();
private boolean pushBack;
private boolean EOLSignificant;
private boolean CComments;
private boolean CPlusPlusComments;
private boolean toLower;
private StringBuffer buffer = new StringBuffer();
private boolean endOfFile;
private boolean EOLPushedBack;
private int lineNumber = 1;
/**
* @deprecated
*/
public StreamTokenizer (InputStream i) {
this(new InputStreamReader(i));
}
public StreamTokenizer(Reader r) {
rawIn = r;
bufferedIn = new BufferedReader(rawIn);
pushIn = new PushbackReader(bufferedIn);
for (int i = 0; i < lookup.length; i++) {
lookup[i] = new TableEntry();
}
init();
}
private int chrRead() throws IOException {
if (endOfFile) {
return (-1);
}
else {
return (pushIn.read());
}
}
private void unRead(int c) throws IOException {
/* do not push EOF back --- it would show up as 65535 the next time */
if (c == -1) {
endOfFile = true;
} else {
pushIn.unread(c);
}
}
public void commentChar(int ch) {
if (ch >= 0 && ch <= 255) {
lookup(ch).isComment = true;
}
}
public void eolIsSignificant(boolean flag) {
EOLSignificant = flag;
}
public int lineno() {
return (lineNumber);
}
public void lowerCaseMode(boolean fl) {
toLower = fl;
}
public int nextToken() throws IOException {
if (pushBack == true) {
/* Do nothing */
pushBack = false;
}
else {
/* pushBack is false,
* so get the next token type
*/
nextTokenType();
}
return (ttype);
}
private void nextTokenType() throws IOException {
/* Sets ttype to the type of the next token */
int chr = chrRead();
TableEntry e = lookup(chr);
if (e.isWhitespace) {
/* Skip whitespace and return nextTokenType */
parseWhitespaceChars(chr);
}
else if (e.isNumeric) {
/* Parse the number and return */
parseNumericChars(chr);
}
else if (e.isAlphabetic) {
/* Parse the word and return */
parseAlphabeticChars(chr);
}
else if (e.isComment) {
/* skip comment and return nextTokenType() */
parseCommentChars();
}
else if (e.isStringQuote) {
/* Parse string and return word */
parseStringQuoteChars(chr);
}
else if (chr=='/' && CPlusPlusComments
&& parseCPlusPlusCommentChars()) {
/* Check for C++ comments */
}
else if (chr=='/' && CComments
&& parseCCommentChars()) {
/* Check for C comments */
}
else {
/* Just return it as a token */
sval = null;
if (chr == -1) {
ttype = TT_EOF;
}
else {
ttype = chr;
}
}
}
private boolean EOLParsed(int chr) {
/* Checks whether chr is an EOL character
like \r, \n.
Returns true if that's the case, false
otherwise.
*/
if (chr == '\r' || chr == '\n') {
return true;
}
else {
return false;
}
}
private void skipEOL(int chr) throws IOException {
/* Skips the \r in \r\n.
*/
if (chr == '\r') {
chr = chrRead();
if (chr != '\n') {
unRead(chr);
}
}
}
private void parseWhitespaceChars(int chr) throws IOException {
do {
if (EOLParsed(chr)) {
lineNumber ++;
skipEOL(chr);
if (EOLSignificant) {
ttype = TT_EOL;
return;
}
}
chr = chrRead();
} while (chr != -1 && lookup(chr).isWhitespace);
/* For next time */
unRead(chr);
nextTokenType();
}
private void parseNumericChars(int chr) throws IOException {
boolean dotParsed = false;
buffer.setLength( 0);
/* Parse characters until a non-numeric character,
* or the first '-' after the first character, or
* the second decimal dot is parsed.
*/
do {
if (chr == '.') {
if (dotParsed) {
/* Second decimal dot parsed,
* so the number is finished.
*/
break;
}
else {
/* First decimal dot parsed */
dotParsed = true;
}
}
buffer.append((char)chr);
chr = chrRead();
} while (lookup(chr).isNumeric
&& chr != '-'
&& !(chr == '.' && dotParsed));
/* For next time */
unRead(chr);
try {
nval = Double.parseDouble(buffer.toString());
ttype = TT_NUMBER;
}
catch ( NumberFormatException x) {
if (buffer.toString().equals("-")) {
/* if the first character was an '-'
* but no other numeric characters followed
*/
ttype = '-';
}
else if (buffer.toString().equals(".")) {
/* A sole decimal dot is parsed as the
* decimal number 0.0 according to what the
* JDK 1.1 does.
*/
ttype = TT_NUMBER;
nval = 0.0;
}
else {
/* A minus and a decimal dot are parsed as the
* decimal number -0.0 according to what the
* JDK 1.1 does.
*/
ttype = TT_NUMBER;
nval = -0.0;
}
}
}
private void parseAlphabeticChars(int chr) throws IOException {
buffer.setLength( 0);
while (lookup(chr).isAlphabetic || lookup(chr).isNumeric) {
buffer.append((char)chr);
chr = chrRead();
}
/* For next time */
unRead(chr);
ttype = TT_WORD;
sval = buffer.toString();
if (toLower) {
sval = sval.toLowerCase();
}
}
private void parseCommentChars() throws IOException {
skipLine();
nextTokenType();
}
private void parseStringQuoteChars(int chr) throws IOException {
int cq = chr;
buffer.setLength(0);
chr = chrRead();
while ( chr != cq && !(EOLParsed(chr)) && chr != -1) {
if ( chr == '\\' ) {
chr = chrRead();
switch (chr) {
case 'a':
chr = 0x7;
break;
case 'b':
chr = '\b';
break;
case 'f':
chr = 0xC;
break;
case 'n':
chr = '\n';
break;
case 'r':
chr = '\r';
break;
case 't':
chr = '\t';
break;
case 'v':
chr = 0xB;
break;
default:
if ('0' <= chr && chr <= '7') {
/* it's an octal escape */
chr = parseOctalEscape(chr);
}
}
}
buffer.append((char)chr);
chr = chrRead();
}
if (EOLParsed(chr)) {
unRead(chr);
}
/* JDK doc says: When the nextToken method encounters a
* string constant, the ttype field is set to the string
* delimiter and the sval field is set to the body of the
* string.
*/
ttype = cq;
sval = buffer.toString();
}
private boolean parseCPlusPlusCommentChars() throws IOException {
int next = chrRead();
if (next == '/') {
/* C++ comment */
skipLine();
nextTokenType();
return true;
}
else {
unRead(next);
return false;
}
}
private boolean parseCCommentChars() throws IOException {
int next = chrRead();
if (next == '*') {
/* C comment */
skipCComment();
nextTokenType();
return true;
}
else {
unRead(next);
return false;
}
}
private int parseOctalEscape(int chr) throws IOException {
int value = 0;
int digits = 1;
boolean maybeThreeOctalDigits = false;
/* There could be one, two, or three octal
* digits specifying a character's code.
* If it's three digits, the Java Language
* Specification says that the first one has
* to be in the range between '0' and '3'.
*/
if ('0' <= chr && chr <= '3') {
maybeThreeOctalDigits = true;
}
do {
value = value * 8 + Character.digit((char) chr, 8);
chr = chrRead();
digits++;
} while (('0' <= chr && chr <= '7')
&& (digits <= 2 || maybeThreeOctalDigits)
&& (digits <= 3));
unRead(chr);
return (value);
}
public void ordinaryChar(int c) {
if (c >= 0 && c <= 255) {
TableEntry e = lookup(c);
e.isAlphabetic = false;
e.isStringQuote = false;
e.isNumeric = false;
e.isComment = false;
e.isWhitespace = false;
}
}
public void ordinaryChars(int low, int hi) {
if (low < 0) {
low = 0;
}
if (hi > 255) {
hi = 255;
}
for (int letter=low; letter<=hi; letter++) {
ordinaryChar(letter);
}
}
public void parseNumbers() {
for (int letter = '0'; letter <= '9'; letter++) {
lookup(letter).isNumeric = true;
}
lookup('.').isNumeric = true;
lookup('-').isNumeric = true;
}
public void pushBack() {
pushBack = true;
}
public void quoteChar(int ch) {
if (ch >= 0 && ch <= 255) {
lookup(ch).isStringQuote = true;
}
}
private void init() {
wordChars('A', 'Z');
wordChars('a', 'z');
wordChars('\u00A0', '\u00FF');
whitespaceChars('\u0000', '\u0020');
parseNumbers();
commentChar('/');
quoteChar('\'');
quoteChar('"');
EOLSignificant = false;
CComments = false;
CPlusPlusComments = false;
toLower = false;
}
public void resetSyntax() {
ordinaryChars('\u0000', '\u00FF');
}
private void skipCComment() throws IOException {
for (;;) {
int chr = chrRead();
if (EOLParsed(chr)) {
lineNumber ++;
skipEOL(chr);
}
else if (chr == '*') {
int next = chrRead();
if (next=='/') {
break;
}
else {
unRead(next);
}
}
else if (chr == -1) {
break;
}
}
}
private void skipLine() throws IOException {
/* Skip all characters to the end of line or EOF,
* whichever comes first.
*/
int chr = chrRead();
while (!EOLParsed(chr) && chr != -1)
chr = chrRead();
if (EOLParsed(chr)) {
unRead(chr);
}
}
public void slashSlashComments(boolean flag) {
CPlusPlusComments = flag;
}
public void slashStarComments(boolean flag) {
CComments = flag;
}
public String toString() {
if (ttype == TT_EOF) {
return ("Token[EOF], line "+lineno());
}
else if (ttype == TT_EOL) {
return ("Token[EOL], line "+lineno());
}
else if (ttype == TT_NUMBER) {
return ("Token[n="+nval+"], line "+lineno());
}
else if (ttype == TT_WORD) {
return ("Token["+sval+"], line "+lineno());
}
else {
return ("Token[\'"+ (char) ttype +"\'], line "+lineno());
}
}
public void whitespaceChars(int low, int hi) {
if (low < 0) {
low = 0;
}
if (hi > 255) {
hi = 255;
}
for (int letter = low; letter <= hi; letter++) {
TableEntry e = lookup(letter);
e.isWhitespace = true;
e.isAlphabetic = false;
e.isNumeric = false;
}
}
public void wordChars(int low, int hi) {
if (low < 0) {
low = 0;
}
if (hi > 255) {
hi = 255;
}
for (int letter = low; letter <= hi; letter++) {
lookup(letter).isAlphabetic = true;
}
}
private TableEntry lookup(int letter) {
if (letter < 0 || letter > 255) {
return (ordinary);
}
return (lookup[letter]);
}
class TableEntry {
private boolean isNumeric = false;
private boolean isWhitespace = false;
private boolean isAlphabetic = false;
private boolean isStringQuote = false;
private boolean isComment = false;
}
}
| libraries/javalib/java/io/StreamTokenizer.java | /*
* Java core library component.
*
* Copyright (c) 1997, 1998
* Transvirtual Technologies, Inc. All rights reserved.
*
* See the file "license.terms" for information on usage and redistribution
* of this file.
*/
package java.io;
import java.lang.String;
public class StreamTokenizer {
final public static int TT_EOF = -1;
final public static int TT_EOL = '\n';
final public static int TT_NUMBER = -2;
final public static int TT_WORD = -3;
public int ttype;
public String sval;
public double nval;
private PushbackReader pushIn;
private BufferedReader bufferedIn;
private Reader rawIn;
private TableEntry lookup[] = new TableEntry[256];
private TableEntry ordinary = new TableEntry();
private boolean pushBack;
private boolean EOLSignificant;
private boolean CComments;
private boolean CPlusPlusComments;
private boolean toLower;
private StringBuffer buffer = new StringBuffer();
private boolean endOfFile;
private boolean EOLPushedBack;
private int lineNumber = 1;
/**
* @deprecated
*/
public StreamTokenizer (InputStream i) {
this(new InputStreamReader(i));
}
public StreamTokenizer(Reader r) {
rawIn = r;
bufferedIn = new BufferedReader(rawIn);
pushIn = new PushbackReader(bufferedIn);
for (int i = 0; i < lookup.length; i++) {
lookup[i] = new TableEntry();
}
init();
}
private int chrRead() throws IOException {
if (endOfFile) {
return (-1);
}
else {
return (pushIn.read());
}
}
private void unRead(int c) throws IOException {
/* do not push EOF back --- it would show up as 65535 the next time */
if (c == -1) {
endOfFile = true;
} else {
pushIn.unread(c);
}
}
public void commentChar(int ch) {
if (ch >= 0 && ch <= 255) {
lookup(ch).isComment = true;
}
}
public void eolIsSignificant(boolean flag) {
EOLSignificant = flag;
}
public int lineno() {
return (lineNumber);
}
public void lowerCaseMode(boolean fl) {
toLower = fl;
}
public int nextToken() throws IOException {
if (pushBack == true) {
/* Do nothing */
pushBack = false;
}
else {
/* pushBack is false,
* so get the next token type
*/
nextTokenType();
}
return (ttype);
}
private void nextTokenType() throws IOException {
/* Sets ttype to the type of the next token */
int chr = chrRead();
TableEntry e = lookup(chr);
if (e.isWhitespace) {
/* Skip whitespace and return nextTokenType */
parseWhitespaceChars(chr);
}
else if (e.isNumeric) {
/* Parse the number and return */
parseNumericChars(chr);
}
else if (e.isAlphabetic) {
/* Parse the word and return */
parseAlphabeticChars(chr);
}
else if (e.isComment) {
/* skip comment and return nextTokenType() */
parseCommentChars();
}
else if (e.isStringQuote) {
/* Parse string and return word */
parseStringQuoteChars(chr);
}
else if (chr=='/' && CPlusPlusComments) {
/* Check for C++ comments */
parseCPlusPlusCommentChars();
}
else if (chr=='/' && CComments) {
/* Check for C comments */
parseCCommentChars();
}
else {
/* Just return it as a token */
sval = null;
if (chr == -1) {
ttype = TT_EOF;
}
else {
ttype = chr;
}
}
}
private boolean EOLParsed(int chr) {
/* Checks whether chr is an EOL character
like \r, \n.
Returns true if that's the case, false
otherwise.
*/
if (chr == '\r' || chr == '\n') {
return true;
}
else {
return false;
}
}
private void skipEOL(int chr) throws IOException {
/* Skips the \r in \r\n.
*/
if (chr == '\r') {
chr = chrRead();
if (chr != '\n') {
unRead(chr);
}
}
}
private void parseWhitespaceChars(int chr) throws IOException {
do {
if (EOLParsed(chr)) {
lineNumber ++;
skipEOL(chr);
if (EOLSignificant) {
ttype = TT_EOL;
return;
}
}
chr = chrRead();
} while (chr != -1 && lookup(chr).isWhitespace);
/* For next time */
unRead(chr);
nextTokenType();
}
private void parseNumericChars(int chr) throws IOException {
boolean dotParsed = false;
buffer.setLength( 0);
/* Parse characters until a non-numeric character,
* or the first '-' after the first character, or
* the second decimal dot is parsed.
*/
do {
if (chr == '.') {
if (dotParsed) {
/* Second decimal dot parsed,
* so the number is finished.
*/
break;
}
else {
/* First decimal dot parsed */
dotParsed = true;
}
}
buffer.append((char)chr);
chr = chrRead();
} while (lookup(chr).isNumeric
&& chr != '-'
&& !(chr == '.' && dotParsed));
/* For next time */
unRead(chr);
try {
nval = Double.parseDouble(buffer.toString());
ttype = TT_NUMBER;
}
catch ( NumberFormatException x) {
if (buffer.toString().equals("-")) {
/* if the first character was an '-'
* but no other numeric characters followed
*/
ttype = '-';
}
else if (buffer.toString().equals(".")) {
/* A sole decimal dot is parsed as the
* decimal number 0.0 according to what the
* JDK 1.1 does.
*/
ttype = TT_NUMBER;
nval = 0.0;
}
else {
/* A minus and a decimal dot are parsed as the
* decimal number -0.0 according to what the
* JDK 1.1 does.
*/
ttype = TT_NUMBER;
nval = -0.0;
}
}
}
private void parseAlphabeticChars(int chr) throws IOException {
buffer.setLength( 0);
while (lookup(chr).isAlphabetic || lookup(chr).isNumeric) {
buffer.append((char)chr);
chr = chrRead();
}
/* For next time */
unRead(chr);
ttype = TT_WORD;
sval = buffer.toString();
if (toLower) {
sval = sval.toLowerCase();
}
}
private void parseCommentChars() throws IOException {
skipLine();
nextTokenType();
}
private void parseStringQuoteChars(int chr) throws IOException {
int cq = chr;
buffer.setLength(0);
chr = chrRead();
while ( chr != cq && !(EOLParsed(chr)) && chr != -1) {
if ( chr == '\\' ) {
chr = chrRead();
switch (chr) {
case 'a':
chr = 0x7;
break;
case 'b':
chr = '\b';
break;
case 'f':
chr = 0xC;
break;
case 'n':
chr = '\n';
break;
case 'r':
chr = '\r';
break;
case 't':
chr = '\t';
break;
case 'v':
chr = 0xB;
break;
default:
if ('0' <= chr && chr <= '7') {
/* it's an octal escape */
chr = parseOctalEscape(chr);
}
}
}
buffer.append((char)chr);
chr = chrRead();
}
if (EOLParsed(chr)) {
unRead(chr);
}
/* JDK doc says: When the nextToken method encounters a
* string constant, the ttype field is set to the string
* delimiter and the sval field is set to the body of the
* string.
*/
ttype = cq;
sval = buffer.toString();
}
private void parseCPlusPlusCommentChars() throws IOException {
int next = chrRead();
if (next == '/') {
/* C++ comment */
skipLine();
nextTokenType();
}
else {
unRead(next);
ttype = '/';
}
}
private void parseCCommentChars() throws IOException {
int next = chrRead();
if (next == '*') {
/* C comment */
skipCComment();
nextTokenType();
}
else {
unRead(next);
ttype = '/';
}
}
private int parseOctalEscape(int chr) throws IOException {
int value = 0;
int digits = 1;
boolean maybeThreeOctalDigits = false;
/* There could be one, two, or three octal
* digits specifying a character's code.
* If it's three digits, the Java Language
* Specification says that the first one has
* to be in the range between '0' and '3'.
*/
if ('0' <= chr && chr <= '3') {
maybeThreeOctalDigits = true;
}
do {
value = value * 8 + Character.digit((char) chr, 8);
chr = chrRead();
digits++;
} while (('0' <= chr && chr <= '7')
&& (digits <= 2 || maybeThreeOctalDigits)
&& (digits <= 3));
unRead(chr);
return (value);
}
public void ordinaryChar(int c) {
if (c >= 0 && c <= 255) {
TableEntry e = lookup(c);
e.isAlphabetic = false;
e.isStringQuote = false;
e.isNumeric = false;
e.isComment = false;
e.isWhitespace = false;
}
}
public void ordinaryChars(int low, int hi) {
if (low < 0) {
low = 0;
}
if (hi > 255) {
hi = 255;
}
for (int letter=low; letter<=hi; letter++) {
ordinaryChar(letter);
}
}
public void parseNumbers() {
for (int letter = '0'; letter <= '9'; letter++) {
lookup(letter).isNumeric = true;
}
lookup('.').isNumeric = true;
lookup('-').isNumeric = true;
}
public void pushBack() {
pushBack = true;
}
public void quoteChar(int ch) {
if (ch >= 0 && ch <= 255) {
lookup(ch).isStringQuote = true;
}
}
private void init() {
wordChars('A', 'Z');
wordChars('a', 'z');
wordChars('\u00A0', '\u00FF');
whitespaceChars('\u0000', '\u0020');
parseNumbers();
commentChar('/');
quoteChar('\'');
quoteChar('"');
EOLSignificant = false;
CComments = false;
CPlusPlusComments = false;
toLower = false;
}
public void resetSyntax() {
ordinaryChars('\u0000', '\u00FF');
}
private void skipCComment() throws IOException {
for (;;) {
int chr = chrRead();
if (EOLParsed(chr)) {
lineNumber ++;
skipEOL(chr);
}
else if (chr == '*') {
int next = chrRead();
if (next=='/') {
break;
}
else {
unRead(next);
}
}
else if (chr == -1) {
break;
}
}
}
private void skipLine() throws IOException {
/* Skip all characters to the end of line or EOF,
* whichever comes first.
*/
int chr = chrRead();
while (!EOLParsed(chr) && chr != -1)
chr = chrRead();
if (EOLParsed(chr)) {
unRead(chr);
}
}
public void slashSlashComments(boolean flag) {
CPlusPlusComments = flag;
}
public void slashStarComments(boolean flag) {
CComments = flag;
}
public String toString() {
if (ttype == TT_EOF) {
return ("Token[EOF], line "+lineno());
}
else if (ttype == TT_EOL) {
return ("Token[EOL], line "+lineno());
}
else if (ttype == TT_NUMBER) {
return ("Token[n="+nval+"], line "+lineno());
}
else if (ttype == TT_WORD) {
return ("Token["+sval+"], line "+lineno());
}
else {
return ("Token[\'"+ (char) ttype +"\'], line "+lineno());
}
}
public void whitespaceChars(int low, int hi) {
if (low < 0) {
low = 0;
}
if (hi > 255) {
hi = 255;
}
for (int letter = low; letter <= hi; letter++) {
TableEntry e = lookup(letter);
e.isWhitespace = true;
e.isAlphabetic = false;
e.isNumeric = false;
}
}
public void wordChars(int low, int hi) {
if (low < 0) {
low = 0;
}
if (hi > 255) {
hi = 255;
}
for (int letter = low; letter <= hi; letter++) {
lookup(letter).isAlphabetic = true;
}
}
private TableEntry lookup(int letter) {
if (letter < 0 || letter > 255) {
return (ordinary);
}
return (lookup[letter]);
}
class TableEntry {
private boolean isNumeric = false;
private boolean isWhitespace = false;
private boolean isAlphabetic = false;
private boolean isStringQuote = false;
private boolean isComment = false;
}
}
| Fix bugs parsing C and C++ comment characters.
Submitted by: Tatu Saloranta <[email protected]>
| libraries/javalib/java/io/StreamTokenizer.java | Fix bugs parsing C and C++ comment characters. | <ide><path>ibraries/javalib/java/io/StreamTokenizer.java
<ide> /* Parse string and return word */
<ide> parseStringQuoteChars(chr);
<ide> }
<del> else if (chr=='/' && CPlusPlusComments) {
<add> else if (chr=='/' && CPlusPlusComments
<add> && parseCPlusPlusCommentChars()) {
<ide> /* Check for C++ comments */
<del> parseCPlusPlusCommentChars();
<del> }
<del> else if (chr=='/' && CComments) {
<add> }
<add> else if (chr=='/' && CComments
<add> && parseCCommentChars()) {
<ide> /* Check for C comments */
<del> parseCCommentChars();
<ide> }
<ide> else {
<ide> /* Just return it as a token */
<ide> sval = buffer.toString();
<ide> }
<ide>
<del>private void parseCPlusPlusCommentChars() throws IOException {
<add>private boolean parseCPlusPlusCommentChars() throws IOException {
<ide> int next = chrRead();
<ide> if (next == '/') {
<ide> /* C++ comment */
<ide> skipLine();
<ide>
<ide> nextTokenType();
<add> return true;
<ide> }
<ide> else {
<ide> unRead(next);
<del>
<del> ttype = '/';
<del> }
<del>}
<del>
<del>private void parseCCommentChars() throws IOException {
<add> return false;
<add> }
<add>}
<add>
<add>private boolean parseCCommentChars() throws IOException {
<ide> int next = chrRead();
<ide> if (next == '*') {
<ide> /* C comment */
<ide> skipCComment();
<ide>
<ide> nextTokenType();
<add> return true;
<ide> }
<ide> else {
<ide> unRead(next);
<del>
<del> ttype = '/';
<add> return false;
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | c7fb2f0b1f967be1a3e9ca4c2f1fc527a15c2d14 | 0 | ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt | 'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, ArgumentsRequired, NullResponse, InvalidOrder, NotSupported } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class cex extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'cex',
'name': 'CEX.IO',
'countries': [ 'GB', 'EU', 'CY', 'RU' ],
'rateLimit': 1500,
'has': {
'CORS': true,
'fetchTickers': true,
'fetchOHLCV': true,
'fetchOrder': true,
'fetchOpenOrders': true,
'fetchClosedOrders': true,
'fetchDepositAddress': true,
'fetchOrders': true,
},
'timeframes': {
'1m': '1m',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766442-8ddc33b0-5ed8-11e7-8b98-f786aef0f3c9.jpg',
'api': 'https://cex.io/api',
'www': 'https://cex.io',
'doc': 'https://cex.io/cex-api',
'fees': [
'https://cex.io/fee-schedule',
'https://cex.io/limits-commissions',
],
'referral': 'https://cex.io/r/0/up105393824/0/',
},
'requiredCredentials': {
'apiKey': true,
'secret': true,
'uid': true,
},
'api': {
'public': {
'get': [
'currency_limits/',
'last_price/{pair}/',
'last_prices/{currencies}/',
'ohlcv/hd/{yyyymmdd}/{pair}',
'order_book/{pair}/',
'ticker/{pair}/',
'tickers/{currencies}/',
'trade_history/{pair}/',
],
'post': [
'convert/{pair}',
'price_stats/{pair}',
],
},
'private': {
'post': [
'active_orders_status/',
'archived_orders/{pair}/',
'balance/',
'cancel_order/',
'cancel_orders/{pair}/',
'cancel_replace_order/{pair}/',
'close_position/{pair}/',
'get_address/',
'get_myfee/',
'get_order/',
'get_order_tx/',
'open_orders/{pair}/',
'open_orders/',
'open_position/{pair}/',
'open_positions/{pair}/',
'place_order/{pair}/',
],
},
},
'fees': {
'trading': {
'maker': 0.16 / 100,
'taker': 0.25 / 100,
},
'funding': {
'withdraw': {
// 'USD': undefined,
// 'EUR': undefined,
// 'RUB': undefined,
// 'GBP': undefined,
'BTC': 0.001,
'ETH': 0.01,
'BCH': 0.001,
'DASH': 0.01,
'BTG': 0.001,
'ZEC': 0.001,
'XRP': 0.02,
},
'deposit': {
// 'USD': amount => amount * 0.035 + 0.25,
// 'EUR': amount => amount * 0.035 + 0.24,
// 'RUB': amount => amount * 0.05 + 15.57,
// 'GBP': amount => amount * 0.035 + 0.2,
'BTC': 0.0,
'ETH': 0.0,
'BCH': 0.0,
'DASH': 0.0,
'BTG': 0.0,
'ZEC': 0.0,
'XRP': 0.0,
'XLM': 0.0,
},
},
},
'options': {
'fetchOHLCVWarning': true,
'createMarketBuyOrderRequiresPrice': true,
'order': {
'status': {
'c': 'canceled',
'd': 'closed',
'cd': 'closed',
'a': 'open',
},
},
},
});
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'limit': limit,
'pair': market['id'],
'dateFrom': since,
};
const response = await this.privatePostArchivedOrdersPair (this.extend (request, params));
const results = [];
for (let i = 0; i < response.length; i++) {
// cancelled (unfilled):
// { id: '4005785516',
// type: 'sell',
// time: '2017-07-18T19:08:34.223Z',
// lastTxTime: '2017-07-18T19:08:34.396Z',
// lastTx: '4005785522',
// pos: null,
// status: 'c',
// symbol1: 'ETH',
// symbol2: 'GBP',
// amount: '0.20000000',
// price: '200.5625',
// remains: '0.20000000',
// 'a:ETH:cds': '0.20000000',
// tradingFeeMaker: '0',
// tradingFeeTaker: '0.16',
// tradingFeeUserVolumeAmount: '10155061217',
// orderId: '4005785516' }
// --
// cancelled (partially filled buy):
// { id: '4084911657',
// type: 'buy',
// time: '2017-08-05T03:18:39.596Z',
// lastTxTime: '2019-03-19T17:37:46.404Z',
// lastTx: '8459265833',
// pos: null,
// status: 'cd',
// symbol1: 'BTC',
// symbol2: 'GBP',
// amount: '0.05000000',
// price: '2241.4692',
// tfacf: '1',
// remains: '0.03910535',
// 'tfa:GBP': '0.04',
// 'tta:GBP': '24.39',
// 'a:BTC:cds': '0.01089465',
// 'a:GBP:cds': '112.26',
// 'f:GBP:cds': '0.04',
// tradingFeeMaker: '0',
// tradingFeeTaker: '0.16',
// tradingFeeUserVolumeAmount: '13336396963',
// orderId: '4084911657' }
// --
// cancelled (partially filled sell):
// { id: '4426728375',
// type: 'sell',
// time: '2017-09-22T00:24:20.126Z',
// lastTxTime: '2017-09-22T00:24:30.476Z',
// lastTx: '4426729543',
// pos: null,
// status: 'cd',
// symbol1: 'BCH',
// symbol2: 'BTC',
// amount: '0.10000000',
// price: '0.11757182',
// tfacf: '1',
// remains: '0.09935956',
// 'tfa:BTC': '0.00000014',
// 'tta:BTC': '0.00007537',
// 'a:BCH:cds': '0.10000000',
// 'a:BTC:cds': '0.00007537',
// 'f:BTC:cds': '0.00000014',
// tradingFeeMaker: '0',
// tradingFeeTaker: '0.18',
// tradingFeeUserVolumeAmount: '3466715450',
// orderId: '4426728375' }
// --
// filled:
// { id: '5342275378',
// type: 'sell',
// time: '2018-01-04T00:28:12.992Z',
// lastTxTime: '2018-01-04T00:28:12.992Z',
// lastTx: '5342275393',
// pos: null,
// status: 'd',
// symbol1: 'BCH',
// symbol2: 'BTC',
// amount: '0.10000000',
// kind: 'api',
// price: '0.17',
// remains: '0.00000000',
// 'tfa:BTC': '0.00003902',
// 'tta:BTC': '0.01699999',
// 'a:BCH:cds': '0.10000000',
// 'a:BTC:cds': '0.01699999',
// 'f:BTC:cds': '0.00003902',
// tradingFeeMaker: '0.15',
// tradingFeeTaker: '0.23',
// tradingFeeUserVolumeAmount: '1525951128',
// orderId: '5342275378' }
// --
// market order (buy):
// { "id": "6281946200",
// "pos": null,
// "time": "2018-05-23T11:55:43.467Z",
// "type": "buy",
// "amount": "0.00000000",
// "lastTx": "6281946210",
// "status": "d",
// "amount2": "20.00",
// "orderId": "6281946200",
// "remains": "0.00000000",
// "symbol1": "ETH",
// "symbol2": "EUR",
// "tfa:EUR": "0.05",
// "tta:EUR": "19.94",
// "a:ETH:cds": "0.03764100",
// "a:EUR:cds": "20.00",
// "f:EUR:cds": "0.05",
// "lastTxTime": "2018-05-23T11:55:43.467Z",
// "tradingFeeTaker": "0.25",
// "tradingFeeUserVolumeAmount": "55998097" }
// --
// market order (sell):
// { "id": "6282200948",
// "pos": null,
// "time": "2018-05-23T12:42:58.315Z",
// "type": "sell",
// "amount": "-0.05000000",
// "lastTx": "6282200958",
// "status": "d",
// "orderId": "6282200948",
// "remains": "0.00000000",
// "symbol1": "ETH",
// "symbol2": "EUR",
// "tfa:EUR": "0.07",
// "tta:EUR": "26.49",
// "a:ETH:cds": "0.05000000",
// "a:EUR:cds": "26.49",
// "f:EUR:cds": "0.07",
// "lastTxTime": "2018-05-23T12:42:58.315Z",
// "tradingFeeTaker": "0.25",
// "tradingFeeUserVolumeAmount": "56294576" }
const item = response[i];
const status = this.parseOrderStatus (this.safeString (item, 'status'));
const baseId = item['symbol1'];
const quoteId = item['symbol2'];
const side = item['type'];
const baseAmount = this.safeFloat (item, 'a:' + baseId + ':cds');
const quoteAmount = this.safeFloat (item, 'a:' + quoteId + ':cds');
const fee = this.safeFloat (item, 'f:' + quoteId + ':cds');
const amount = this.safeFloat (item, 'amount');
let price = this.safeFloat (item, 'price');
const remaining = this.safeFloat (item, 'remains');
const filled = amount - remaining;
let orderAmount = undefined;
let cost = undefined;
let average = undefined;
let type = undefined;
if (!price) {
type = 'market';
orderAmount = baseAmount;
cost = quoteAmount;
average = orderAmount / cost;
} else {
const ta = this.safeFloat (item, 'ta:' + quoteId, 0);
const tta = this.safeFloat (item, 'tta:' + quoteId, 0);
const fa = this.safeFloat (item, 'fa:' + quoteId, 0);
const tfa = this.safeFloat (item, 'tfa:' + quoteId, 0);
if (side === 'sell')
cost = ta + tta + (fa + tfa);
else
cost = ta + tta - (fa + tfa);
type = 'limit';
orderAmount = amount;
average = cost / filled;
}
const time = this.safeString (item, 'time');
const lastTxTime = this.safeString (item, 'lastTxTime');
const timestamp = this.parse8601 (time);
results.push ({
'id': item['id'],
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastUpdated': this.parse8601 (lastTxTime),
'status': status,
'symbol': this.findSymbol (baseId + '/' + quoteId),
'side': side,
'price': price,
'amount': orderAmount,
'average': average,
'type': type,
'filled': filled,
'cost': cost,
'remaining': remaining,
'fee': {
'cost': fee,
'currency': this.currencyId (quoteId),
},
'info': item,
});
}
return results;
}
parseOrderStatus (status) {
return this.safeString (this.options['order']['status'], status, status);
}
async fetchMarkets (params = {}) {
let markets = await this.publicGetCurrencyLimits ();
let result = [];
for (let p = 0; p < markets['data']['pairs'].length; p++) {
let market = markets['data']['pairs'][p];
let id = market['symbol1'] + '/' + market['symbol2'];
let symbol = id;
let [ base, quote ] = symbol.split ('/');
result.push ({
'id': id,
'info': market,
'symbol': symbol,
'base': base,
'quote': quote,
'precision': {
'price': this.precisionFromString (this.safeString (market, 'minPrice')),
'amount': this.precisionFromString (this.safeString (market, 'minLotSize')),
},
'limits': {
'amount': {
'min': market['minLotSize'],
'max': market['maxLotSize'],
},
'price': {
'min': this.safeFloat (market, 'minPrice'),
'max': this.safeFloat (market, 'maxPrice'),
},
'cost': {
'min': market['minLotSizeS2'],
'max': undefined,
},
},
});
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let response = await this.privatePostBalance ();
let result = { 'info': response };
let ommited = [ 'username', 'timestamp' ];
let balances = this.omit (response, ommited);
let currencies = Object.keys (balances);
for (let i = 0; i < currencies.length; i++) {
let currency = currencies[i];
if (currency in balances) {
let account = {
'free': this.safeFloat (balances[currency], 'available', 0.0),
'used': this.safeFloat (balances[currency], 'orders', 0.0),
'total': 0.0,
};
account['total'] = this.sum (account['free'], account['used']);
result[currency] = account;
}
}
return this.parseBalance (result);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
let request = {
'pair': this.marketId (symbol),
};
if (limit !== undefined) {
request['depth'] = limit;
}
let orderbook = await this.publicGetOrderBookPair (this.extend (request, params));
let timestamp = orderbook['timestamp'] * 1000;
return this.parseOrderBook (orderbook, timestamp);
}
parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
return [
ohlcv[0] * 1000,
ohlcv[1],
ohlcv[2],
ohlcv[3],
ohlcv[4],
ohlcv[5],
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
if (since === undefined) {
since = this.milliseconds () - 86400000; // yesterday
} else {
if (this.options['fetchOHLCVWarning']) {
throw new ExchangeError (this.id + " fetchOHLCV warning: CEX can return historical candles for a certain date only, this might produce an empty or null reply. Set exchange.options['fetchOHLCVWarning'] = false or add ({ 'options': { 'fetchOHLCVWarning': false }}) to constructor params to suppress this warning message.");
}
}
let ymd = this.ymd (since);
ymd = ymd.split ('-');
ymd = ymd.join ('');
let request = {
'pair': market['id'],
'yyyymmdd': ymd,
};
try {
let response = await this.publicGetOhlcvHdYyyymmddPair (this.extend (request, params));
let key = 'data' + this.timeframes[timeframe];
let ohlcvs = JSON.parse (response[key]);
return this.parseOHLCVs (ohlcvs, market, timeframe, since, limit);
} catch (e) {
if (e instanceof NullResponse) {
return [];
}
}
}
parseTicker (ticker, market = undefined) {
let timestamp = undefined;
if ('timestamp' in ticker) {
timestamp = parseInt (ticker['timestamp']) * 1000;
}
let volume = this.safeFloat (ticker, 'volume');
let high = this.safeFloat (ticker, 'high');
let low = this.safeFloat (ticker, 'low');
let bid = this.safeFloat (ticker, 'bid');
let ask = this.safeFloat (ticker, 'ask');
let last = this.safeFloat (ticker, 'last');
let symbol = undefined;
if (market)
symbol = market['symbol'];
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': high,
'low': low,
'bid': bid,
'bidVolume': undefined,
'ask': ask,
'askVolume': undefined,
'vwap': undefined,
'open': undefined,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': volume,
'quoteVolume': undefined,
'info': ticker,
};
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
let currencies = Object.keys (this.currencies);
let response = await this.publicGetTickersCurrencies (this.extend ({
'currencies': currencies.join ('/'),
}, params));
let tickers = response['data'];
let result = {};
for (let t = 0; t < tickers.length; t++) {
let ticker = tickers[t];
let symbol = ticker['pair'].replace (':', '/');
let market = this.markets[symbol];
result[symbol] = this.parseTicker (ticker, market);
}
return result;
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let ticker = await this.publicGetTickerPair (this.extend ({
'pair': market['id'],
}, params));
return this.parseTicker (ticker, market);
}
parseTrade (trade, market = undefined) {
let timestamp = parseInt (trade['date']) * 1000;
return {
'info': trade,
'id': trade['tid'],
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': market['symbol'],
'type': undefined,
'side': trade['type'],
'price': this.safeFloat (trade, 'price'),
'amount': this.safeFloat (trade, 'amount'),
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.publicGetTradeHistoryPair (this.extend ({
'pair': market['id'],
}, params));
return this.parseTrades (response, market, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
if (type === 'market') {
// for market buy it requires the amount of quote currency to spend
if (side === 'buy') {
if (this.options['createMarketBuyOrderRequiresPrice']) {
if (price === undefined) {
throw new InvalidOrder (this.id + " createOrder() requires the price argument with market buy orders to calculate total order cost (amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options['createMarketBuyOrderRequiresPrice'] = false to supply the cost in the amount argument (the exchange-specific behaviour)");
} else {
amount = amount * price;
}
}
}
}
await this.loadMarkets ();
let request = {
'pair': this.marketId (symbol),
'type': side,
'amount': amount,
};
if (type === 'limit') {
request['price'] = price;
} else {
request['order_type'] = type;
}
let response = await this.privatePostPlaceOrderPair (this.extend (request, params));
return {
'info': response,
'id': response['id'],
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
return await this.privatePostCancelOrder ({ 'id': id });
}
parseOrderStatus (status) {
const statuses = {
'a': 'open',
'cd': 'canceled',
'c': 'canceled',
'd': 'closed',
};
return this.safeValue (statuses, status, status);
}
parseOrder (order, market = undefined) {
// Depending on the call, 'time' can be a unix int, unix string or ISO string
// Yes, really
let timestamp = this.safeValue (order, 'time');
if (typeof timestamp === 'string' && timestamp.indexOf ('T') >= 0) {
// ISO8601 string
timestamp = this.parse8601 (timestamp);
} else {
// either integer or string integer
timestamp = parseInt (timestamp);
}
let symbol = undefined;
if (market === undefined) {
let symbol = order['symbol1'] + '/' + order['symbol2'];
if (symbol in this.markets)
market = this.market (symbol);
}
let status = order['status'];
if (status === 'a') {
status = 'open'; // the unified status
} else if (status === 'cd') {
status = 'canceled';
} else if (status === 'c') {
status = 'canceled';
} else if (status === 'd') {
status = 'closed';
}
let price = this.safeFloat (order, 'price');
let amount = this.safeFloat (order, 'amount');
let remaining = this.safeFloat (order, 'pending');
if (!remaining)
remaining = this.safeFloat (order, 'remains');
let filled = amount - remaining;
let fee = undefined;
let cost = undefined;
if (market !== undefined) {
symbol = market['symbol'];
cost = this.safeFloat (order, 'ta:' + market['quote']);
if (cost === undefined)
cost = this.safeFloat (order, 'tta:' + market['quote']);
let baseFee = 'fa:' + market['base'];
let baseTakerFee = 'tfa:' + market['base'];
let quoteFee = 'fa:' + market['quote'];
let quoteTakerFee = 'tfa:' + market['quote'];
let feeRate = this.safeFloat (order, 'tradingFeeMaker');
if (!feeRate)
feeRate = this.safeFloat (order, 'tradingFeeTaker', feeRate);
if (feeRate)
feeRate /= 100.0; // convert to mathematically-correct percentage coefficients: 1.0 = 100%
if ((baseFee in order) || (baseTakerFee in order)) {
let baseFeeCost = this.safeFloat (order, baseFee);
if (baseFeeCost === undefined)
baseFeeCost = this.safeFloat (order, baseTakerFee);
fee = {
'currency': market['base'],
'rate': feeRate,
'cost': baseFeeCost,
};
} else if ((quoteFee in order) || (quoteTakerFee in order)) {
let quoteFeeCost = this.safeFloat (order, quoteFee);
if (quoteFeeCost === undefined)
quoteFeeCost = this.safeFloat (order, quoteTakerFee);
fee = {
'currency': market['quote'],
'rate': feeRate,
'cost': quoteFeeCost,
};
}
}
if (!cost)
cost = price * filled;
const side = order['type'];
let trades = undefined;
const orderId = order['id'];
if ('vtx' in order) {
trades = [];
for (let i = 0; i < order['vtx'].length; i++) {
const item = order['vtx'][i];
const tradeSide = this.safeString (item, 'type');
if (item['type'] === 'cancel') {
// looks like this might represent the cancelled part of an order
// { id: '4426729543',
// type: 'cancel',
// time: '2017-09-22T00:24:30.476Z',
// user: 'up106404164',
// c: 'user:up106404164:a:BCH',
// d: 'order:4426728375:a:BCH',
// a: '0.09935956',
// amount: '0.09935956',
// balance: '0.42580261',
// symbol: 'BCH',
// order: '4426728375',
// buy: null,
// sell: null,
// pair: null,
// pos: null,
// cs: '0.42580261',
// ds: 0 }
continue;
}
if (!item['price']) {
// this represents the order
// {
// "a": "0.47000000",
// "c": "user:up106404164:a:EUR",
// "d": "order:6065499239:a:EUR",
// "cs": "1432.93",
// "ds": "476.72",
// "id": "6065499249",
// "buy": null,
// "pos": null,
// "pair": null,
// "sell": null,
// "time": "2018-04-22T13:07:22.152Z",
// "type": "buy",
// "user": "up106404164",
// "order": "6065499239",
// "amount": "-715.97000000",
// "symbol": "EUR",
// "balance": "1432.93000000" }
continue;
}
// if (item['type'] === 'costsNothing')
// console.log (item);
// todo: deal with these
if (item['type'] === 'costsNothing')
continue;
// --
// if (side !== tradeSide)
// throw Error (JSON.stringify (order, null, 2));
// if (orderId !== item['order'])
// throw Error (JSON.stringify (order, null, 2));
// --
// partial buy trade
// {
// "a": "0.01589885",
// "c": "user:up106404164:a:BTC",
// "d": "order:6065499239:a:BTC",
// "cs": "0.36300000",
// "ds": 0,
// "id": "6067991213",
// "buy": "6065499239",
// "pos": null,
// "pair": null,
// "sell": "6067991206",
// "time": "2018-04-22T23:09:11.773Z",
// "type": "buy",
// "user": "up106404164",
// "order": "6065499239",
// "price": 7146.5,
// "amount": "0.01589885",
// "symbol": "BTC",
// "balance": "0.36300000",
// "symbol2": "EUR",
// "fee_amount": "0.19" }
// --
// trade with zero amount, but non-zero fee
// {
// "a": "0.00000000",
// "c": "user:up106404164:a:EUR",
// "d": "order:5840654423:a:EUR",
// "cs": 559744,
// "ds": 0,
// "id": "5840654429",
// "buy": "5807238573",
// "pos": null,
// "pair": null,
// "sell": "5840654423",
// "time": "2018-03-15T03:20:14.010Z",
// "type": "sell",
// "user": "up106404164",
// "order": "5840654423",
// "price": 730,
// "amount": "0.00000000",
// "symbol": "EUR",
// "balance": "5597.44000000",
// "symbol2": "BCH",
// "fee_amount": "0.01" }
const tradeTime = this.safeString (item, 'time');
const tradeTimestamp = this.parse8601 (tradeTime);
const tradeAmount = this.safeFloat (item, 'amount');
const tradePrice = this.safeFloat (item, 'price');
let absTradeAmount = tradeAmount < 0 ? -tradeAmount : tradeAmount;
let tradeCost = undefined;
if (tradeSide === 'sell') {
tradeCost = absTradeAmount;
absTradeAmount = tradeCost / tradePrice;
} else {
tradeCost = absTradeAmount * tradePrice;
}
trades.push ({
'id': this.safeString (item, 'id'),
'timestamp': tradeTimestamp,
'datetime': this.iso8601 (tradeTimestamp),
'order': orderId,
'symbol': symbol,
'price': tradePrice,
'amount': absTradeAmount,
'cost': tradeCost,
'side': tradeSide,
'fee': {
'cost': this.safeFloat (item, 'fee_amount'),
'currency': market['quote'],
},
'info': item,
});
}
}
return {
'id': orderId,
'datetime': this.iso8601 (timestamp),
'timestamp': timestamp,
'lastTradeTimestamp': undefined,
'status': status,
'symbol': symbol,
'type': undefined,
'side': side,
'price': price,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': remaining,
'trades': trades,
'fee': fee,
'info': order,
};
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
let method = 'privatePostOpenOrders';
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
request['pair'] = market['id'];
method += 'Pair';
}
const orders = await this[method] (this.extend (request, params));
for (let i = 0; i < orders.length; i++) {
orders[i] = this.extend (orders[i], { 'status': 'open' });
}
return this.parseOrders (orders, market, since, limit);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let method = 'privatePostArchivedOrdersPair';
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchClosedOrders requires a symbol argument');
}
const market = this.market (symbol);
const request = { 'pair': market['id'] };
const response = await this[method] (this.extend (request, params));
return this.parseOrders (response, market, since, limit);
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'id': id.toString (),
};
const response = await this.privatePostGetOrderTx (this.extend (request, params));
return this.parseOrder (response['data']);
}
nonce () {
return this.milliseconds ();
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = this.urls['api'] + '/' + this.implodeParams (path, params);
let query = this.omit (params, this.extractParams (path));
if (api === 'public') {
if (Object.keys (query).length)
url += '?' + this.urlencode (query);
} else {
this.checkRequiredCredentials ();
let nonce = this.nonce ().toString ();
let auth = nonce + this.uid + this.apiKey;
let signature = this.hmac (this.encode (auth), this.encode (this.secret));
body = this.json (this.extend ({
'key': this.apiKey,
'signature': signature.toUpperCase (),
'nonce': nonce,
}, query));
headers = {
'Content-Type': 'application/json',
};
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let response = await this.fetch2 (path, api, method, params, headers, body);
if (!response) {
throw new NullResponse (this.id + ' returned ' + this.json (response));
} else if (response === true || response === 'true') {
return response;
} else if ('e' in response) {
if ('ok' in response)
if (response['ok'] === 'ok')
return response;
throw new ExchangeError (this.id + ' ' + this.json (response));
} else if ('error' in response) {
if (response['error'])
throw new ExchangeError (this.id + ' ' + this.json (response));
}
return response;
}
async fetchDepositAddress (code, params = {}) {
if (code === 'XRP' || code === 'XLM') {
// https://github.com/ccxt/ccxt/pull/2327#issuecomment-375204856
throw new NotSupported (this.id + ' fetchDepositAddress does not support XRP and XLM addresses yet (awaiting docs from CEX.io)');
}
await this.loadMarkets ();
let currency = this.currency (code);
let request = {
'currency': currency['id'],
};
let response = await this.privatePostGetAddress (this.extend (request, params));
let address = this.safeString (response, 'data');
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': undefined,
'info': response,
};
}
};
| js/cex.js | 'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, ArgumentsRequired, NullResponse, InvalidOrder, NotSupported } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class cex extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'cex',
'name': 'CEX.IO',
'countries': [ 'GB', 'EU', 'CY', 'RU' ],
'rateLimit': 1500,
'has': {
'CORS': true,
'fetchTickers': true,
'fetchOHLCV': true,
'fetchOrder': true,
'fetchOpenOrders': true,
'fetchClosedOrders': true,
'fetchDepositAddress': true,
'fetchOrders': true,
},
'timeframes': {
'1m': '1m',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766442-8ddc33b0-5ed8-11e7-8b98-f786aef0f3c9.jpg',
'api': 'https://cex.io/api',
'www': 'https://cex.io',
'doc': 'https://cex.io/cex-api',
'fees': [
'https://cex.io/fee-schedule',
'https://cex.io/limits-commissions',
],
'referral': 'https://cex.io/r/0/up105393824/0/',
},
'requiredCredentials': {
'apiKey': true,
'secret': true,
'uid': true,
},
'api': {
'public': {
'get': [
'currency_limits/',
'last_price/{pair}/',
'last_prices/{currencies}/',
'ohlcv/hd/{yyyymmdd}/{pair}',
'order_book/{pair}/',
'ticker/{pair}/',
'tickers/{currencies}/',
'trade_history/{pair}/',
],
'post': [
'convert/{pair}',
'price_stats/{pair}',
],
},
'private': {
'post': [
'active_orders_status/',
'archived_orders/{pair}/',
'balance/',
'cancel_order/',
'cancel_orders/{pair}/',
'cancel_replace_order/{pair}/',
'close_position/{pair}/',
'get_address/',
'get_myfee/',
'get_order/',
'get_order_tx/',
'open_orders/{pair}/',
'open_orders/',
'open_position/{pair}/',
'open_positions/{pair}/',
'place_order/{pair}/',
],
},
},
'fees': {
'trading': {
'maker': 0.16 / 100,
'taker': 0.25 / 100,
},
'funding': {
'withdraw': {
// 'USD': undefined,
// 'EUR': undefined,
// 'RUB': undefined,
// 'GBP': undefined,
'BTC': 0.001,
'ETH': 0.01,
'BCH': 0.001,
'DASH': 0.01,
'BTG': 0.001,
'ZEC': 0.001,
'XRP': 0.02,
},
'deposit': {
// 'USD': amount => amount * 0.035 + 0.25,
// 'EUR': amount => amount * 0.035 + 0.24,
// 'RUB': amount => amount * 0.05 + 15.57,
// 'GBP': amount => amount * 0.035 + 0.2,
'BTC': 0.0,
'ETH': 0.0,
'BCH': 0.0,
'DASH': 0.0,
'BTG': 0.0,
'ZEC': 0.0,
'XRP': 0.0,
'XLM': 0.0,
},
},
},
'options': {
'fetchOHLCVWarning': true,
'createMarketBuyOrderRequiresPrice': true,
'order': {
'status': {
'c': 'canceled',
'd': 'closed',
'cd': 'closed',
'a': 'open',
},
},
},
});
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'limit': limit,
'pair': market.id,
'dateFrom': since,
};
const response = await this.privatePostArchivedOrdersPair (this.extend (request, params));
const results = [];
for (let i = 0; i < response.length; i++) {
// cancelled (unfilled):
// { id: '4005785516',
// type: 'sell',
// time: '2017-07-18T19:08:34.223Z',
// lastTxTime: '2017-07-18T19:08:34.396Z',
// lastTx: '4005785522',
// pos: null,
// status: 'c',
// symbol1: 'ETH',
// symbol2: 'GBP',
// amount: '0.20000000',
// price: '200.5625',
// remains: '0.20000000',
// 'a:ETH:cds': '0.20000000',
// tradingFeeMaker: '0',
// tradingFeeTaker: '0.16',
// tradingFeeUserVolumeAmount: '10155061217',
// orderId: '4005785516' }
// --
// cancelled (partially filled buy):
// { id: '4084911657',
// type: 'buy',
// time: '2017-08-05T03:18:39.596Z',
// lastTxTime: '2019-03-19T17:37:46.404Z',
// lastTx: '8459265833',
// pos: null,
// status: 'cd',
// symbol1: 'BTC',
// symbol2: 'GBP',
// amount: '0.05000000',
// price: '2241.4692',
// tfacf: '1',
// remains: '0.03910535',
// 'tfa:GBP': '0.04',
// 'tta:GBP': '24.39',
// 'a:BTC:cds': '0.01089465',
// 'a:GBP:cds': '112.26',
// 'f:GBP:cds': '0.04',
// tradingFeeMaker: '0',
// tradingFeeTaker: '0.16',
// tradingFeeUserVolumeAmount: '13336396963',
// orderId: '4084911657' }
// --
// cancelled (partially filled sell):
// { id: '4426728375',
// type: 'sell',
// time: '2017-09-22T00:24:20.126Z',
// lastTxTime: '2017-09-22T00:24:30.476Z',
// lastTx: '4426729543',
// pos: null,
// status: 'cd',
// symbol1: 'BCH',
// symbol2: 'BTC',
// amount: '0.10000000',
// price: '0.11757182',
// tfacf: '1',
// remains: '0.09935956',
// 'tfa:BTC': '0.00000014',
// 'tta:BTC': '0.00007537',
// 'a:BCH:cds': '0.10000000',
// 'a:BTC:cds': '0.00007537',
// 'f:BTC:cds': '0.00000014',
// tradingFeeMaker: '0',
// tradingFeeTaker: '0.18',
// tradingFeeUserVolumeAmount: '3466715450',
// orderId: '4426728375' }
// --
// filled:
// { id: '5342275378',
// type: 'sell',
// time: '2018-01-04T00:28:12.992Z',
// lastTxTime: '2018-01-04T00:28:12.992Z',
// lastTx: '5342275393',
// pos: null,
// status: 'd',
// symbol1: 'BCH',
// symbol2: 'BTC',
// amount: '0.10000000',
// kind: 'api',
// price: '0.17',
// remains: '0.00000000',
// 'tfa:BTC': '0.00003902',
// 'tta:BTC': '0.01699999',
// 'a:BCH:cds': '0.10000000',
// 'a:BTC:cds': '0.01699999',
// 'f:BTC:cds': '0.00003902',
// tradingFeeMaker: '0.15',
// tradingFeeTaker: '0.23',
// tradingFeeUserVolumeAmount: '1525951128',
// orderId: '5342275378' }
// --
// market order (buy):
// { "id": "6281946200",
// "pos": null,
// "time": "2018-05-23T11:55:43.467Z",
// "type": "buy",
// "amount": "0.00000000",
// "lastTx": "6281946210",
// "status": "d",
// "amount2": "20.00",
// "orderId": "6281946200",
// "remains": "0.00000000",
// "symbol1": "ETH",
// "symbol2": "EUR",
// "tfa:EUR": "0.05",
// "tta:EUR": "19.94",
// "a:ETH:cds": "0.03764100",
// "a:EUR:cds": "20.00",
// "f:EUR:cds": "0.05",
// "lastTxTime": "2018-05-23T11:55:43.467Z",
// "tradingFeeTaker": "0.25",
// "tradingFeeUserVolumeAmount": "55998097" }
// --
// market order (sell):
// { "id": "6282200948",
// "pos": null,
// "time": "2018-05-23T12:42:58.315Z",
// "type": "sell",
// "amount": "-0.05000000",
// "lastTx": "6282200958",
// "status": "d",
// "orderId": "6282200948",
// "remains": "0.00000000",
// "symbol1": "ETH",
// "symbol2": "EUR",
// "tfa:EUR": "0.07",
// "tta:EUR": "26.49",
// "a:ETH:cds": "0.05000000",
// "a:EUR:cds": "26.49",
// "f:EUR:cds": "0.07",
// "lastTxTime": "2018-05-23T12:42:58.315Z",
// "tradingFeeTaker": "0.25",
// "tradingFeeUserVolumeAmount": "56294576" }
const item = response[i];
const status = this.parseOrderStatus (this.safeString (item, 'status'));
const baseId = item['symbol1'];
const quoteId = item['symbol2'];
const side = item['type'];
const baseAmount = this.safeFloat (item, 'a:' + baseId + ':cds');
const quoteAmount = this.safeFloat (item, 'a:' + quoteId + ':cds');
const fee = this.safeFloat (item, 'f:' + quoteId + ':cds');
const amount = this.safeFloat (item, 'amount');
let price = this.safeFloat (item, 'price');
const remaining = this.safeFloat (item, 'remains');
const filled = amount - remaining;
let orderAmount = undefined;
let cost = undefined;
let average = undefined;
let type = undefined;
if (!price) {
type = 'market';
orderAmount = baseAmount;
cost = quoteAmount;
average = orderAmount / cost;
} else {
const ta = this.safeFloat (item, 'ta:' + quoteId, 0);
const tta = this.safeFloat (item, 'tta:' + quoteId, 0);
const fa = this.safeFloat (item, 'fa:' + quoteId, 0);
const tfa = this.safeFloat (item, 'tfa:' + quoteId, 0);
if (side === 'sell')
cost = ta + tta + (fa + tfa);
else
cost = ta + tta - (fa + tfa);
type = 'limit';
orderAmount = amount;
average = cost / filled;
}
const time = this.safeString (item, 'time');
const lastTxTime = this.safeString (item, 'lastTxTime');
const timestamp = this.parse8601 (time);
results.push ({
'id': item['id'],
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastUpdated': this.parse8601 (lastTxTime),
'status': status,
'symbol': this.findSymbol (baseId + '/' + quoteId),
'side': side,
'price': price,
'amount': orderAmount,
'average': average,
'type': type,
'filled': filled,
'cost': cost,
'remaining': remaining,
'fee': {
'cost': fee,
'currency': this.currencyId (quoteId),
},
'info': item,
});
}
return results;
}
parseOrderStatus (status) {
return this.safeString (this.options['order']['status'], status, status);
}
async fetchMarkets (params = {}) {
let markets = await this.publicGetCurrencyLimits ();
let result = [];
for (let p = 0; p < markets['data']['pairs'].length; p++) {
let market = markets['data']['pairs'][p];
let id = market['symbol1'] + '/' + market['symbol2'];
let symbol = id;
let [ base, quote ] = symbol.split ('/');
result.push ({
'id': id,
'info': market,
'symbol': symbol,
'base': base,
'quote': quote,
'precision': {
'price': this.precisionFromString (this.safeString (market, 'minPrice')),
'amount': this.precisionFromString (this.safeString (market, 'minLotSize')),
},
'limits': {
'amount': {
'min': market['minLotSize'],
'max': market['maxLotSize'],
},
'price': {
'min': this.safeFloat (market, 'minPrice'),
'max': this.safeFloat (market, 'maxPrice'),
},
'cost': {
'min': market['minLotSizeS2'],
'max': undefined,
},
},
});
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let response = await this.privatePostBalance ();
let result = { 'info': response };
let ommited = [ 'username', 'timestamp' ];
let balances = this.omit (response, ommited);
let currencies = Object.keys (balances);
for (let i = 0; i < currencies.length; i++) {
let currency = currencies[i];
if (currency in balances) {
let account = {
'free': this.safeFloat (balances[currency], 'available', 0.0),
'used': this.safeFloat (balances[currency], 'orders', 0.0),
'total': 0.0,
};
account['total'] = this.sum (account['free'], account['used']);
result[currency] = account;
}
}
return this.parseBalance (result);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
let request = {
'pair': this.marketId (symbol),
};
if (limit !== undefined) {
request['depth'] = limit;
}
let orderbook = await this.publicGetOrderBookPair (this.extend (request, params));
let timestamp = orderbook['timestamp'] * 1000;
return this.parseOrderBook (orderbook, timestamp);
}
parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
return [
ohlcv[0] * 1000,
ohlcv[1],
ohlcv[2],
ohlcv[3],
ohlcv[4],
ohlcv[5],
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
if (since === undefined) {
since = this.milliseconds () - 86400000; // yesterday
} else {
if (this.options['fetchOHLCVWarning']) {
throw new ExchangeError (this.id + " fetchOHLCV warning: CEX can return historical candles for a certain date only, this might produce an empty or null reply. Set exchange.options['fetchOHLCVWarning'] = false or add ({ 'options': { 'fetchOHLCVWarning': false }}) to constructor params to suppress this warning message.");
}
}
let ymd = this.ymd (since);
ymd = ymd.split ('-');
ymd = ymd.join ('');
let request = {
'pair': market['id'],
'yyyymmdd': ymd,
};
try {
let response = await this.publicGetOhlcvHdYyyymmddPair (this.extend (request, params));
let key = 'data' + this.timeframes[timeframe];
let ohlcvs = JSON.parse (response[key]);
return this.parseOHLCVs (ohlcvs, market, timeframe, since, limit);
} catch (e) {
if (e instanceof NullResponse) {
return [];
}
}
}
parseTicker (ticker, market = undefined) {
let timestamp = undefined;
if ('timestamp' in ticker) {
timestamp = parseInt (ticker['timestamp']) * 1000;
}
let volume = this.safeFloat (ticker, 'volume');
let high = this.safeFloat (ticker, 'high');
let low = this.safeFloat (ticker, 'low');
let bid = this.safeFloat (ticker, 'bid');
let ask = this.safeFloat (ticker, 'ask');
let last = this.safeFloat (ticker, 'last');
let symbol = undefined;
if (market)
symbol = market['symbol'];
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': high,
'low': low,
'bid': bid,
'bidVolume': undefined,
'ask': ask,
'askVolume': undefined,
'vwap': undefined,
'open': undefined,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': volume,
'quoteVolume': undefined,
'info': ticker,
};
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
let currencies = Object.keys (this.currencies);
let response = await this.publicGetTickersCurrencies (this.extend ({
'currencies': currencies.join ('/'),
}, params));
let tickers = response['data'];
let result = {};
for (let t = 0; t < tickers.length; t++) {
let ticker = tickers[t];
let symbol = ticker['pair'].replace (':', '/');
let market = this.markets[symbol];
result[symbol] = this.parseTicker (ticker, market);
}
return result;
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let ticker = await this.publicGetTickerPair (this.extend ({
'pair': market['id'],
}, params));
return this.parseTicker (ticker, market);
}
parseTrade (trade, market = undefined) {
let timestamp = parseInt (trade['date']) * 1000;
return {
'info': trade,
'id': trade['tid'],
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': market['symbol'],
'type': undefined,
'side': trade['type'],
'price': this.safeFloat (trade, 'price'),
'amount': this.safeFloat (trade, 'amount'),
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.publicGetTradeHistoryPair (this.extend ({
'pair': market['id'],
}, params));
return this.parseTrades (response, market, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
if (type === 'market') {
// for market buy it requires the amount of quote currency to spend
if (side === 'buy') {
if (this.options['createMarketBuyOrderRequiresPrice']) {
if (price === undefined) {
throw new InvalidOrder (this.id + " createOrder() requires the price argument with market buy orders to calculate total order cost (amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options['createMarketBuyOrderRequiresPrice'] = false to supply the cost in the amount argument (the exchange-specific behaviour)");
} else {
amount = amount * price;
}
}
}
}
await this.loadMarkets ();
let request = {
'pair': this.marketId (symbol),
'type': side,
'amount': amount,
};
if (type === 'limit') {
request['price'] = price;
} else {
request['order_type'] = type;
}
let response = await this.privatePostPlaceOrderPair (this.extend (request, params));
return {
'info': response,
'id': response['id'],
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
return await this.privatePostCancelOrder ({ 'id': id });
}
parseOrderStatus (status) {
const statuses = {
'a': 'open',
'cd': 'canceled',
'c': 'canceled',
'd': 'closed',
};
return this.safeValue (statuses, status, status);
}
parseOrder (order, market = undefined) {
// Depending on the call, 'time' can be a unix int, unix string or ISO string
// Yes, really
let timestamp = this.safeValue (order, 'time');
if (typeof timestamp === 'string' && timestamp.indexOf ('T') >= 0) {
// ISO8601 string
timestamp = this.parse8601 (timestamp);
} else {
// either integer or string integer
timestamp = parseInt (timestamp);
}
let symbol = undefined;
if (market === undefined) {
let symbol = order['symbol1'] + '/' + order['symbol2'];
if (symbol in this.markets)
market = this.market (symbol);
}
let status = order['status'];
if (status === 'a') {
status = 'open'; // the unified status
} else if (status === 'cd') {
status = 'canceled';
} else if (status === 'c') {
status = 'canceled';
} else if (status === 'd') {
status = 'closed';
}
let price = this.safeFloat (order, 'price');
let amount = this.safeFloat (order, 'amount');
let remaining = this.safeFloat (order, 'pending');
if (!remaining)
remaining = this.safeFloat (order, 'remains');
let filled = amount - remaining;
let fee = undefined;
let cost = undefined;
if (market !== undefined) {
symbol = market['symbol'];
cost = this.safeFloat (order, 'ta:' + market['quote']);
if (cost === undefined)
cost = this.safeFloat (order, 'tta:' + market['quote']);
let baseFee = 'fa:' + market['base'];
let baseTakerFee = 'tfa:' + market['base'];
let quoteFee = 'fa:' + market['quote'];
let quoteTakerFee = 'tfa:' + market['quote'];
let feeRate = this.safeFloat (order, 'tradingFeeMaker');
if (!feeRate)
feeRate = this.safeFloat (order, 'tradingFeeTaker', feeRate);
if (feeRate)
feeRate /= 100.0; // convert to mathematically-correct percentage coefficients: 1.0 = 100%
if ((baseFee in order) || (baseTakerFee in order)) {
let baseFeeCost = this.safeFloat (order, baseFee);
if (baseFeeCost === undefined)
baseFeeCost = this.safeFloat (order, baseTakerFee);
fee = {
'currency': market['base'],
'rate': feeRate,
'cost': baseFeeCost,
};
} else if ((quoteFee in order) || (quoteTakerFee in order)) {
let quoteFeeCost = this.safeFloat (order, quoteFee);
if (quoteFeeCost === undefined)
quoteFeeCost = this.safeFloat (order, quoteTakerFee);
fee = {
'currency': market['quote'],
'rate': feeRate,
'cost': quoteFeeCost,
};
}
}
if (!cost)
cost = price * filled;
const side = order['type'];
let trades = undefined;
const orderId = order['id'];
if ('vtx' in order) {
trades = [];
for (let i = 0; i < order['vtx'].length; i++) {
const item = order['vtx'][i];
const tradeSide = this.safeString (item, 'type');
if (item['type'] === 'cancel') {
// looks like this might represent the cancelled part of an order
// { id: '4426729543',
// type: 'cancel',
// time: '2017-09-22T00:24:30.476Z',
// user: 'up106404164',
// c: 'user:up106404164:a:BCH',
// d: 'order:4426728375:a:BCH',
// a: '0.09935956',
// amount: '0.09935956',
// balance: '0.42580261',
// symbol: 'BCH',
// order: '4426728375',
// buy: null,
// sell: null,
// pair: null,
// pos: null,
// cs: '0.42580261',
// ds: 0 }
continue;
}
if (!item['price']) {
// this represents the order
// {
// "a": "0.47000000",
// "c": "user:up106404164:a:EUR",
// "d": "order:6065499239:a:EUR",
// "cs": "1432.93",
// "ds": "476.72",
// "id": "6065499249",
// "buy": null,
// "pos": null,
// "pair": null,
// "sell": null,
// "time": "2018-04-22T13:07:22.152Z",
// "type": "buy",
// "user": "up106404164",
// "order": "6065499239",
// "amount": "-715.97000000",
// "symbol": "EUR",
// "balance": "1432.93000000" }
continue;
}
// if (item['type'] === 'costsNothing')
// console.log (item);
// todo: deal with these
if (item['type'] === 'costsNothing')
continue;
// --
// if (side !== tradeSide)
// throw Error (JSON.stringify (order, null, 2));
// if (orderId !== item['order'])
// throw Error (JSON.stringify (order, null, 2));
// --
// partial buy trade
// {
// "a": "0.01589885",
// "c": "user:up106404164:a:BTC",
// "d": "order:6065499239:a:BTC",
// "cs": "0.36300000",
// "ds": 0,
// "id": "6067991213",
// "buy": "6065499239",
// "pos": null,
// "pair": null,
// "sell": "6067991206",
// "time": "2018-04-22T23:09:11.773Z",
// "type": "buy",
// "user": "up106404164",
// "order": "6065499239",
// "price": 7146.5,
// "amount": "0.01589885",
// "symbol": "BTC",
// "balance": "0.36300000",
// "symbol2": "EUR",
// "fee_amount": "0.19" }
// --
// trade with zero amount, but non-zero fee
// {
// "a": "0.00000000",
// "c": "user:up106404164:a:EUR",
// "d": "order:5840654423:a:EUR",
// "cs": 559744,
// "ds": 0,
// "id": "5840654429",
// "buy": "5807238573",
// "pos": null,
// "pair": null,
// "sell": "5840654423",
// "time": "2018-03-15T03:20:14.010Z",
// "type": "sell",
// "user": "up106404164",
// "order": "5840654423",
// "price": 730,
// "amount": "0.00000000",
// "symbol": "EUR",
// "balance": "5597.44000000",
// "symbol2": "BCH",
// "fee_amount": "0.01" }
const tradeTime = this.safeString (item, 'time');
const tradeTimestamp = this.parse8601 (tradeTime);
const tradeAmount = this.safeFloat (item, 'amount');
const tradePrice = this.safeFloat (item, 'price');
let absTradeAmount = tradeAmount < 0 ? -tradeAmount : tradeAmount;
let tradeCost = undefined;
if (tradeSide === 'sell') {
tradeCost = absTradeAmount;
absTradeAmount = tradeCost / tradePrice;
} else {
tradeCost = absTradeAmount * tradePrice;
}
trades.push ({
'id': this.safeString (item, 'id'),
'timestamp': tradeTimestamp,
'datetime': this.iso8601 (tradeTimestamp),
'order': orderId,
'symbol': symbol,
'price': tradePrice,
'amount': absTradeAmount,
'cost': tradeCost,
'side': tradeSide,
'fee': {
'cost': this.safeFloat (item, 'fee_amount'),
'currency': market['quote'],
},
'info': item,
});
}
}
return {
'id': orderId,
'datetime': this.iso8601 (timestamp),
'timestamp': timestamp,
'lastTradeTimestamp': undefined,
'status': status,
'symbol': symbol,
'type': undefined,
'side': side,
'price': price,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': remaining,
'trades': trades,
'fee': fee,
'info': order,
};
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
let method = 'privatePostOpenOrders';
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
request['pair'] = market['id'];
method += 'Pair';
}
const orders = await this[method] (this.extend (request, params));
for (let i = 0; i < orders.length; i++) {
orders[i] = this.extend (orders[i], { 'status': 'open' });
}
return this.parseOrders (orders, market, since, limit);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let method = 'privatePostArchivedOrdersPair';
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchClosedOrders requires a symbol argument');
}
const market = this.market (symbol);
const request = { 'pair': market['id'] };
const response = await this[method] (this.extend (request, params));
return this.parseOrders (response, market, since, limit);
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'id': id.toString (),
};
const response = await this.privatePostGetOrderTx (this.extend (request, params));
return this.parseOrder (response['data']);
}
nonce () {
return this.milliseconds ();
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = this.urls['api'] + '/' + this.implodeParams (path, params);
let query = this.omit (params, this.extractParams (path));
if (api === 'public') {
if (Object.keys (query).length)
url += '?' + this.urlencode (query);
} else {
this.checkRequiredCredentials ();
let nonce = this.nonce ().toString ();
let auth = nonce + this.uid + this.apiKey;
let signature = this.hmac (this.encode (auth), this.encode (this.secret));
body = this.json (this.extend ({
'key': this.apiKey,
'signature': signature.toUpperCase (),
'nonce': nonce,
}, query));
headers = {
'Content-Type': 'application/json',
};
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let response = await this.fetch2 (path, api, method, params, headers, body);
if (!response) {
throw new NullResponse (this.id + ' returned ' + this.json (response));
} else if (response === true || response === 'true') {
return response;
} else if ('e' in response) {
if ('ok' in response)
if (response['ok'] === 'ok')
return response;
throw new ExchangeError (this.id + ' ' + this.json (response));
} else if ('error' in response) {
if (response['error'])
throw new ExchangeError (this.id + ' ' + this.json (response));
}
return response;
}
async fetchDepositAddress (code, params = {}) {
if (code === 'XRP' || code === 'XLM') {
// https://github.com/ccxt/ccxt/pull/2327#issuecomment-375204856
throw new NotSupported (this.id + ' fetchDepositAddress does not support XRP and XLM addresses yet (awaiting docs from CEX.io)');
}
await this.loadMarkets ();
let currency = this.currency (code);
let request = {
'currency': currency['id'],
};
let response = await this.privatePostGetAddress (this.extend (request, params));
let address = this.safeString (response, 'data');
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': undefined,
'info': response,
};
}
};
| cex market.id → market['id'] | js/cex.js | cex market.id → market['id'] | <ide><path>s/cex.js
<ide> const market = this.market (symbol);
<ide> const request = {
<ide> 'limit': limit,
<del> 'pair': market.id,
<add> 'pair': market['id'],
<ide> 'dateFrom': since,
<ide> };
<ide> const response = await this.privatePostArchivedOrdersPair (this.extend (request, params)); |
|
Java | epl-1.0 | 1bf2a468cad1651c4b99686f15322466d65ed353 | 0 | HQebupt/JavaBasis | package org.hq.detail;
public class LongTrap {
/**
* 丧心病狂的包装类型细节:Long 和Integer 缓存了 [-128, 127]范围内的值。
* This is the result of auto-boxing. See Long.valueOf().
*/
public static void main(final String[] args) {
final Long n = 0L;
final Long m = 0L;
System.out.println(n + " == " + m + " : " + (n == m));
final Long a = 127L;
final Long b = 127L;
System.out.println(a + " == " + b + " : " + (a == b));
final Long A = 128L;
final Long B = 128L;
System.out.println(A + " == " + B + " : " + (A == B));
final Long x = -128L;
final Long y = -128L;
System.out.println(x + " == " + y + " : " + (x == y));
final Long X = -129L;
final Long Y = -129L;
System.out.println(X + " == " + Y + " : " + (X == Y));
}
/**
* OutPut:
* 0 == 0 : true
* 127 == 127 : true
* 128 == 128 : false
* -128 == -128 : true
* -129 == -129 : false
*/
}
| src/org/hq/detail/LongTrap.java | package org.hq.detail;
public class LongTrap {
/**
* 丧心病狂的包装类型细节:Long 和Integer 缓存了 [-128, 127]范围内的值。
* This is the result of auto-boxing. See Long.valueOf().
*/
public static void main(final String[] args) {
final Long n = 0L;
final Long m = 0L;
System.out.println(n + " == " + m + " : " + (n == m));
final Long a = 127L;
final Long b = 127L;
System.out.println(a + " == " + b + " : " + (a == b));
final Long A = 128L;
final Long B = 128L;
System.out.println(A + " == " + B + " : " + (A == B));
final Long x = -128L;
final Long y = -128L;
System.out.println(x + " == " + y + " : " + (x == y));
final Long X = -129L;
final Long Y = -129L;
System.out.println(X + " == " + Y + " : " + (X == Y));
}
}
| Add output result.
| src/org/hq/detail/LongTrap.java | Add output result. | <ide><path>rc/org/hq/detail/LongTrap.java
<ide> final Long Y = -129L;
<ide> System.out.println(X + " == " + Y + " : " + (X == Y));
<ide> }
<add> /**
<add> * OutPut:
<add> * 0 == 0 : true
<add> * 127 == 127 : true
<add> * 128 == 128 : false
<add> * -128 == -128 : true
<add> * -129 == -129 : false
<add> */
<ide>
<ide> } |
|
Java | apache-2.0 | 1ef8138b2b90388ad08d5b659885b416cba8b39b | 0 | thomasjungblut/thomasjungblut-common | package de.jungblut.crawl;
import java.io.IOException;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
/**
* Writes the result into a sequencefile "files/crawl/result.seq". It tab
* separates the outlinks in the sequencefile value, the key is the origin url.
*
* @author thomas.jungblut
*
*/
public final class SequenceFileResultWriter<T extends FetchResult> implements
ResultWriter<T> {
private FileSystem fs;
private SequenceFile.Writer writer;
@Override
public void open(Configuration conf) throws IOException {
fs = FileSystem.get(conf);
Path outputPath = getOutputPath();
fs.delete(outputPath, true);
writer = new SequenceFile.Writer(fs, conf, outputPath, Text.class,
Text.class);
}
@Override
public void write(FetchResult result) throws IOException {
writer.append(new Text(result.url), asText(result.outlinks));
}
public Path getOutputPath() {
return new Path("files/crawl/result.seq");
}
private static Text asText(final Set<String> set) {
Text text = new Text();
final StringBuilder sb = new StringBuilder();
for (String s : set) {
sb.append(s);
sb.append('\t');
}
text.set(sb.toString());
return text;
}
@Override
public void close() throws Exception {
writer.close();
}
}
| src/de/jungblut/crawl/SequenceFileResultWriter.java | package de.jungblut.crawl;
import java.io.IOException;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
/**
* Writes the result into a sequencefile "files/crawl/result.seq". It tab
* separates the outlinks in the sequencefile value, the key is the origin url.
*
* @author thomas.jungblut
*
*/
public final class SequenceFileResultWriter implements ResultWriter<FetchResult> {
private FileSystem fs;
private SequenceFile.Writer writer;
@Override
public void open(Configuration conf) throws IOException {
fs = FileSystem.get(conf);
Path outputPath = getOutputPath();
fs.delete(outputPath, true);
writer = new SequenceFile.Writer(fs, conf, outputPath, Text.class,
Text.class);
}
@Override
public void write(FetchResult result) throws IOException {
writer.append(new Text(result.url), asText(result.outlinks));
}
public Path getOutputPath() {
return new Path("files/crawl/result.seq");
}
private static Text asText(final Set<String> set) {
Text text = new Text();
final StringBuilder sb = new StringBuilder();
for (String s : set) {
sb.append(s);
sb.append('\t');
}
text.set(sb.toString());
return text;
}
@Override
public void close() throws Exception {
writer.close();
}
}
| generify the resultwriter | src/de/jungblut/crawl/SequenceFileResultWriter.java | generify the resultwriter | <ide><path>rc/de/jungblut/crawl/SequenceFileResultWriter.java
<ide> * @author thomas.jungblut
<ide> *
<ide> */
<del>public final class SequenceFileResultWriter implements ResultWriter<FetchResult> {
<add>public final class SequenceFileResultWriter<T extends FetchResult> implements
<add> ResultWriter<T> {
<ide>
<ide> private FileSystem fs;
<ide> private SequenceFile.Writer writer; |
|
JavaScript | apache-2.0 | 092e91cd2fb762081fde2013c2db9e26c47ccf06 | 0 | EchoAppsTeam/EchoConversations | (function(jQuery) {
"use strict";
var $ = jQuery;
/**
* @class Echo.StreamServer.Controls.CardComposer
* Echo Submit control which encapsulates interaction with the
* <a href="http://echoplatform.com/streamserver/docs/rest-api/items-api/submit/" target="_blank">Echo Submit API</a>.
*
* new Echo.StreamServer.Controls.CardComposer({
* "target": document.getElementById("composer"),
* "targetURL": "http://example.com/composer",
* "appkey": "echo.jssdk.demo.aboutecho.com",
* });
*
* More information regarding the possible ways of the Control initialization
* can be found in the [“How to initialize Echo components”](#!/guide/how_to_initialize_components-section-initializing-an-app) guide.
*
* @extends Echo.Control
*
* @package streamserver/controls.pack.js
* @package streamserver.pack.js
*
* @constructor
* Submit constructor initializing Echo.StreamServer.Controls.CardComposer class
*
* @param {Object} config
* Configuration options
*/
var composer = Echo.Control.manifest("Echo.StreamServer.Controls.CardComposer");
if (Echo.Control.isDefined(composer)) return;
/** @hide @cfg apiBaseURL */
/** @hide @method placeImage */
/** @hide @method getRelativeTime */
/** @hide @echo_label justNow */
/** @hide @echo_label today */
/** @hide @echo_label yesterday */
/** @hide @echo_label lastWeek */
/** @hide @echo_label lastMonth */
/** @hide @echo_label secondAgo */
/** @hide @echo_label secondsAgo */
/** @hide @echo_label minuteAgo */
/** @hide @echo_label minutesAgo */
/** @hide @echo_label hourAgo */
/** @hide @echo_label hoursAgo */
/** @hide @echo_label dayAgo */
/** @hide @echo_label daysAgo */
/** @hide @echo_label weekAgo */
/** @hide @echo_label weeksAgo */
/** @hide @echo_label monthAgo */
/** @hide @echo_label monthsAgo */
/** @hide @echo_label loading */
/** @hide @echo_label retrying */
/** @hide @echo_label error_busy */
/** @hide @echo_label error_timeout */
/** @hide @echo_label error_waiting */
/** @hide @echo_label error_view_limit */
/** @hide @echo_label error_view_update_capacity_exceeded */
/** @hide @echo_label error_result_too_large */
/** @hide @echo_label error_wrong_query */
/** @hide @echo_label error_incorrect_appkey */
/** @hide @echo_label error_internal_error */
/** @hide @echo_label error_quota_exceeded */
/** @hide @echo_label error_incorrect_user_id */
/** @hide @echo_label error_unknown */
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onReady
* Triggered when the app initialization is finished completely.
*/
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onRefresh
* Triggered when the app is refreshed. For example after the user
* login/logout action or as a result of the "refresh" function call.
*/
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onRender
* Triggered when the app is rendered.
*/
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onRerender
* Triggered when the app is rerendered.
*/
composer.init = function() {
var self = this;
if (!this.checkAppKey()) return;
this.addPostValidator(function() {
if (self.user.is("logged")) return true;
var isGuestAllowed = self.config.get("submitPermissions") === "allowGuest";
if (!isGuestAllowed) {
self.set("_deferredActivity", $.proxy(self.posting.action, self));
self._requestLoginPrompt();
return false;
}
return true;
}, "low");
var tabsUniqueId = Echo.Utils.getUniqueString();
$.each(this.composers, function(i, tab) {
tab.index = i;
tab.uniqueId = tab.id + "-" + tabsUniqueId;
if (!$.isFunction(tab.isValid)) return;
self.addPostValidator(function() {
if (self.currentComposer.id !== tab.id) return true;
return tab.isValid();
}, "low");
});
this.resolver = new Echo.URLResolver({
"embedly": this.config.get("dependencies.embedly")
});
this.collapsed = this.config.get("initialMode") === "collapsed";
this._extractInfoFromExternalData();
this.render();
this.ready();
};
composer.destroy = function() {
this.auth && this.auth.destroy();
this.tabs && this.tabs.destroy();
this.mediaContainer && this.mediaContainer.destroy();
this.toggleModeHandler && $(document).off("mousedown", this.toggleModeHandler);
};
composer.config = {
/**
* @cfg {String} [targetURL=document.location.href]
* Specifies the URI to which the submitted Echo item is related.
* This parameter will be used as a activity target value for the item.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "targetURL": "http://somedomain.com/some_article.html",
* ...
* });
*/
"targetURL": document.location.href,
/**
* @cfg {Object} contentTypes
*
* @cfg {Object} contentTypes.comments
*
* @cfg {String} contentTypes.comments.prompt
* Is used to define the default call to action phrase.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "contentTypes": {
* "comments": {
* "prompt": "Type your comment here..."
* }
* }
* ...
* });
*/
"contentTypes": {
"comments": {
"visible": true,
"prompt": "What's on your mind?",
"resolveURLs": true
}
},
/**
* @cfg {Array} markers
* This parameter is used to attach the markers metadata to the item
* during the item submission. The format of the value is the array
* with the string values. Markers will also be displayed in the "Markers"
* field in the Submit form UI for Moderators and Administrators.
* For non-admin users the markers value will be submitted along with
* other item content when the "Post" button is pressed.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "markers": ["marker1", "marker2", "marker3"],
* ...
* });
*/
"markers": [],
/**
* @cfg {Object} source
* Designates the initial item source (E.g. Twitter). You can override
* source name, URI and the corresponding icon.
*
* @cfg {String} source.name
* Source name.
*
* @cfg {String} source.uri
* Source uri.
*
* @cfg {String} source.icon
* Source icon.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "source": {
* "name": "ExampleSource",
* "uri": "http://example.com/",
* "icon": "http://example.com/images/source.png"
* },
* ...
* });
*/
"source": {},
/**
* @cfg {Array} tags
* This parameter is used to attach the tags metadata to the item during
* the item submission. The format of the value is the array array with
* the string values. Tags will be also displayed in the "Tags" field in
* the Submit form UI for Moderators and Administrators. For non-admin
* users the tags value will be submitted along with the other item
* content when the "Post" button is pressed.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "tags": ["tag1", "tag2", "tag3"],
* ...
* });
*/
"tags": [],
/**
* @cfg {String} requestMethod
* This parameter is used to specify the request method. Possible values
* are "GET" and "POST". Setting parameter to "POST" has some restrictions.
* We can't handle server response, UI won't show any waiting for the
* server responses actions.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "requestMethod": "POST",
* ...
* });
*/
"requestMethod": "GET",
/**
* @cfg {String} itemURIPattern
* Allows to define item id pattern. The value of this parameter should be
* a valid URI with "{id}" placeholder which will indicate the place where
* unique id should be inserted. If this parameter is ommited in
* configuration or the URI is invalid it'll be ignored.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "itemURIPattern": "http://your-domain.com/path/{id}",
* ...
* });
*/
"itemURIPattern": undefined,
/**
* @cfg {Number} postingTimeout
* Is used to specify the number of seconds after which the Submit Form will show
* the timeout error dialog if the server does not return anything. If the parameter
* value is 0 then the mentioned dialog will never be shown.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "postingTimeout": 15,
* ...
* });
*/
"postingTimeout": 30,
/**
* @cfg {Object} errorPopup
* Is used to define dimensions of error message popup. The value of this parameter
* is an object with the following fields:
*
* @cfg {Number} errorPopup.minHeight
* The minimum height of error message popup.
*
* @cfg {Number} errorPopup.maxHeight
* The maximum height of error message popup.
*
* @cfg {Number} errorPopup.width
* The width of error message popup.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "errorPopup": {
* "minHeight": 70,
* "maxHeight": 150,
* "width": 390
* }
* ...
* });
*/
"errorPopup": {
"minHeight": 70,
"maxHeight": 150,
"width": 390
},
/**
* @cfg {Object} auth
* Configuration options as described in Echo.IdentityServer.Controls.Auth documentation.
*/
"auth": {},
"dependencies": {
"FilePicker": {
"apiKey": undefined
},
"embedly": {
"apiKey": undefined,
"maxDescriptionCharacters": "200"
}
},
"initialMode": "expanded", // expanded || collapsed
"collapsible": false,
"compact": {
"layout": "inline", // small || smallest || inline
"prompt": "Contribute here"
},
"displaySharingOnPost": true,
"submitPermissions": "forceLogin",
"confirmation": {
"enabled": false,
"message": "Thanks, your post has been submitted for review",
"timeout": 5000,
"hidingTimeout": 200
},
"targetQuery": undefined
};
composer.vars = {
"collapsed": false,
"toggleModeHandler": undefined,
"postButtonState": "disabled",
"formData": {
"text": "",
"media": []
},
"composers": [],
"validators": []
};
composer.dependencies = [{
"url": "{%= baseURLs.prod %}/controls/nested-card.js",
"loaded": function() { return !!Echo.Conversations.NestedCard; }
}, {
"url": "{%= baseURLs.prod %}/controls/media-container.js",
"loaded": function() { return !!Echo.Conversations.MediaContainer; }
}, {
"url": "{%= baseURLs.prod %}/third-party/jquery.placeholder.js",
"loaded": function() { return !!$.placeholder; }
}, {
"loaded": function() { return !!Echo.GUI; },
"url": "{config:cdnBaseURL.sdk}/gui.pack.js"
}, {
"url": "{config:cdnBaseURL.sdk}/gui.pack.css"
}];
composer.labels = {
/**
* @echo_label
*/
"markers": "Markers:",
/**
* @echo_label
*/
"markersHint": "Marker1, marker2, marker3, ...",
/**
* @echo_label
* Label for the button allowing to submit form
*/
"post": "Post",
/**
* @echo_label
*/
"postAndShare": "Post and Share",
/**
* @echo_label
*/
"posting": "Posting...",
/**
* @echo_label
*/
"postingFailed": "There was a server error while trying to submit your item. Please try again in a few minutes. <b>Error: \"{error}\"</b>.",
/**
* @echo_label
*/
"postingTimeout": "There was a network issue while trying to submit your item. Please try again in a few minutes.",
/**
* @echo_label
*/
"tagsHint": "Tag1, tag2, tag3, ...",
/**
* @echo_label
*/
"tags": "Tags:",
/**
* @echo_label
*/
"yourName": "Your Name",
/**
* @echo_label
*/
"required": " (required)"
};
composer.events = {
"Echo.UserSession.onInvalidate": {
"context": "global",
"handler": function() {
if (this.get("_deferredActivity")) {
this.get("_deferredActivity")();
this.remove("_deferredActivity");
// clearing up saved text...
var targetURL = this.config.get("targetURL");
Echo.Utils.set(Echo.Variables, targetURL, "");
}
}
},
"Echo.StreamServer.Controls.CardComposer.onAutoSharingToggle": {
"context": "global",
"handler": function() {
this.view.render({"name": "postButton"});
}
}
};
/**
* @echo_template
*/
composer.templates.main =
'<div class="{class:container}">' +
'<div class="alert alert-success echo-primaryFont {class:confirmation}">' +
'{config:confirmation.message}' +
'</div>' +
'<div class="{class:header}">' +
'<div class="{class:auth}"></div>' +
'<div class="{class:nameContainer} {class:border}">' +
'<input type="text" class="echo-primaryFont echo-primaryColor {class:name}" placeholder="{label:yourName}" required>' +
'</div>' +
'</div>' +
'<div class="{class:tabs}"></div>' +
'<div class="{class:compactFieldWrapper} {class:border}">' +
'<input type="text" class="echo-primaryFont {class:compactField}" placeholder="{config:compact.prompt}">' +
'</div>' +
'<div class="{class:formWrapper}">' +
'<div class="{class:composers}"></div>' +
'<div class="{class:media}"></div>' +
'<div class="{class:metadata}">' +
'<div class="echo-primaryFont echo-primaryColor {class:markersContainer} {class:metadataContainer}">' +
'<div class="{class:metadataLabel}">{label:markers}</div>' +
'<div class="{class:metadataWrapper}">' +
'<div class="{class:metadataSubwrapper} {class:border}">' +
'<input type="text" class="echo-primaryFont {class:markers}">' +
'</div>' +
'</div>' +
'<div class="echo-clear"></div>' +
'</div>' +
'<div class="echo-primaryFont echo-primaryColor {class:tagsContainer} {class:metadataContainer}">' +
'<div class="{class:metadataLabel}">{label:tags}</div>' +
'<div class="{class:metadataWrapper}">' +
'<div class="{class:metadataSubwrapper} {class:border}">' +
'<input type="text" class="echo-primaryFont {class:tags} {class:border}">' +
'</div>' +
'</div>' +
'<div class="echo-clear"></div>' +
'</div>' +
'</div>' +
'<div class="{class:controls}">' +
'<div class="{class:postButtonWrapper}">' +
'<div class="btn btn-primary {class:postButton}"></div>' +
'<div class="btn btn-primary dropdown-toggle {class:postButtonSwitcher}" data-toggle="dropdown">' +
'<span class="caret"></span>' +
'</div>' +
'<ul class="dropdown-menu pull-right">' +
'<li><a href="#" class="{class:switchToPost}">{label:post}</a></li>' +
'<li><a href="#" class="{class:switchToPostAndShare}">{label:postAndShare}</a></li>' +
'</ul>' +
'</div>' +
'<div class="{class:attachers}">' +
'<img class="{class:attachPic}" src="{%= baseURLs.prod %}/images/attach.png">' +
'</div>' +
'<div class="echo-clear"></div>' +
'</div>' +
'</div>' +
'<div class="echo-clear"></div>' +
'</div>';
/**
* @echo_template
*/
composer.templates.post =
'<div class="echo-item-text">{data:text}</div>' +
'<div class="echo-item-files" data-composer="{data:composer}">{data:media}</div>';
/**
* @echo_renderer
*/
composer.renderers.container = function(element) {
var self = this;
var classes = $.map(["normal", "small", "smallest", "inline"], function(_class) {
return self.cssPrefix + _class;
});
element.removeClass(classes.join(" "));
var _class = this.collapsed ? this.config.get("compact.layout") : "normal";
element.addClass(this.cssPrefix + _class);
_class = this.substitute({"template": "{class:logged} {class:anonymous} {class:forcedLogin}"});
element
.removeClass(_class)
.addClass(this.cssPrefix + this._userStatus());
if (this.config.get("collapsible")) {
if (!this.toggleModeHandler) {
this.toggleModeHandler = function(event) {
if (self.collapsed) return;
var target = self.config.get("target");
var isInTarget = target && target.find(event.target).length;
if (isInTarget) return;
self.collapse();
};
$(document).on("mousedown", this.toggleModeHandler);
}
}
return element;
};
/**
* @echo_renderer
*/
composer.renderers.tabs = function(element) {
// TODO: support URL in icons
var self = this;
element.empty();
if (!this.composers.length) {
this.log({"message": "No composer plugins are found"});
return element;
}
this.tabs = new Echo.GUI.Tabs({
"target": element,
"classPrefix": this.cssPrefix + "tabs-",
"selected": this.currentComposer && this.currentComposer.index,
"entries": $.map(this.composers, function(tab) {
tab.panel = $("<div>");
return {
"id": tab.id,
"extraClass": "echo-primaryFont",
"panel": tab.panel,
"label": self.substitute({
"template": '<span class="{class:icon} {data:icon}"></span>' +
'<span class="{class:label}">{data:label}</span>',
"data": tab
})
};
}),
"panels": this.view.get("composers").empty(),
"shown": function(tab, panel, id, index) {
self.currentComposer = self.composers[index];
self._initCurrentComposer();
}
});
};
/**
* @echo_renderer
*/
composer.renderers.media = function(element) {
var self = this;
this.mediaContainer && this.mediaContainer.destroy();
if (!this.formData.media.length) return element;
this.mediaContainer = new Echo.Conversations.MediaContainer({
"target": element.empty(),
"data": this.formData.media,
"card": {
"displaySourceIcon": false,
"displayAuthor": false,
"onRemove": function(data) {
self.removeMedia(self._getDefinedMediaIndex(data));
}
}
});
return element;
};
/**
* @echo_renderer
*/
composer.renderers.tagsContainer = function(element) {
return this.user.is("admin") ? element.show() : element.hide();
};
/**
* @method
* @echo_renderer
* @param element
*/
composer.renderers.markersContainer = composer.renderers.tagsContainer;
/**
* @echo_renderer
*/
composer.renderers.markers = function(element) {
return this.view.render({
"name": "_metaFields",
"target": element,
"extra": {"type": "markers"}
});
};
/**
* @echo_renderer
*/
composer.renderers.tags = function(element) {
return this.view.render({
"name": "_metaFields",
"target": element,
"extra": {"type": "tags"}
});
};
/**
* @echo_renderer
*/
composer.renderers.compactField = function(element) {
var self = this;
return element.on("focus", function() {
self.expand();
});
};
/**
* @echo_renderer
*/
composer.renderers.auth = function(element) {
var config = $.extend(true, {
"target": element.show(),
"appkey": this.config.get("appkey"),
"apiBaseURL": this.config.get("apiBaseURL"),
"cdnBaseURL": this.config.get("cdnBaseURL")
}, this.config.get("auth"));
this.auth && this.auth.destroy();
this.auth = new Echo.StreamServer.Controls.Auth(config);
return element;
};
/**
* @echo_renderer
*/
composer.renderers.nameContainer = function(element) {
var status = this._userStatus();
if (status === "logged" || status === "forcedLogin") {
element.remove();
}
return element;
};
/**
* @echo_renderer
*/
composer.renderers.postButton = function(element) {
var self = this;
var label = this.labels.get(this._isAutoSharingEnabled() ? "postAndShare" : "post");
var states = {
"normal": {
"target": element,
"icon": false,
"disabled": false,
"label": label
},
"disabled": {
"target": element,
"icon": false,
"disabled": true,
"label": label
},
"posting": {
"target": element,
"icon": this.config.get("cdnBaseURL.sdk-assets") + "/images/loading.gif",
"disabled": true,
"label": this.labels.get("posting")
}
};
new Echo.GUI.Button(states[this.postButtonState]);
this.posting = this.posting || {};
this.posting.subscriptions = this.posting.subscriptions || [];
var subscribe = function(phase, state, callback) {
var topic = composer.name + ".onPost" + phase;
var subscriptions = self.posting.subscriptions;
if (subscriptions[topic]) {
self.events.unsubscribe({
"topic": topic,
"handlerId": subscriptions[topic]
});
}
subscriptions[topic] = self.events.subscribe({
"topic": topic,
"handler": function(topic, params) {
self._setPostButtonState(state);
if (callback) callback(params);
}
});
};
subscribe("Init", "posting", function() {
if (self.config.get("confirmation.enabled")) {
self.view.get("confirmation").hide();
}
});
subscribe("Complete", "disabled", function(data) {
if (self.config.get("confirmation.enabled")) {
var confirmation = self.view.get("confirmation").show();
setTimeout(function() {
confirmation.slideUp(self.config.get("confirmation.hidingTimeout"));
}, self.config.get("confirmation.timeout"));
}
if (self._isAutoSharingEnabled()) {
self._share(data);
}
self.removeMedia();
self.view.render({"name": "tabs"});
self.view.render({"name": "tags"});
self.view.render({"name": "markers"});
});
subscribe("Error", "normal", function(params) {
var request = params.request || {};
if (request.state && request.state.critical) {
self._showError(params);
}
});
this.posting.action = this.posting.action || function() {
if (self.postButtonState === "disabled") return;
if (self._isPostValid()) {
self.post();
}
};
element.off("click", this.posting.action).on("click", this.posting.action);
return element;
};
/**
* @echo_renderer
*/
composer.renderers.postButtonWrapper = function(element) {
var action = this.config.get("displaySharingOnPost")
? "addClass"
: "removeClass";
return element[action]("btn-group");
};
/**
* @echo_renderer
*/
composer.renderers.postButtonSwitcher = function(element) {
if (!this.config.get("displaySharingOnPost")) {
element.hide();
}
var action = this.postButtonState === "normal"
? "removeClass"
: "addClass";
return element[action]("disabled");
};
/**
* @echo_renderer
*/
composer.renderers.switchToPost = function(element) {
var self = this;
return element.off("click").on("click", function(e) {
self._switchAutoSharing("off");
e.preventDefault();
});
};
/**
* @echo_renderer
*/
composer.renderers.switchToPostAndShare = function(element) {
var self = this;
return element.off("click").on("click", function(e) {
self._switchAutoSharing("on");
e.preventDefault();
});
};
composer.renderers._metaFields = function(element, extra) {
var type = extra.type;
var data = this.get("data.object." + type, this.config.get(type));
var value = $.trim(Echo.Utils.stripTags(data.join(", ")));
return this.view.get(type).iHint({
"text": this.labels.get(type + "Hint"),
"className": "echo-secondaryColor"
}).val(value).blur();
};
/**
* Method used for posting user provided content to the
* <a href="http://echoplatform.com/streamserver/docs/rest-api/items-api/submit/" target="_blank">Echo Submit</a>
* endpoint through <a href="http://echoplatform.com/streamserver/docs/features/submission-proxy/" target="_blank">Echo Submission Proxy</a>.
*/
composer.methods.post = function() {
var self = this;
var publish = function(phase, data, responseBody, requestState) {
var args = {
"topic": "onPost" + phase,
"data": {"postData": data}
};
if (requestState || responseBody) {
args.data.request = {
"state": requestState,
"response": responseBody
};
}
self.events.publish(args);
};
var data = this.currentComposer.getData();
var text = self.substitute({
"template": composer.templates.post,
"data": {
"text": data.text,
"media": data.media,
"composer": self.currentComposer.id
}
});
var objectType = this.currentComposer.objectType || this._getASURL("comment");
var content = [].concat(
self._getActivity("post", objectType, text),
self._getActivity("tag", this._getASURL("marker"), self.view.get("markers").val()),
self._getActivity("tag", this._getASURL("tag"), self.view.get("tags").val())
);
var entry = {
"content": content,
"appkey": this.config.get("appkey"),
"sessionID": this.user.get("sessionID", "")
};
if (this.config.get("targetQuery")) {
entry["target-query"] = this.config.get("targetQuery");
}
var callbacks = {
"onData": function(response, state) {
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onPostComplete
* Triggered when the submit operation is finished.
*/
publish("Complete", entry, response, state);
/**
* @echo_event Echo.Control.onDataInvalidate
* Triggered if dataset is changed.
*/
// notify all widgets on the page about a new item posted
Echo.Events.publish({
"topic": "Echo.Control.onDataInvalidate",
"context": "global",
"data": {}
});
},
"onError": function(response, state) {
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onPostError
* Triggered if submit operation failed.
*/
publish("Error", entry, response, state);
}
};
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onPostInit
* Triggered if submit operation was started.
*/
publish("Init", entry);
Echo.StreamServer.API.request({
"endpoint": "submit",
"method": this.config.get("requestMethod"),
"itemURIPattern": this.config.get("itemURIPattern"),
"submissionProxyURL": this.config.get("submissionProxyURL"),
"timeout": this.config.get("postingTimeout"),
"secure": this.config.get("useSecureAPI"),
"data": entry,
"onData": callbacks.onData,
"onError": callbacks.onError
}).send();
};
/**
* Method highlighting the input data fields
*/
// TODO: better name
composer.methods.highlightField = function(element, message) {
if (!element) return;
var css = this.cssPrefix + "error";
element.parent().addClass(css);
element.tooltip({
"title": message,
"placement": "right",
"trigger": "hover"
});
element.focus(function() {
$(this).tooltip("destroy");
$(this).parent().removeClass(css);
});
};
composer.methods.attachMedia = function(params) {
var self = this;
params = $.extend({
"urls": [],
"removeOld": false,
"render": true
}, params);
var urls = params.urls.length && params.urls || [params.url || ""];
urls = $.map(urls, function(url) {
return $.trim(url);
});
this.resolver.resolve(urls, function(data) {
if (params.removeOld) {
self.removeMedia();
}
data = $.grep(data, function(oembed) {
return !$.isEmptyObject(oembed) && !~self._getDefinedMediaIndex(oembed);
});
if (!data.length) return;
$.each(data, function(i, oembed) {
self.formData.media.push(oembed);
});
self.view.render({"name": "media"});
});
};
composer.methods.removeMedia = function(index) {
if (typeof index === "undefined") {
this.formData.media = [];
} else if (!~index) {
return;
} else {
this.formData.media.splice(index, 1);
}
this.view.render({"name": "media"});
};
/**
* Allows to register custom post composer
*/
composer.methods.registerComposer = function(config) {
if (!config || !config.id) {
this.log({"message": "Invalid composer configuration"});
return;
}
this.composers.push(config);
};
/**
* This method adds a custom validator to check the posting possibility.
*/
composer.methods.addPostValidator = function(validator, priority) {
this.validators[priority === "low" ? "push" : "unshift"](validator);
};
/**
* Method implements the refresh logic for the Submit Composer control.
*/
/*composer.methods.refresh = function() {
var self = this;
this.config.set("data.object.content", this.view.get("text").val());
$.map(["tags", "markers"], function(field) {
var elements = self.view.get(field).val().split(", ");
self.config.set("data.object." + field, elements || []);
});
var component = Echo.Utils.getComponent("Echo.StreamServer.Controls.CardComposer");
component.parent.refresh.call(this);
};*/
composer.methods.expand = function() {
if (!this.collapsed) return;
this.collapsed = false;
this._initCurrentComposer();
this.view.render({"name": "container"});
this.events.publish({"topic": "onExpand"});
};
composer.methods.collapse = function() {
if (this.collapsed) return;
this.collapsed = true;
this.view.render({"name": "container"});
this.events.publish({"topic": "onCollapse"});
};
composer.methods._initCurrentComposer = function() {
if (this.collapsed) return;
var self = this;
var composer = this.currentComposer;
if (!composer.panel.children().length) {
composer.panel.append(composer.composer());
composer.setData($.extend(true, {}, this.formData));
}
// timeout allows form fields to be added to target element DOM
setTimeout(function() {
self._initFormFields();
}, 0);
};
composer.methods._extractInfoFromExternalData = function() {
var self = this;
this.formData = {
"text": "",
"media": []
};
var data = this.config.get("data");
if (!data || $.isEmptyObject(data)) return;
Echo.Utils.safelyExecute(function() {
var content = $("<div>").append(self.config.get("data.object.content"));
//self.set("content", self.config.get("data.object.content"));
self.formData.text = $(".echo-item-text", content).html();
if (/*self.get("content") !== item.get("data.object.content") || */!self.formData.media.length) {
self.formData.media = $("div[oembed], div[data-oembed]", content).map(function() {
return $.parseJSON($(this).attr("oembed") || $(this).attr("data-oembed"));
}).get();
}
var composer = $(".echo-item-files", content).data("composer");
var types = self.config.get("data.object.objectTypes");
$.each(self.composers, function(i, data) {
if (data.id === composer) {
self.currentComposer = data;
return false;
}
var matches = $.grep(types, function(type) {
return data.objectType === type;
});
if (matches.length) {
self.currentComposer = data;
return false;
}
});
});
};
composer.methods._htmlEncode = function(json) {
return JSON.stringify(json)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
};
composer.methods._getDefinedMediaIndex = function(oembed) {
var found = false, index = -1;
var fields = ["original_url", "url", "title", "author_name"];
var fieldsByType = {
"link": fields.slice(),
"photo": fields.slice(),
"video": fields.slice().concat("html")
};
$.each(this.formData.media, function(i, media) {
if (media.type !== oembed.type) return;
$.each(fieldsByType[oembed.type], function(j, field) {
found = true;
if (typeof media[field] !== "undefined" &&
media[field] !== oembed[field]
) {
found = false;
return false;
}
});
if (found) {
index = i;
return false;
}
});
return index;
};
composer.methods._initFormFields = function() {
var self = this, nonEmpty = {};
var init = function(container, id) {
var timer;
nonEmpty[id] = [];
var fields = container.find("input[type=text][required], textarea[required]");
if (id === "_global") {
// filter out composer fields while searching for global fields
fields = fields.map(function(i, el) {
if ($(el).closest("." + self.cssPrefix + "formWrapper", container).length) {
return null;
}
return el;
});
}
return fields
.off("keyup.cardComposer paste.cardComposer")
.on("keyup.cardComposer paste.cardComposer", function() {
clearTimeout(timer);
var el = this;
timer = setTimeout(function() {
process(el, id);
}, 100);
});
};
var process = function(el, id) {
var idx = nonEmpty[id].indexOf(el);
if ($.trim($(el).val())) {
if (idx === -1) nonEmpty[id].push(el);
} else {
if (idx !== -1) nonEmpty[id].splice(idx, 1);
}
var actual = nonEmpty["_global"].length + nonEmpty[self.currentComposer.id].length;
var expected = globalFields.length + composerFields.length;
self._setPostButtonState(actual === expected ? "normal" : "disabled");
};
this.config.get("target")
.find("input[type=text], textarea")
.each(function() {
var el = $(this);
if (el.prop("echo-processed")) return;
el.prop("echo-processed", true);
var hint = el.attr("placeholder");
if (hint) {
el.placeholder();
if (el.attr("required")) {
el.attr("placeholder", hint + self.labels.get("required"));
}
}
});
var globalFields = init(this.config.get("target"), "_global");
var composerFields = init(this.currentComposer.panel, this.currentComposer.id);
if (!globalFields.length && !composerFields.length) {
this._setPostButtonState("normal");
return;
}
globalFields.each(function(i, el) {
process(el, "_global");
});
composerFields.each(function(i, el) {
process(el, self.currentComposer.id);
});
};
composer.methods._setPostButtonState = function(state) {
if (state === this.postButtonState) return;
this.postButtonState = state;
this.view.render({"name": "postButton"});
this.view.render({"name": "postButtonSwitcher"});
};
composer.methods._switchAutoSharing = function(state) {
var enabled = this._isAutoSharingEnabled();
if (enabled ^ (state !== "on")) return;
Echo.Cookie.set("sharingOnPost", state === "on");
Echo.Events.publish({
"topic": composer.name + ".onAutoSharingToggle",
"context": "global"
});
};
composer.methods._isAutoSharingEnabled = function(state) {
return this.config.get("displaySharingOnPost") &&
Echo.Cookie.get("sharingOnPost") === "true";
};
composer.methods._share = function(data) {
// XXX: garantee that first element is "post" and ignore "update"
var item = data.postData.content[0];
var payload = {
"origin": "item",
"actor": {
"id": this.user.get("identityUrl"),
"name": item.actor.name,
"avatar": item.actor.avatar
},
"object": {
"id": data.request.response.objectID,
"content": item.object.content
},
"source": item.source,
"target": item.targets[0].id
};
Backplane.response([{
// IMPORTANT: we use ID of the last received message
// from the server-side to avoid same messages re-processing
// because of the "since" parameter cleanup...
"id": Backplane.since,
"channel_name": Backplane.getChannelName(),
"message": {
"type": "content/share/request",
"payload": payload
}
}]);
};
composer.methods._requestLoginPrompt = function() {
Backplane.response([{
// IMPORTANT: we use ID of the last received message
// from the server-side to avoid same messages re-processing
// because of the "since" parameter cleanup...
"id": Backplane.since,
"channel_name": Backplane.getChannelName(),
"message": {
"type": "identity/login/request",
"payload": this.user.data || {}
}
}]);
};
composer.methods._userStatus = function() {
return this.user.is("logged")
? "logged"
: this.config.get("submitPermissions") === "forceLogin"
? "forcedLogin"
: "anonymous";
};
composer.methods._getActivity = function(verb, type, data) {
return !data ? [] : {
"actor": {
"objectTypes": [this._getASURL("person")],
"name": this.user.get("name", this.user.is("logged")
? ""
: this.view.get("name").val()),
"avatar": this.user.get("avatar", "")
},
"object": {
"objectTypes": [type],
"content": data
},
"source": this.config.get("source"),
"verbs": [this._getASURL(verb)],
"targets": [{
"id": this.config.get("targetURL")
}]
};
};
composer.methods._getASURL = function(postfix) {
return "http://activitystrea.ms/schema/1.0/" + postfix;
};
composer.methods._showError = function(data) {
data = data || {};
var response = data.request && data.request.response || {};
var message = $.inArray(response.errorCode, ["network_timeout", "connection_failure"]) >= 0
? this.labels.get("postingTimeout")
: this.labels.get("postingFailed", {"error": response.errorMessage || response.errorCode});
var popup = this._assembleErrorPopup(message);
new Echo.GUI.Modal({
"data": {
"body": popup.content
},
"width": popup.width,
"footer": false,
"fade": true,
"show": true
});
};
composer.methods._assembleErrorPopup = function(message) {
var dimensions = this.config.get("errorPopup");
var template = this.substitute({
"template": '<div class="{data:css}">{data:message}</div>',
"data": {
"message": message,
"css": this.cssPrefix + "error"
}
});
var popup = {
"content": $(template).css({
"min-height": dimensions.minHeight,
"max-height": dimensions.maxHeight
}),
"width": dimensions.width
};
return popup;
};
composer.methods._isPostValid = function() {
var valid = true;
$.each(this.validators, function(i, handler) {
valid = handler();
return valid;
});
return valid;
};
composer.methods._prepareEventParams = function(params) {
return $.extend(params, {
"data": this.get("data"),
"target": this.config.get("target").get(0),
"targetURL": this.config.get("targetURL")
});
};
composer.css =
'.{class:header} { margin-bottom: 10px; }' +
'.{class:anonymous} .{class:header} { margin-bottom: 7px; }' +
'.{class:auth} { display: none; }' +
'.{class:nameContainer} { margin: 11px 0px 0px 0px; padding: 3px 2px 3px 5px; }' +
'.{class:nameContainer} input.{class:name}[type="text"] { font-size: 14px; border: none; width: 100%; margin-bottom: 0px; padding: 0px; outline: 0; box-shadow: none; background-color: transparent; }' +
'.{class:nameContainer} input.{class:name}[type="text"]:focus { outline: 0; box-shadow: none; }' +
'.{class:nameContainer} input.{class:name}[type="text"].echo-secondaryColor,' +
'.{class:container} .{class:metadataSubwrapper} input.echo-secondaryColor[type="text"]' +
' { color: #C6C6C6; }' +
'.{class:compactFieldWrapper} { padding: 4px 8px; background-color: #fff; }' +
'.{class:compactFieldWrapper} input.{class:compactField}[type="text"] { border: none; width: 100%; margin-bottom: 0px; padding: 0px; outline: 0; box-shadow: none; font-size: 12px; }' +
'.{class:metadataContainer} { margin-top: 6px; }' +
'.{class:metadataLabel} { float: left; width: 50px; margin-right: -50px; text-align: right; line-height: 22px; }' +
'.{class:metadataWrapper} { float: left; width: 100%; }' +
'.{class:metadataSubwrapper} { margin-left: 55px; padding: 2px 2px 2px 3px; background-color: #fff; }' +
'.{class:container} { padding: 20px; border: 1px solid #d8d8d8; border-bottom-width: 2px; border-radius: 3px; }' +
'.{class:container} .{class:metadataSubwrapper} input[type="text"] { width: 100%; border: 0; padding: 0px; outline: 0; box-shadow: none; margin-bottom: 0px; }' +
'.{class:container} .{class:metadataSubwrapper} input[type="text"]:focus { outline: 0; box-shadow: none; }' +
'.{class:composers} { margin: 0px; border: 1px solid #dedede; border-width: 0px 1px; }' +
'.{class:controls} { margin: 0px; padding: 5px; border: 1px solid #d8d8d8; background-color: transparent; }' +
'.{class:confirmation} { margin-bottom: 10px; display: none; }' +
'.{class:attachers} { display: none; margin: 5px; float: left; }' +
'.{class:postButtonWrapper} { float: right; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; }' +
'.{class:postButtonWrapper} .dropdown-menu { min-width: 100px; }' +
'.{class:postButtonWrapper} .{class:postButton}.btn { padding: 3px 12px 5px 12px; }' +
'.{class:tagsContainer} { display: none !important; }' +
'.{class:markersContainer} { display: none !important; }' +
'.{class:border} { border: 1px solid #d8d8d8; }' +
'.{class:mandatory} { border: 1px solid red; }' +
'.{class:queriesViewOption} { padding-right: 5px; }' +
'.echo-sdk-ui .{class:composers} input[type=text], .echo-sdk-ui .{class:composers} textarea { width: 100%; border: 0px; resize: none; outline: none; box-shadow: none; padding: 0px; margin: 0px; background-color: transparent; }' +
'.echo-sdk-ui .{class:container} input[type=text]:focus, .echo-sdk-ui .{class:composers} textarea:focus { outline: none; box-shadow: none; }' +
'.echo-sdk-ui .{class:container} input[type=text]:focus:invalid,' +
'.echo-sdk-ui .{class:container} input[type=text]:focus:invalid:focus,' +
'.echo-sdk-ui .{class:container} textarea:focus:invalid,' +
'.echo-sdk-ui .{class:container} textarea:focus:invalid:focus' +
'{ color: #3c3c3c; border-color: transparent; box-shadow: none; }' +
'.echo-cardcomposer-delimiter { height: 0px; border-top: 1px dashed #d8d8d8; }' +
'.echo-cardcomposer-field-wrapper { padding: 7px 11px; border: 1px solid transparent; display: inline-block; width: 100%; box-sizing: border-box !important/* XXX: because of conversations*/; }' +
'.{class:error} { border: 1px solid red; }' +
'.{class:error} input, .{class:error} textarea { background: no-repeat center right url({config:cdnBaseURL.sdk-assets}/images/warning.gif); }' +
'.{class:media} .echo-conversations-mediacontainer-multiple { border: 1px solid #DEDEDE; border-top-style: dashed; border-bottom: 0px; background-color: #F1F1F1; }' +
// display modes
'.{class:normal} .{class:compactFieldWrapper},' +
'.{class:small} .{class:formWrapper},' +
'.{class:smallest} .{class:formWrapper},' +
'.{class:smallest} .{class:header} { display: none; }' +
'.echo-sdk-ui .{class:inline} .nav-tabs,' +
'.{class:inline} .{class:formWrapper},' +
'.{class:inline}.{class:anonymous} .{class:header},' +
'.{class:inline} .echo-streamserver-controls-auth-container { display: none; }' +
'.{class:inline} .{class:compactFieldWrapper} { margin-left: 38px; }' +
'.{class:inline}.{class:anonymous} .{class:compactFieldWrapper} { margin-left: 0px; }' +
'.{class:inline}.{class:container}:not(.{class:anonymous}) { padding-left: 12px; }' +
'.{class:inline} .{class:header} { float: left; margin: 0px; }' +
'.{class:inline} .echo-streamserver-controls-auth-avatarContainer,' +
'.{class:inline} .echo-streamserver-controls-auth-avatar { width: 28px; height: 28px; }' +
'.echo-sdk-ui .{class:small} .nav-tabs,' +
'.echo-sdk-ui .{class:smallest} .nav-tabs { border-bottom-width: 0px; }' +
// tabs
'.{class:icon} { vertical-align: middle; margin-right: 2px; }' +
'.echo-sdk-ui .{class:tabs} .nav { margin-bottom: 0px; }' +
'.echo-sdk-ui .{class:tabs} .nav > li > a { padding: 0px; margin-right: 10px; border: 0px; color: #3c3c3c; background-color: transparent; opacity: 0.5; }' +
'.echo-sdk-ui .{class:tabs} .nav > li > a:hover, .echo-sdk-ui .{class:tabs} .nav > li > a:focus { background-color: transparent; border: 0px; }' +
'.echo-sdk-ui .{class:tabs} .nav > li.active > a,' +
'.echo-sdk-ui .{class:tabs} .nav > li.active > a:hover,' +
'.echo-sdk-ui .{class:tabs} .nav > li.active > a:focus,' +
'.echo-sdk-ui .{class:tabs} .nav > li.active > a:active { border: 0px; border-bottom: 4px solid #d8d8d8; color: #3c3c3c; background-color: transparent; opacity: 1; }' +
'';
Echo.Control.create(composer);
})(Echo.jQuery);
| sdk-derived/controls/card-composer.js | (function(jQuery) {
"use strict";
var $ = jQuery;
/**
* @class Echo.StreamServer.Controls.CardComposer
* Echo Submit control which encapsulates interaction with the
* <a href="http://echoplatform.com/streamserver/docs/rest-api/items-api/submit/" target="_blank">Echo Submit API</a>.
*
* new Echo.StreamServer.Controls.CardComposer({
* "target": document.getElementById("composer"),
* "targetURL": "http://example.com/composer",
* "appkey": "echo.jssdk.demo.aboutecho.com",
* });
*
* More information regarding the possible ways of the Control initialization
* can be found in the [“How to initialize Echo components”](#!/guide/how_to_initialize_components-section-initializing-an-app) guide.
*
* @extends Echo.Control
*
* @package streamserver/controls.pack.js
* @package streamserver.pack.js
*
* @constructor
* Submit constructor initializing Echo.StreamServer.Controls.CardComposer class
*
* @param {Object} config
* Configuration options
*/
var composer = Echo.Control.manifest("Echo.StreamServer.Controls.CardComposer");
if (Echo.Control.isDefined(composer)) return;
/** @hide @cfg apiBaseURL */
/** @hide @method placeImage */
/** @hide @method getRelativeTime */
/** @hide @echo_label justNow */
/** @hide @echo_label today */
/** @hide @echo_label yesterday */
/** @hide @echo_label lastWeek */
/** @hide @echo_label lastMonth */
/** @hide @echo_label secondAgo */
/** @hide @echo_label secondsAgo */
/** @hide @echo_label minuteAgo */
/** @hide @echo_label minutesAgo */
/** @hide @echo_label hourAgo */
/** @hide @echo_label hoursAgo */
/** @hide @echo_label dayAgo */
/** @hide @echo_label daysAgo */
/** @hide @echo_label weekAgo */
/** @hide @echo_label weeksAgo */
/** @hide @echo_label monthAgo */
/** @hide @echo_label monthsAgo */
/** @hide @echo_label loading */
/** @hide @echo_label retrying */
/** @hide @echo_label error_busy */
/** @hide @echo_label error_timeout */
/** @hide @echo_label error_waiting */
/** @hide @echo_label error_view_limit */
/** @hide @echo_label error_view_update_capacity_exceeded */
/** @hide @echo_label error_result_too_large */
/** @hide @echo_label error_wrong_query */
/** @hide @echo_label error_incorrect_appkey */
/** @hide @echo_label error_internal_error */
/** @hide @echo_label error_quota_exceeded */
/** @hide @echo_label error_incorrect_user_id */
/** @hide @echo_label error_unknown */
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onReady
* Triggered when the app initialization is finished completely.
*/
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onRefresh
* Triggered when the app is refreshed. For example after the user
* login/logout action or as a result of the "refresh" function call.
*/
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onRender
* Triggered when the app is rendered.
*/
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onRerender
* Triggered when the app is rerendered.
*/
composer.init = function() {
var self = this;
if (!this.checkAppKey()) return;
this.addPostValidator(function() {
if (self.user.is("logged")) return true;
var isGuestAllowed = self.config.get("submitPermissions") === "allowGuest";
if (!isGuestAllowed) {
self.set("_deferredActivity", $.proxy(self.posting.action, self));
self._requestLoginPrompt();
return false;
}
return true;
}, "low");
var tabsUniqueId = Echo.Utils.getUniqueString();
$.each(this.composers, function(i, tab) {
tab.index = i;
tab.uniqueId = tab.id + "-" + tabsUniqueId;
if (!$.isFunction(tab.isValid)) return;
self.addPostValidator(function() {
if (self.currentComposer.id !== tab.id) return true;
return tab.isValid();
}, "low");
});
this.resolver = new Echo.URLResolver({
"embedly": this.config.get("dependencies.embedly")
});
this.collapsed = this.config.get("initialMode") === "collapsed";
this._extractInfoFromExternalData();
this.render();
this.ready();
};
composer.destroy = function() {
this.auth && this.auth.destroy();
this.tabs && this.tabs.destroy();
this.mediaContainer && this.mediaContainer.destroy();
this.toggleModeHandler && $(document).off("mousedown", this.toggleModeHandler);
};
composer.config = {
/**
* @cfg {String} [targetURL=document.location.href]
* Specifies the URI to which the submitted Echo item is related.
* This parameter will be used as a activity target value for the item.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "targetURL": "http://somedomain.com/some_article.html",
* ...
* });
*/
"targetURL": document.location.href,
/**
* @cfg {Object} contentTypes
*
* @cfg {Object} contentTypes.comments
*
* @cfg {String} contentTypes.comments.prompt
* Is used to define the default call to action phrase.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "contentTypes": {
* "comments": {
* "prompt": "Type your comment here..."
* }
* }
* ...
* });
*/
"contentTypes": {
"comments": {
"visible": true,
"prompt": "What's on your mind?",
"resolveURLs": true
}
},
/**
* @cfg {Array} markers
* This parameter is used to attach the markers metadata to the item
* during the item submission. The format of the value is the array
* with the string values. Markers will also be displayed in the "Markers"
* field in the Submit form UI for Moderators and Administrators.
* For non-admin users the markers value will be submitted along with
* other item content when the "Post" button is pressed.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "markers": ["marker1", "marker2", "marker3"],
* ...
* });
*/
"markers": [],
/**
* @cfg {Object} source
* Designates the initial item source (E.g. Twitter). You can override
* source name, URI and the corresponding icon.
*
* @cfg {String} source.name
* Source name.
*
* @cfg {String} source.uri
* Source uri.
*
* @cfg {String} source.icon
* Source icon.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "source": {
* "name": "ExampleSource",
* "uri": "http://example.com/",
* "icon": "http://example.com/images/source.png"
* },
* ...
* });
*/
"source": {},
/**
* @cfg {Array} tags
* This parameter is used to attach the tags metadata to the item during
* the item submission. The format of the value is the array array with
* the string values. Tags will be also displayed in the "Tags" field in
* the Submit form UI for Moderators and Administrators. For non-admin
* users the tags value will be submitted along with the other item
* content when the "Post" button is pressed.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "tags": ["tag1", "tag2", "tag3"],
* ...
* });
*/
"tags": [],
/**
* @cfg {String} requestMethod
* This parameter is used to specify the request method. Possible values
* are "GET" and "POST". Setting parameter to "POST" has some restrictions.
* We can't handle server response, UI won't show any waiting for the
* server responses actions.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "requestMethod": "POST",
* ...
* });
*/
"requestMethod": "GET",
/**
* @cfg {String} itemURIPattern
* Allows to define item id pattern. The value of this parameter should be
* a valid URI with "{id}" placeholder which will indicate the place where
* unique id should be inserted. If this parameter is ommited in
* configuration or the URI is invalid it'll be ignored.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "itemURIPattern": "http://your-domain.com/path/{id}",
* ...
* });
*/
"itemURIPattern": undefined,
/**
* @cfg {Number} postingTimeout
* Is used to specify the number of seconds after which the Submit Form will show
* the timeout error dialog if the server does not return anything. If the parameter
* value is 0 then the mentioned dialog will never be shown.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "postingTimeout": 15,
* ...
* });
*/
"postingTimeout": 30,
/**
* @cfg {Object} errorPopup
* Is used to define dimensions of error message popup. The value of this parameter
* is an object with the following fields:
*
* @cfg {Number} errorPopup.minHeight
* The minimum height of error message popup.
*
* @cfg {Number} errorPopup.maxHeight
* The maximum height of error message popup.
*
* @cfg {Number} errorPopup.width
* The width of error message popup.
*
* new Echo.StreamServer.Controls.CardComposer({
* ...
* "errorPopup": {
* "minHeight": 70,
* "maxHeight": 150,
* "width": 390
* }
* ...
* });
*/
"errorPopup": {
"minHeight": 70,
"maxHeight": 150,
"width": 390
},
/**
* @cfg {Object} auth
* Configuration options as described in Echo.IdentityServer.Controls.Auth documentation.
*/
"auth": {},
"dependencies": {
"FilePicker": {
"apiKey": undefined
},
"embedly": {
"apiKey": undefined,
"maxDescriptionCharacters": "200"
}
},
"initialMode": "expanded", // expanded || collapsed
"collapsible": false,
"compact": {
"layout": "inline", // small || smallest || inline
"prompt": "Contribute here"
},
"displaySharingOnPost": true,
"submitPermissions": "forceLogin",
"confirmation": {
"enabled": false,
"message": "Thanks, your post has been submitted for review",
"timeout": 5000,
"hidingTimeout": 200
},
"targetQuery": undefined
};
composer.vars = {
"collapsed": false,
"toggleModeHandler": undefined,
"postButtonState": "disabled",
"formData": {
"text": "",
"media": []
},
"composers": [],
"validators": []
};
composer.dependencies = [{
"url": "{%= baseURLs.prod %}/controls/nested-card.js",
"loaded": function() { return !!Echo.Conversations.NestedCard; }
}, {
"url": "{%= baseURLs.prod %}/controls/media-container.js",
"loaded": function() { return !!Echo.Conversations.MediaContainer; }
}, {
"url": "{%= baseURLs.prod %}/third-party/jquery.placeholder.js",
"loaded": function() { return !!$.placeholder; }
}, {
"loaded": function() { return !!Echo.GUI; },
"url": "{config:cdnBaseURL.sdk}/gui.pack.js"
}, {
"url": "{config:cdnBaseURL.sdk}/gui.pack.css"
}];
composer.labels = {
/**
* @echo_label
*/
"markers": "Markers:",
/**
* @echo_label
*/
"markersHint": "Marker1, marker2, marker3, ...",
/**
* @echo_label
* Label for the button allowing to submit form
*/
"post": "Post",
/**
* @echo_label
*/
"postAndShare": "Post and Share",
/**
* @echo_label
*/
"posting": "Posting...",
/**
* @echo_label
*/
"postingFailed": "There was a server error while trying to submit your item. Please try again in a few minutes. <b>Error: \"{error}\"</b>.",
/**
* @echo_label
*/
"postingTimeout": "There was a network issue while trying to submit your item. Please try again in a few minutes.",
/**
* @echo_label
*/
"tagsHint": "Tag1, tag2, tag3, ...",
/**
* @echo_label
*/
"tags": "Tags:",
/**
* @echo_label
*/
"yourName": "Your Name",
/**
* @echo_label
*/
"required": " (required)"
};
composer.events = {
"Echo.UserSession.onInvalidate": {
"context": "global",
"handler": function() {
if (this.get("_deferredActivity")) {
this.get("_deferredActivity")();
this.remove("_deferredActivity");
// clearing up saved text...
var targetURL = this.config.get("targetURL");
Echo.Utils.set(Echo.Variables, targetURL, "");
}
}
},
"Echo.StreamServer.Controls.CardComposer.onAutoSharingToggle": {
"context": "global",
"handler": function() {
this.view.render({"name": "postButton"});
}
}
};
/**
* @echo_template
*/
composer.templates.main =
'<div class="{class:container}">' +
'<div class="alert alert-success echo-primaryFont {class:confirmation}">' +
'{config:confirmation.message}' +
'</div>' +
'<div class="{class:header}">' +
'<div class="{class:auth}"></div>' +
'<div class="{class:nameContainer} {class:border}">' +
'<input type="text" class="echo-primaryFont echo-primaryColor {class:name}" placeholder="{label:yourName}" required>' +
'</div>' +
'</div>' +
'<div class="{class:tabs}"></div>' +
'<div class="{class:compactFieldWrapper} {class:border}">' +
'<input type="text" class="echo-primaryFont {class:compactField}" placeholder="{config:compact.prompt}">' +
'</div>' +
'<div class="{class:formWrapper}">' +
'<div class="{class:composers}"></div>' +
'<div class="{class:media}"></div>' +
'<div class="{class:metadata}">' +
'<div class="echo-primaryFont echo-primaryColor {class:markersContainer} {class:metadataContainer}">' +
'<div class="{class:metadataLabel}">{label:markers}</div>' +
'<div class="{class:metadataWrapper}">' +
'<div class="{class:metadataSubwrapper} {class:border}">' +
'<input type="text" class="echo-primaryFont {class:markers}">' +
'</div>' +
'</div>' +
'<div class="echo-clear"></div>' +
'</div>' +
'<div class="echo-primaryFont echo-primaryColor {class:tagsContainer} {class:metadataContainer}">' +
'<div class="{class:metadataLabel}">{label:tags}</div>' +
'<div class="{class:metadataWrapper}">' +
'<div class="{class:metadataSubwrapper} {class:border}">' +
'<input type="text" class="echo-primaryFont {class:tags} {class:border}">' +
'</div>' +
'</div>' +
'<div class="echo-clear"></div>' +
'</div>' +
'</div>' +
'<div class="{class:controls}">' +
'<div class="{class:postButtonWrapper}">' +
'<div class="btn btn-primary {class:postButton}"></div>' +
'<div class="btn btn-primary dropdown-toggle {class:postButtonSwitcher}" data-toggle="dropdown">' +
'<span class="caret"></span>' +
'</div>' +
'<ul class="dropdown-menu pull-right">' +
'<li><a href="#" class="{class:switchToPost}">{label:post}</a></li>' +
'<li><a href="#" class="{class:switchToPostAndShare}">{label:postAndShare}</a></li>' +
'</ul>' +
'</div>' +
'<div class="{class:attachers}">' +
'<img class="{class:attachPic}" src="{%= baseURLs.prod %}/images/attach.png">' +
'</div>' +
'<div class="echo-clear"></div>' +
'</div>' +
'</div>' +
'<div class="echo-clear"></div>' +
'</div>';
/**
* @echo_template
*/
composer.templates.post =
'<div class="echo-item-text">{data:text}</div>' +
'<div class="echo-item-files" data-composer="{data:composer}">{data:media}</div>';
/**
* @echo_renderer
*/
composer.renderers.container = function(element) {
var self = this;
var classes = $.map(["normal", "small", "smallest", "inline"], function(_class) {
return self.cssPrefix + _class;
});
element.removeClass(classes.join(" "));
var _class = this.collapsed ? this.config.get("compact.layout") : "normal";
element.addClass(this.cssPrefix + _class);
_class = this.substitute({"template": "{class:logged} {class:anonymous} {class:forcedLogin}"});
element
.removeClass(_class)
.addClass(this.cssPrefix + this._userStatus());
if (this.config.get("collapsible")) {
if (!this.toggleModeHandler) {
this.toggleModeHandler = function(event) {
if (self.collapsed) return;
var target = self.config.get("target");
var isInTarget = target && target.find(event.target).length;
if (isInTarget) return;
self.collapse();
};
$(document).on("mousedown", this.toggleModeHandler);
}
}
return element;
};
/**
* @echo_renderer
*/
composer.renderers.tabs = function(element) {
// TODO: support URL in icons
var self = this;
element.empty();
if (!this.composers.length) {
this.log({"message": "No composer plugins are found"});
return element;
}
this.tabs = new Echo.GUI.Tabs({
"target": element,
"classPrefix": this.cssPrefix + "tabs-",
"selected": this.currentComposer && this.currentComposer.index,
"entries": $.map(this.composers, function(tab) {
tab.panel = $("<div>");
return {
"id": tab.id,
"extraClass": "echo-primaryFont",
"panel": tab.panel,
"label": self.substitute({
"template": '<span class="{class:icon} {data:icon}"></span>' +
'<span class="{class:label}">{data:label}</span>',
"data": tab
})
};
}),
"panels": this.view.get("composers").empty(),
"shown": function(tab, panel, id, index) {
self.currentComposer = self.composers[index];
self._initCurrentComposer();
}
});
};
/**
* @echo_renderer
*/
composer.renderers.media = function(element) {
var self = this;
this.mediaContainer && this.mediaContainer.destroy();
if (!this.formData.media.length) return element;
this.mediaContainer = new Echo.Conversations.MediaContainer({
"target": element.empty(),
"data": this.formData.media,
"card": {
"displaySourceIcon": false,
"displayAuthor": false,
"onRemove": function(data) {
self.removeMedia(self._getDefinedMediaIndex(data));
}
}
});
return element;
};
/**
* @echo_renderer
*/
composer.renderers.tagsContainer = function(element) {
return this.user.is("admin") ? element.show() : element.hide();
};
/**
* @method
* @echo_renderer
* @param element
*/
composer.renderers.markersContainer = composer.renderers.tagsContainer;
/**
* @echo_renderer
*/
composer.renderers.markers = function(element) {
return this.view.render({
"name": "_metaFields",
"target": element,
"extra": {"type": "markers"}
});
};
/**
* @echo_renderer
*/
composer.renderers.tags = function(element) {
return this.view.render({
"name": "_metaFields",
"target": element,
"extra": {"type": "tags"}
});
};
/**
* @echo_renderer
*/
composer.renderers.compactField = function(element) {
var self = this;
return element.on("focus", function() {
self.expand();
});
};
/**
* @echo_renderer
*/
composer.renderers.auth = function(element) {
var config = $.extend(true, {
"target": element.show(),
"appkey": this.config.get("appkey"),
"apiBaseURL": this.config.get("apiBaseURL"),
"cdnBaseURL": this.config.get("cdnBaseURL")
}, this.config.get("auth"));
this.auth && this.auth.destroy();
this.auth = new Echo.StreamServer.Controls.Auth(config);
return element;
};
/**
* @echo_renderer
*/
composer.renderers.nameContainer = function(element) {
var status = this._userStatus();
if (status === "logged" || status === "forcedLogin") {
element.remove();
}
return element;
};
/**
* @echo_renderer
*/
composer.renderers.postButton = function(element) {
var self = this;
var label = this.labels.get(this._isAutoSharingEnabled() ? "postAndShare" : "post");
var states = {
"normal": {
"target": element,
"icon": false,
"disabled": false,
"label": label
},
"disabled": {
"target": element,
"icon": false,
"disabled": true,
"label": label
},
"posting": {
"target": element,
"icon": this.config.get("cdnBaseURL.sdk-assets") + "/images/loading.gif",
"disabled": true,
"label": this.labels.get("posting")
}
};
new Echo.GUI.Button(states[this.postButtonState]);
this.posting = this.posting || {};
this.posting.subscriptions = this.posting.subscriptions || [];
var subscribe = function(phase, state, callback) {
var topic = composer.name + ".onPost" + phase;
var subscriptions = self.posting.subscriptions;
if (subscriptions[topic]) {
self.events.unsubscribe({
"topic": topic,
"handlerId": subscriptions[topic]
});
}
subscriptions[topic] = self.events.subscribe({
"topic": topic,
"handler": function(topic, params) {
self._setPostButtonState(state);
if (callback) callback(params);
}
});
};
subscribe("Init", "posting", function() {
if (self.config.get("confirmation.enabled")) {
self.view.get("confirmation").hide();
}
});
subscribe("Complete", "disabled", function(data) {
if (self.config.get("confirmation.enabled")) {
var confirmation = self.view.get("confirmation").show();
setTimeout(function() {
confirmation.slideUp(self.config.get("confirmation.hidingTimeout"));
}, self.config.get("confirmation.timeout"));
}
if (self._isAutoSharingEnabled()) {
self._share(data);
}
self.removeMedia();
self.view.render({"name": "tabs"});
self.view.render({"name": "tags"});
self.view.render({"name": "markers"});
});
subscribe("Error", "normal", function(params) {
var request = params.request || {};
if (request.state && request.state.critical) {
self._showError(params);
}
});
this.posting.action = this.posting.action || function() {
if (self.postButtonState === "disabled") return;
if (self._isPostValid()) {
self.post();
}
};
element.off("click", this.posting.action).on("click", this.posting.action);
return element;
};
/**
* @echo_renderer
*/
composer.renderers.postButtonWrapper = function(element) {
var action = this.config.get("displaySharingOnPost")
? "addClass"
: "removeClass";
return element[action]("btn-group");
};
/**
* @echo_renderer
*/
composer.renderers.postButtonSwitcher = function(element) {
if (!this.config.get("displaySharingOnPost")) {
element.hide();
}
var action = this.postButtonState === "normal"
? "removeClass"
: "addClass";
return element[action]("disabled");
};
/**
* @echo_renderer
*/
composer.renderers.switchToPost = function(element) {
var self = this;
return element.off("click").on("click", function(e) {
self._switchAutoSharing("off");
e.preventDefault();
});
};
/**
* @echo_renderer
*/
composer.renderers.switchToPostAndShare = function(element) {
var self = this;
return element.off("click").on("click", function(e) {
self._switchAutoSharing("on");
e.preventDefault();
});
};
composer.renderers._metaFields = function(element, extra) {
var type = extra.type;
var data = this.get("data.object." + type, this.config.get(type));
var value = $.trim(Echo.Utils.stripTags(data.join(", ")));
return this.view.get(type).iHint({
"text": this.labels.get(type + "Hint"),
"className": "echo-secondaryColor"
}).val(value).blur();
};
/**
* Method used for posting user provided content to the
* <a href="http://echoplatform.com/streamserver/docs/rest-api/items-api/submit/" target="_blank">Echo Submit</a>
* endpoint through <a href="http://echoplatform.com/streamserver/docs/features/submission-proxy/" target="_blank">Echo Submission Proxy</a>.
*/
composer.methods.post = function() {
var self = this;
var publish = function(phase, data, responseBody, requestState) {
var args = {
"topic": "onPost" + phase,
"data": {"postData": data}
};
if (requestState || responseBody) {
args.data.request = {
"state": requestState,
"response": responseBody
};
}
self.events.publish(args);
};
var data = this.currentComposer.getData();
var text = self.substitute({
"template": composer.templates.post,
"data": {
"text": data.text,
"media": data.media,
"composer": self.currentComposer.id
}
});
var objectType = this.currentComposer.objectType || this._getASURL("comment");
var content = [].concat(
self._getActivity("post", objectType, text),
self._getActivity("tag", this._getASURL("marker"), self.view.get("markers").val()),
self._getActivity("tag", this._getASURL("tag"), self.view.get("tags").val())
);
var entry = {
"content": content,
"appkey": this.config.get("appkey"),
"sessionID": this.user.get("sessionID", "")
};
if (this.config.get("targetQuery")) {
entry["target-query"] = this.config.get("targetQuery");
}
var callbacks = {
"onData": function(response, state) {
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onPostComplete
* Triggered when the submit operation is finished.
*/
publish("Complete", entry, response, state);
/**
* @echo_event Echo.Control.onDataInvalidate
* Triggered if dataset is changed.
*/
// notify all widgets on the page about a new item posted
Echo.Events.publish({
"topic": "Echo.Control.onDataInvalidate",
"context": "global",
"data": {}
});
},
"onError": function(response, state) {
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onPostError
* Triggered if submit operation failed.
*/
publish("Error", entry, response, state);
}
};
/**
* @echo_event Echo.StreamServer.Controls.CardComposer.onPostInit
* Triggered if submit operation was started.
*/
publish("Init", entry);
Echo.StreamServer.API.request({
"endpoint": "submit",
"method": this.config.get("requestMethod"),
"itemURIPattern": this.config.get("itemURIPattern"),
"submissionProxyURL": this.config.get("submissionProxyURL"),
"timeout": this.config.get("postingTimeout"),
"secure": this.config.get("useSecureAPI"),
"data": entry,
"onData": callbacks.onData,
"onError": callbacks.onError
}).send();
};
/**
* Method highlighting the input data fields
*/
// TODO: better name
composer.methods.highlightField = function(element, message) {
if (!element) return;
var css = this.cssPrefix + "error";
element.parent().addClass(css);
element.tooltip({
"title": message,
"placement": "right",
"trigger": "hover"
});
element.focus(function() {
$(this).tooltip("destroy");
$(this).parent().removeClass(css);
});
};
composer.methods.attachMedia = function(params) {
var self = this;
params = $.extend({
"urls": [],
"removeOld": false,
"render": true
}, params);
var urls = params.urls.length && params.urls || [params.url || ""];
urls = $.map(urls, function(url) {
return $.trim(url);
});
this.resolver.resolve(urls, function(data) {
if (params.removeOld) {
self.removeMedia();
}
data = $.grep(data, function(oembed) {
return !$.isEmptyObject(oembed) && !~self._getDefinedMediaIndex(oembed);
});
if (!data.length) return;
$.each(data, function(i, oembed) {
self.formData.media.push(oembed);
});
self.view.render({"name": "media"});
});
};
composer.methods.removeMedia = function(index) {
if (typeof index === "undefined") {
this.formData.media = [];
} else if (!~index) {
return;
} else {
this.formData.media.splice(index, 1);
}
this.view.render({"name": "media"});
};
/**
* Allows to register custom post composer
*/
composer.methods.registerComposer = function(config) {
if (!config || !config.id) {
this.log({"message": "Invalid composer configuration"});
return;
}
this.composers.push(config);
};
/**
* This method adds a custom validator to check the posting possibility.
*/
composer.methods.addPostValidator = function(validator, priority) {
this.validators[priority === "low" ? "push" : "unshift"](validator);
};
/**
* Method implements the refresh logic for the Submit Composer control.
*/
/*composer.methods.refresh = function() {
var self = this;
this.config.set("data.object.content", this.view.get("text").val());
$.map(["tags", "markers"], function(field) {
var elements = self.view.get(field).val().split(", ");
self.config.set("data.object." + field, elements || []);
});
var component = Echo.Utils.getComponent("Echo.StreamServer.Controls.CardComposer");
component.parent.refresh.call(this);
};*/
composer.methods.expand = function() {
if (!this.collapsed) return;
this.collapsed = false;
this._initCurrentComposer();
this.view.render({"name": "container"});
this.events.publish({"topic": "onExpand"});
};
composer.methods.collapse = function() {
if (this.collapsed) return;
this.collapsed = true;
this.view.render({"name": "container"});
this.events.publish({"topic": "onCollapse"});
};
composer.methods._initCurrentComposer = function() {
if (this.collapsed) return;
var self = this;
var composer = this.currentComposer;
if (!composer.panel.children().length) {
composer.panel.append(composer.composer());
composer.setData($.extend(true, {}, this.formData));
}
// timeout allows form fields to be added to target element DOM
setTimeout(function() {
self._initFormFields();
}, 0);
};
composer.methods._extractInfoFromExternalData = function() {
var self = this;
this.formData = {
"text": "",
"media": []
};
var data = this.config.get("data");
if (!data || $.isEmptyObject(data)) return;
Echo.Utils.safelyExecute(function() {
var content = $("<div>").append(self.config.get("data.object.content"));
//self.set("content", self.config.get("data.object.content"));
self.formData.text = $(".echo-item-text", content).html();
if (/*self.get("content") !== item.get("data.object.content") || */!self.formData.media.length) {
self.formData.media = $("div[oembed], div[data-oembed]", content).map(function() {
return $.parseJSON($(this).attr("oembed") || $(this).attr("data-oembed"));
}).get();
}
var composer = $(".echo-item-files", content).data("composer");
var types = self.config.get("data.object.objectTypes");
$.each(self.composers, function(i, data) {
if (data.id === composer) {
self.currentComposer = data;
return false;
}
var matches = $.grep(types, function(type) {
return data.objectType === type;
});
if (matches.length) {
self.currentComposer = data;
return false;
}
});
});
};
composer.methods._htmlEncode = function(json) {
return JSON.stringify(json)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
};
composer.methods._getDefinedMediaIndex = function(oembed) {
var found = false, index = -1;
var fields = ["original_url", "url", "title", "author_name"];
var fieldsByType = {
"link": fields.slice(),
"photo": fields.slice(),
"video": fields.slice().concat("html")
};
$.each(this.formData.media, function(i, media) {
if (media.type !== oembed.type) return;
$.each(fieldsByType[oembed.type], function(j, field) {
found = true;
if (typeof media[field] !== "undefined" &&
media[field] !== oembed[field]
) {
found = false;
return false;
}
});
if (found) {
index = i;
return false;
}
});
return index;
};
composer.methods._initFormFields = function() {
var self = this, nonEmpty = {};
var init = function(container, id) {
var timer;
nonEmpty[id] = [];
var fields = container.find("input[type=text][required], textarea[required]");
if (id === "_global") {
// filter out composer fields while searching for global fields
fields = fields.map(function(i, el) {
if ($(el).closest("." + self.cssPrefix + "formWrapper", container).length) {
return null;
}
return el;
});
}
return fields
.off("keyup.cardComposer paste.cardComposer")
.on("keyup.cardComposer paste.cardComposer", function() {
clearTimeout(timer);
var el = this;
timer = setTimeout(function() {
process(el, id);
}, 100);
});
};
var process = function(el, id) {
var idx = nonEmpty[id].indexOf(el);
if ($.trim($(el).val())) {
if (idx === -1) nonEmpty[id].push(el);
} else {
if (idx !== -1) nonEmpty[id].splice(idx, 1);
}
var actual = nonEmpty["_global"].length + nonEmpty[self.currentComposer.id].length;
var expected = globalFields.length + composerFields.length;
self._setPostButtonState(actual === expected ? "normal" : "disabled");
};
this.config.get("target")
.find("input[type=text], textarea")
.each(function() {
var el = $(this);
if (el.prop("echo-processed")) return;
el.prop("echo-processed", true);
var hint = el.attr("placeholder");
if (hint) {
el.placeholder();
if (el.attr("required")) {
el.attr("placeholder", hint + self.labels.get("required"));
}
}
});
var globalFields = init(this.config.get("target"), "_global");
var composerFields = init(this.currentComposer.panel, this.currentComposer.id);
if (!globalFields.length && !composerFields.length) {
this._setPostButtonState("normal");
return;
}
globalFields.each(function(i, el) {
process(el, "_global");
});
composerFields.each(function(i, el) {
process(el, self.currentComposer.id);
});
};
composer.methods._setPostButtonState = function(state) {
if (state === this.postButtonState) return;
this.postButtonState = state;
this.view.render({"name": "postButton"});
this.view.render({"name": "postButtonSwitcher"});
};
composer.methods._switchAutoSharing = function(state) {
var enabled = this._isAutoSharingEnabled();
if (enabled ^ (state !== "on")) return;
Echo.Cookie.set("sharingOnPost", state === "on");
Echo.Events.publish({
"topic": composer.name + ".onAutoSharingToggle",
"context": "global"
});
};
composer.methods._isAutoSharingEnabled = function(state) {
return this.config.get("displaySharingOnPost") &&
Echo.Cookie.get("sharingOnPost") === "true";
};
composer.methods._share = function(data) {
// XXX: garantee that first element is "post" and ignore "update"
var item = data.postData.content[0];
var payload = {
"origin": "item",
"actor": {
"id": this.user.get("identityUrl"),
"name": item.actor.name,
"avatar": item.actor.avatar
},
"object": {
"id": data.request.response.objectID,
"content": item.object.content
},
"source": item.source,
"target": item.targets[0].id
};
Backplane.response([{
// IMPORTANT: we use ID of the last received message
// from the server-side to avoid same messages re-processing
// because of the "since" parameter cleanup...
"id": Backplane.since,
"channel_name": Backplane.getChannelName(),
"message": {
"type": "content/share/request",
"payload": payload
}
}]);
};
composer.methods._requestLoginPrompt = function() {
Backplane.response([{
// IMPORTANT: we use ID of the last received message
// from the server-side to avoid same messages re-processing
// because of the "since" parameter cleanup...
"id": Backplane.since,
"channel_name": Backplane.getChannelName(),
"message": {
"type": "identity/login/request",
"payload": this.user.data || {}
}
}]);
};
composer.methods._userStatus = function() {
return this.user.is("logged")
? "logged"
: this.config.get("submitPermissions") === "forceLogin"
? "forcedLogin"
: "anonymous";
};
composer.methods._getActivity = function(verb, type, data) {
return !data ? [] : {
"actor": {
"objectTypes": [this._getASURL("person")],
"name": this.user.get("name", this.user.is("logged")
? ""
: this.view.get("name").val()),
"avatar": this.user.get("avatar", "")
},
"object": {
"objectTypes": [type],
"content": data
},
"source": this.config.get("source"),
"verbs": [this._getASURL(verb)],
"targets": [{
"id": this.config.get("targetURL")
}]
};
};
composer.methods._getASURL = function(postfix) {
return "http://activitystrea.ms/schema/1.0/" + postfix;
};
composer.methods._showError = function(data) {
data = data || {};
var response = data.request && data.request.response || {};
var message = $.inArray(response.errorCode, ["network_timeout", "connection_failure"]) >= 0
? this.labels.get("postingTimeout")
: this.labels.get("postingFailed", {"error": response.errorMessage || response.errorCode});
var popup = this._assembleErrorPopup(message);
new Echo.GUI.Modal({
"data": {
"body": popup.content
},
"width": popup.width,
"footer": false,
"fade": true,
"show": true
});
};
composer.methods._assembleErrorPopup = function(message) {
var dimensions = this.config.get("errorPopup");
var template = this.substitute({
"template": '<div class="{data:css}">{data:message}</div>',
"data": {
"message": message,
"css": this.cssPrefix + "error"
}
});
var popup = {
"content": $(template).css({
"min-height": dimensions.minHeight,
"max-height": dimensions.maxHeight
}),
"width": dimensions.width
};
return popup;
};
composer.methods._isPostValid = function() {
var valid = true;
$.each(this.validators, function(i, handler) {
valid = handler();
return valid;
});
return valid;
};
composer.methods._prepareEventParams = function(params) {
return $.extend(params, {
"data": this.get("data"),
"target": this.config.get("target").get(0),
"targetURL": this.config.get("targetURL")
});
};
composer.css =
'.{class:header} { margin-bottom: 10px; }' +
'.{class:anonymous} .{class:header} { margin-bottom: 7px; }' +
'.{class:auth} { display: none; }' +
'.{class:nameContainer} { margin: 11px 0px 0px 0px; padding: 3px 2px 3px 5px; }' +
'.{class:nameContainer} input.{class:name}[type="text"] { font-size: 14px; border: none; width: 100%; margin-bottom: 0px; padding: 0px; outline: 0; box-shadow: none; background-color: transparent; }' +
'.{class:nameContainer} input.{class:name}[type="text"]:focus { outline: 0; box-shadow: none; }' +
'.{class:nameContainer} input.{class:name}[type="text"].echo-secondaryColor,' +
'.{class:container} .{class:metadataSubwrapper} input.echo-secondaryColor[type="text"]' +
' { color: #C6C6C6; }' +
'.{class:compactFieldWrapper} { padding: 4px 8px; }' +
'.{class:compactFieldWrapper} input.{class:compactField}[type="text"] { border: none; width: 100%; margin-bottom: 0px; padding: 0px; outline: 0; box-shadow: none; background-color: transparent; font-size: 12px; }' +
'.{class:metadataContainer} { margin-top: 6px; }' +
'.{class:metadataLabel} { float: left; width: 50px; margin-right: -50px; text-align: right; line-height: 22px; }' +
'.{class:metadataWrapper} { float: left; width: 100%; }' +
'.{class:metadataSubwrapper} { margin-left: 55px; padding: 2px 2px 2px 3px; background-color: #fff; }' +
'.{class:container} { padding: 20px; border: 1px solid #d8d8d8; border-bottom-width: 2px; border-radius: 3px; }' +
'.{class:container} .{class:metadataSubwrapper} input[type="text"] { width: 100%; border: 0; padding: 0px; outline: 0; box-shadow: none; margin-bottom: 0px; }' +
'.{class:container} .{class:metadataSubwrapper} input[type="text"]:focus { outline: 0; box-shadow: none; }' +
'.{class:composers} { margin: 0px; border: 1px solid #dedede; border-width: 0px 1px; }' +
'.{class:controls} { margin: 0px; padding: 5px; border: 1px solid #d8d8d8; background-color: transparent; }' +
'.{class:confirmation} { margin-bottom: 10px; display: none; }' +
'.{class:attachers} { display: none; margin: 5px; float: left; }' +
'.{class:postButtonWrapper} { float: right; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; }' +
'.{class:postButtonWrapper} .dropdown-menu { min-width: 100px; }' +
'.{class:postButtonWrapper} .{class:postButton}.btn { padding: 3px 12px 5px 12px; }' +
'.{class:tagsContainer} { display: none !important; }' +
'.{class:markersContainer} { display: none !important; }' +
'.{class:border} { border: 1px solid #d8d8d8; }' +
'.{class:mandatory} { border: 1px solid red; }' +
'.{class:queriesViewOption} { padding-right: 5px; }' +
'.echo-sdk-ui .{class:composers} input[type=text], .echo-sdk-ui .{class:composers} textarea { width: 100%; border: 0px; resize: none; outline: none; box-shadow: none; padding: 0px; margin: 0px; background-color: transparent; }' +
'.echo-sdk-ui .{class:container} input[type=text]:focus, .echo-sdk-ui .{class:composers} textarea:focus { outline: none; box-shadow: none; }' +
'.echo-sdk-ui .{class:container} input[type=text]:focus:invalid,' +
'.echo-sdk-ui .{class:container} input[type=text]:focus:invalid:focus,' +
'.echo-sdk-ui .{class:container} textarea:focus:invalid,' +
'.echo-sdk-ui .{class:container} textarea:focus:invalid:focus' +
'{ color: #3c3c3c; border-color: transparent; box-shadow: none; }' +
'.echo-cardcomposer-delimiter { height: 0px; border-top: 1px dashed #d8d8d8; }' +
'.echo-cardcomposer-field-wrapper { padding: 7px 11px; border: 1px solid transparent; display: inline-block; width: 100%; box-sizing: border-box !important/* XXX: because of conversations*/; }' +
'.{class:error} { border: 1px solid red; }' +
'.{class:error} input, .{class:error} textarea { background: no-repeat center right url({config:cdnBaseURL.sdk-assets}/images/warning.gif); }' +
'.{class:media} .echo-conversations-mediacontainer-multiple { border: 1px solid #DEDEDE; border-top-style: dashed; border-bottom: 0px; background-color: #F1F1F1; }' +
// display modes
'.{class:normal} .{class:compactFieldWrapper},' +
'.{class:small} .{class:formWrapper},' +
'.{class:smallest} .{class:formWrapper},' +
'.{class:smallest} .{class:header} { display: none; }' +
'.echo-sdk-ui .{class:inline} .nav-tabs,' +
'.{class:inline} .{class:formWrapper},' +
'.{class:inline}.{class:anonymous} .{class:header},' +
'.{class:inline} .echo-streamserver-controls-auth-container { display: none; }' +
'.{class:inline} .{class:compactFieldWrapper} { margin-left: 38px; }' +
'.{class:inline}.{class:anonymous} .{class:compactFieldWrapper} { margin-left: 0px; }' +
'.{class:inline}.{class:container}:not(.{class:anonymous}) { padding-left: 12px; }' +
'.{class:inline} .{class:header} { float: left; margin: 0px; }' +
'.{class:inline} .echo-streamserver-controls-auth-avatarContainer,' +
'.{class:inline} .echo-streamserver-controls-auth-avatar { width: 28px; height: 28px; }' +
'.echo-sdk-ui .{class:small} .nav-tabs,' +
'.echo-sdk-ui .{class:smallest} .nav-tabs { border-bottom-width: 0px; }' +
// tabs
'.{class:icon} { vertical-align: middle; margin-right: 2px; }' +
'.echo-sdk-ui .{class:tabs} .nav { margin-bottom: 0px; }' +
'.echo-sdk-ui .{class:tabs} .nav > li > a { padding: 0px; margin-right: 10px; border: 0px; color: #3c3c3c; background-color: transparent; opacity: 0.5; }' +
'.echo-sdk-ui .{class:tabs} .nav > li > a:hover, .echo-sdk-ui .{class:tabs} .nav > li > a:focus { background-color: transparent; border: 0px; }' +
'.echo-sdk-ui .{class:tabs} .nav > li.active > a,' +
'.echo-sdk-ui .{class:tabs} .nav > li.active > a:hover,' +
'.echo-sdk-ui .{class:tabs} .nav > li.active > a:focus,' +
'.echo-sdk-ui .{class:tabs} .nav > li.active > a:active { border: 0px; border-bottom: 4px solid #d8d8d8; color: #3c3c3c; background-color: transparent; opacity: 1; }' +
'';
Echo.Control.create(composer);
})(Echo.jQuery);
| Compact from input background should be white
| sdk-derived/controls/card-composer.js | Compact from input background should be white | <ide><path>dk-derived/controls/card-composer.js
<ide> '.{class:nameContainer} input.{class:name}[type="text"].echo-secondaryColor,' +
<ide> '.{class:container} .{class:metadataSubwrapper} input.echo-secondaryColor[type="text"]' +
<ide> ' { color: #C6C6C6; }' +
<del> '.{class:compactFieldWrapper} { padding: 4px 8px; }' +
<del> '.{class:compactFieldWrapper} input.{class:compactField}[type="text"] { border: none; width: 100%; margin-bottom: 0px; padding: 0px; outline: 0; box-shadow: none; background-color: transparent; font-size: 12px; }' +
<add> '.{class:compactFieldWrapper} { padding: 4px 8px; background-color: #fff; }' +
<add> '.{class:compactFieldWrapper} input.{class:compactField}[type="text"] { border: none; width: 100%; margin-bottom: 0px; padding: 0px; outline: 0; box-shadow: none; font-size: 12px; }' +
<ide> '.{class:metadataContainer} { margin-top: 6px; }' +
<ide> '.{class:metadataLabel} { float: left; width: 50px; margin-right: -50px; text-align: right; line-height: 22px; }' +
<ide> '.{class:metadataWrapper} { float: left; width: 100%; }' + |
|
Java | mit | a8b9cc5a75a454e8478cc92d9b3baa96165ee347 | 0 | feltnerm/uwponopoly,feltnerm/uwponopoly,feltnerm/uwponopoly | // Copyright Aaron Decker
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.FlowLayout;
import java.awt.*;
import java.util.*;
/**
* The main class of UWPonopoly
* @author Aaron Decker
*/
class UWPonopoly implements Runnable
{
// PRIVATE OBJECTS
private Thread thread;
// Game Board
private GameFrame window;
private GameBuffer backbuffer;
private GamePanel gamepanel;
private Property testproperty;
// Player Stats Panel
private JPanel dashboard_panel;
private JPanel dice_panel;
private JPanel player_stats_panel;
private JPanel property_context_panel;
private JButton sell_button;
static final int TICK_LENGTH_MS = 10;
// Height & Width of the Board
static final int DESIRED_WIDTH = 550;
static final int DESIRED_HEIGHT = 350;
public static void main(String[] args)
{
UWPonopoly uwponopoly = new UWPonopoly();
}
UWPonopoly()
{
backbuffer = new GameBuffer(DESIRED_WIDTH, DESIRED_HEIGHT, Color.ORANGE);
// GAME WINDOW
window = new GameFrame("UWPonopoly");
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setSize(DESIRED_WIDTH, DESIRED_HEIGHT);
//window.setResizable(false);
window.setVisible(true);
//window.setLayout( new BoxLayout(window.getContentPane(), BoxLayout.PAGE_AXIS) );
window.setLayout( new BorderLayout() );
// GAME PANEL
gamepanel = new GamePanel( backbuffer );
//window.getContentPane().add( gamepanel );
// DASHBOARD
dashboard_panel = new JPanel();
dashboard_panel.setLayout( new FlowLayout() );
// Property Context Panel
property_context_panel = new JPanel();
property_context_panel.setLayout( new BorderLayout());
ImageIcon property_icon = createImageIcon("images/boardwalk.jpg", "deed");
JButton improve_button = new JButton("Improve");
improve_button.setEnabled(false);
JButton buy_button = new JButton("Buy");
JButton sell_button = new JButton("Sell");
sell_button.setEnabled(false);
property_context_panel.add( new JLabel(property_icon), BorderLayout.NORTH);
property_context_panel.add( buy_button, BorderLayout.WEST);
property_context_panel.add( improve_button, BorderLayout.CENTER);
property_context_panel.add( sell_button, BorderLayout.EAST );
// Dice Control
dice_panel = new JPanel();
dice_panel.setLayout( new BorderLayout() );
ImageIcon icon = createImageIcon("images/dice.jpg", "dice");
dice_panel.add( new JLabel(icon), BorderLayout.NORTH );
dice_panel.add( new JButton("Roll!") , BorderLayout.SOUTH);
// Player Stats
player_stats_panel = new JPanel();
player_stats_panel.setLayout( new BorderLayout() );
player_stats_panel.add( new JLabel("Money: $ 314,159,265"), BorderLayout.NORTH );
player_stats_panel.add( new JLabel("Current Player: Pat the Pioneer"), BorderLayout.SOUTH );
// Add Panels to Dashboard
dashboard_panel.add( property_context_panel );
dashboard_panel.add( player_stats_panel );
dashboard_panel.add( dice_panel );
// GAME BOARD
ImageIcon board_icon = createImageIcon("images/monopoly-board.png","board");
window.getContentPane().add( new JLabel(board_icon), BorderLayout.NORTH );
// Properties
testproperty = new Property( backbuffer );
/*
window.getContentPane().add( testproperty );
window.getContentPane().add( new JSeparator(SwingConstants.HORIZONTAL) );
window.getContentPane().add( dashboard_panel );
*/
//window.getContentPane().add( testproperty , BorderLayout.NORTH);
// Dashboard Panel
window.getContentPane().add( new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.SOUTH );
window.getContentPane().add( dashboard_panel, BorderLayout.SOUTH );
//dashboard_panel.add( new JLabel("Current Player: Pat the Pioneer") );
//dice_panel.add( new JLabel("Dice", icon, JLabel.CENTER) , BorderLayout.NORTH);
//window.getContentPane().add( new JProgressBar(5,10) );
// Pack it and Start the Thread
window.pack();
thread = new Thread(this);
thread.start();
}
/** Implemented from Runnable
*
*/
public void run()
{
Thread current = Thread.currentThread();
while( current == thread )
{
// throttle frame rate
try
{
Thread.sleep(TICK_LENGTH_MS);
}
catch( InterruptedException e )
{
e.printStackTrace();
}
handleMouseEvents();
handleKeyEvents();
// draw
backbuffer.clear();
gamepanel.repaint();
testproperty.repaint();
}
}
public void handleMouseEvents()
{
try
{
MouseEvent e = gamepanel.getNextMouseEvent();
if( e.getID() == MouseEvent.MOUSE_RELEASED )
{
}
}
catch ( java.util.NoSuchElementException exception )
{
// no events on queue, so nothing to do
}
}
public void handleKeyEvents()
{
try
{
KeyEvent e = window.getNextKeyEvent();
if( e.getID() == KeyEvent.KEY_PRESSED )
{
switch( e.getKeyCode() )
{
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_UP:
break;
default:
break;
}
}
if( e.getID() == KeyEvent.KEY_RELEASED )
{
switch( e.getKeyCode() )
{
case KeyEvent.VK_LEFT:
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_UP:
case KeyEvent.VK_DOWN:
default:
break;
}
}
}
catch ( java.util.NoSuchElementException exception )
{
// no events on queue, so nothing to do
}
}
// the following function is copyrighted!
// source: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/LabelDemoProject/src/components/LabelDemo.java
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = UWPonopoly.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
};
| proto/UWPonopoly.java | // Copyright Aaron Decker
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.FlowLayout;
import java.awt.*;
import java.util.*;
/**
* The main class of UWPonopoly
* @author Aaron Decker
*/
class UWPonopoly implements Runnable
{
// widgets
private GameFrame window;
private GameBuffer backbuffer;
private JPanel dashboard_panel;
private JPanel dice_panel;
private JPanel player_stats_panel;
private JPanel property_context_panel;
private JButton sell_button;
private Thread thread;
static final int TICK_LENGTH_MS = 10;
// desired height and width for the window
static final int DESIRED_WIDTH = 550;
static final int DESIRED_HEIGHT = 350;
// testing code
private GamePanel gamepanel;
private Property testproperty;
public static void main(String[] args)
{
UWPonopoly uwponopoly = new UWPonopoly();
}
UWPonopoly()
{
backbuffer = new GameBuffer(DESIRED_WIDTH,DESIRED_HEIGHT, Color.ORANGE);
// setup window
window = new GameFrame("UWPonopoly");
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setSize(DESIRED_WIDTH,DESIRED_HEIGHT);
//window.setResizable(false);
window.setVisible(true);
//window.setLayout( new BoxLayout(window.getContentPane(), BoxLayout.PAGE_AXIS) );
window.setLayout( new BorderLayout() );
// setup gamepanel
gamepanel = new GamePanel( backbuffer );
//window.getContentPane().add( gamepanel );
// PROPERTY CONTEXT PANEL - test code
// @todo: Separate module
// @todo: make it work (?)
property_context_panel = new JPanel();
property_context_panel.setLayout( new BorderLayout());
//property_context_panel.add( new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.NORTH);
ImageIcon property_icon = createImageIcon("images/boardwalk.jpg", "deed");
property_context_panel.add( new JLabel(property_icon), BorderLayout.NORTH);
property_context_panel.add( new JButton("Buy"), BorderLayout.WEST);
JButton improve_button = new JButton("Improve");
improve_button.setEnabled(false);
property_context_panel.add( improve_button, BorderLayout.CENTER);
sell_button = new JButton("Sell");
sell_button.setEnabled(false);
property_context_panel.add( sell_button, BorderLayout.EAST );
dashboard_panel = new JPanel();
dashboard_panel.setLayout( new FlowLayout() );
dice_panel = new JPanel();
dice_panel.setLayout( new BorderLayout() );
player_stats_panel = new JPanel();
player_stats_panel.setLayout( new BorderLayout() );
player_stats_panel.add( new JLabel("Money: $ 314,159,265"), BorderLayout.NORTH );
player_stats_panel.add( new JLabel("Current Player: Pat the Pioneer"), BorderLayout.SOUTH );
// test code
testproperty = new Property( backbuffer );
/*window.getContentPane().add( testproperty );
window.getContentPane().add( new JSeparator(SwingConstants.HORIZONTAL) );
window.getContentPane().add( dashboard_panel );*/
//window.getContentPane().add( testproperty , BorderLayout.NORTH);
ImageIcon board_icon = createImageIcon("images/monopoly-board.png","board");
window.getContentPane().add( new JLabel(board_icon), BorderLayout.NORTH );
window.getContentPane().add( new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.SOUTH );
window.getContentPane().add( dashboard_panel, BorderLayout.SOUTH );
//dashboard_panel.add( new JLabel("Current Player: Pat the Pioneer") );
dashboard_panel.add( property_context_panel );
dashboard_panel.add( player_stats_panel );
dashboard_panel.add( dice_panel );
ImageIcon icon = createImageIcon("images/dice.jpg", "dice");
//dice_panel.add( new JLabel("Dice", icon, JLabel.CENTER) , BorderLayout.NORTH);
dice_panel.add( new JLabel(icon), BorderLayout.NORTH );
dice_panel.add( new JButton("Roll!") , BorderLayout.SOUTH);
//window.getContentPane().add( new JProgressBar(5,10) );
window.pack();
thread = new Thread(this);
thread.start();
}
/** Implemented from Runnable
*
*/
public void run()
{
Thread current = Thread.currentThread();
while( current == thread )
{
// throttle frame rate
try
{
Thread.sleep(TICK_LENGTH_MS);
}
catch( InterruptedException e )
{
e.printStackTrace();
}
handleMouseEvents();
handleKeyEvents();
// draw
backbuffer.clear();
gamepanel.repaint();
testproperty.repaint();
}
}
public void handleMouseEvents()
{
try
{
MouseEvent e = gamepanel.getNextMouseEvent();
if( e.getID() == MouseEvent.MOUSE_RELEASED )
{
}
}
catch ( java.util.NoSuchElementException exception )
{
// no events on queue, so nothing to do
}
}
public void handleKeyEvents()
{
try
{
KeyEvent e = window.getNextKeyEvent();
if( e.getID() == KeyEvent.KEY_PRESSED )
{
switch( e.getKeyCode() )
{
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_UP:
break;
default:
break;
}
}
if( e.getID() == KeyEvent.KEY_RELEASED )
{
switch( e.getKeyCode() )
{
case KeyEvent.VK_LEFT:
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_UP:
case KeyEvent.VK_DOWN:
default:
break;
}
}
}
catch ( java.util.NoSuchElementException exception )
{
// no events on queue, so nothing to do
}
}
// the following function is copyrighted!
// source: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/LabelDemoProject/src/components/LabelDemo.java
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = UWPonopoly.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
};
| Cleaned up code, added some better comments
| proto/UWPonopoly.java | Cleaned up code, added some better comments | <ide><path>roto/UWPonopoly.java
<ide> class UWPonopoly implements Runnable
<ide> {
<ide>
<del> // widgets
<add> // PRIVATE OBJECTS
<add>
<add> private Thread thread;
<add>
<add> // Game Board
<ide> private GameFrame window;
<ide> private GameBuffer backbuffer;
<add> private GamePanel gamepanel;
<add> private Property testproperty;
<add>
<add> // Player Stats Panel
<ide> private JPanel dashboard_panel;
<ide> private JPanel dice_panel;
<ide> private JPanel player_stats_panel;
<ide>
<ide> private JButton sell_button;
<ide>
<del>
<del> private Thread thread;
<del>
<ide> static final int TICK_LENGTH_MS = 10;
<ide>
<del> // desired height and width for the window
<add> // Height & Width of the Board
<ide> static final int DESIRED_WIDTH = 550;
<ide> static final int DESIRED_HEIGHT = 350;
<ide>
<del> // testing code
<del> private GamePanel gamepanel;
<del> private Property testproperty;
<del>
<ide> public static void main(String[] args)
<ide> {
<ide> UWPonopoly uwponopoly = new UWPonopoly();
<ide>
<ide> UWPonopoly()
<ide> {
<del> backbuffer = new GameBuffer(DESIRED_WIDTH,DESIRED_HEIGHT, Color.ORANGE);
<del> // setup window
<add> backbuffer = new GameBuffer(DESIRED_WIDTH, DESIRED_HEIGHT, Color.ORANGE);
<add>
<add> // GAME WINDOW
<ide> window = new GameFrame("UWPonopoly");
<ide> window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
<del> window.setSize(DESIRED_WIDTH,DESIRED_HEIGHT);
<add> window.setSize(DESIRED_WIDTH, DESIRED_HEIGHT);
<ide> //window.setResizable(false);
<ide> window.setVisible(true);
<ide> //window.setLayout( new BoxLayout(window.getContentPane(), BoxLayout.PAGE_AXIS) );
<ide> window.setLayout( new BorderLayout() );
<ide>
<del> // setup gamepanel
<add> // GAME PANEL
<ide> gamepanel = new GamePanel( backbuffer );
<ide> //window.getContentPane().add( gamepanel );
<ide>
<del> // PROPERTY CONTEXT PANEL - test code
<del> // @todo: Separate module
<del> // @todo: make it work (?)
<add> // DASHBOARD
<add> dashboard_panel = new JPanel();
<add> dashboard_panel.setLayout( new FlowLayout() );
<add>
<add> // Property Context Panel
<ide> property_context_panel = new JPanel();
<ide> property_context_panel.setLayout( new BorderLayout());
<del> //property_context_panel.add( new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.NORTH);
<add>
<ide> ImageIcon property_icon = createImageIcon("images/boardwalk.jpg", "deed");
<add>
<add> JButton improve_button = new JButton("Improve");
<add> improve_button.setEnabled(false);
<add> JButton buy_button = new JButton("Buy");
<add> JButton sell_button = new JButton("Sell");
<add> sell_button.setEnabled(false);
<add>
<ide> property_context_panel.add( new JLabel(property_icon), BorderLayout.NORTH);
<del> property_context_panel.add( new JButton("Buy"), BorderLayout.WEST);
<del> JButton improve_button = new JButton("Improve");
<del> improve_button.setEnabled(false);
<add> property_context_panel.add( buy_button, BorderLayout.WEST);
<ide> property_context_panel.add( improve_button, BorderLayout.CENTER);
<del> sell_button = new JButton("Sell");
<del> sell_button.setEnabled(false);
<del> property_context_panel.add( sell_button, BorderLayout.EAST );
<del>
<del> dashboard_panel = new JPanel();
<del> dashboard_panel.setLayout( new FlowLayout() );
<add> property_context_panel.add( sell_button, BorderLayout.EAST );
<add>
<add> // Dice Control
<ide> dice_panel = new JPanel();
<ide> dice_panel.setLayout( new BorderLayout() );
<add> ImageIcon icon = createImageIcon("images/dice.jpg", "dice");
<add> dice_panel.add( new JLabel(icon), BorderLayout.NORTH );
<add> dice_panel.add( new JButton("Roll!") , BorderLayout.SOUTH);
<add>
<add> // Player Stats
<ide> player_stats_panel = new JPanel();
<ide> player_stats_panel.setLayout( new BorderLayout() );
<ide> player_stats_panel.add( new JLabel("Money: $ 314,159,265"), BorderLayout.NORTH );
<ide> player_stats_panel.add( new JLabel("Current Player: Pat the Pioneer"), BorderLayout.SOUTH );
<ide>
<del> // test code
<del> testproperty = new Property( backbuffer );
<del> /*window.getContentPane().add( testproperty );
<del> window.getContentPane().add( new JSeparator(SwingConstants.HORIZONTAL) );
<del> window.getContentPane().add( dashboard_panel );*/
<del> //window.getContentPane().add( testproperty , BorderLayout.NORTH);
<add>
<add> // Add Panels to Dashboard
<add> dashboard_panel.add( property_context_panel );
<add> dashboard_panel.add( player_stats_panel );
<add> dashboard_panel.add( dice_panel );
<add>
<add> // GAME BOARD
<ide> ImageIcon board_icon = createImageIcon("images/monopoly-board.png","board");
<ide> window.getContentPane().add( new JLabel(board_icon), BorderLayout.NORTH );
<add>
<add> // Properties
<add> testproperty = new Property( backbuffer );
<add> /*
<add> window.getContentPane().add( testproperty );
<add> window.getContentPane().add( new JSeparator(SwingConstants.HORIZONTAL) );
<add> window.getContentPane().add( dashboard_panel );
<add> */
<add> //window.getContentPane().add( testproperty , BorderLayout.NORTH);
<add>
<add> // Dashboard Panel
<ide> window.getContentPane().add( new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.SOUTH );
<ide> window.getContentPane().add( dashboard_panel, BorderLayout.SOUTH );
<ide> //dashboard_panel.add( new JLabel("Current Player: Pat the Pioneer") );
<del> dashboard_panel.add( property_context_panel );
<del> dashboard_panel.add( player_stats_panel );
<del> dashboard_panel.add( dice_panel );
<del> ImageIcon icon = createImageIcon("images/dice.jpg", "dice");
<ide> //dice_panel.add( new JLabel("Dice", icon, JLabel.CENTER) , BorderLayout.NORTH);
<del> dice_panel.add( new JLabel(icon), BorderLayout.NORTH );
<del> dice_panel.add( new JButton("Roll!") , BorderLayout.SOUTH);
<add>
<ide> //window.getContentPane().add( new JProgressBar(5,10) );
<ide>
<del>
<add> // Pack it and Start the Thread
<ide> window.pack();
<del>
<ide> thread = new Thread(this);
<ide> thread.start();
<ide> } |
|
Java | apache-2.0 | 234abf18593d54b7f6744593a089b87f997addef | 0 | springrichclient/springrcp,springrichclient/springrcp,springrichclient/springrcp | /*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.richclient.application;
import java.awt.Image;
import java.util.Observable;
import java.util.Observer;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.richclient.application.config.ApplicationLifecycleAdvisor;
import org.springframework.richclient.application.support.DefaultApplicationWindow;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* A singleton workbench or shell of a rich client application.
* <p>
* The application provides a point of reference and context for an entire
* application. It provides an interface to open application windows.
*
* @author Keith Donald
*/
public class Application implements InitializingBean, ApplicationContextAware {
private static final String DEFAULT_APPLICATION_IMAGE_KEY = "applicationInfo.image";
private static final String APPLICATION_WINDOW_BEAN_ID = "applicationWindowPrototype";
private static Application SOLE_INSTANCE;
private ApplicationDescriptor descriptor;
private ApplicationServices services;
private ApplicationLifecycleAdvisor lifecycleAdvisor;
private ApplicationWindow activeWindow;
private WindowManager windowManager;
/**
* Load the single application instance.
*
* @param instance
* The application
*/
public static void load(Application instance) {
SOLE_INSTANCE = instance;
}
/**
* Return the single application instance.
*
* @return The application
*/
public static Application instance() {
Assert
.state(isLoaded(),
"The global rich client application instance has not yet been initialized; it must be created and loaded first.");
return SOLE_INSTANCE;
}
public static boolean isLoaded() {
return SOLE_INSTANCE != null;
}
/**
* Return a global service locator for application services.
*
* @return The application services locator.
*/
public static ApplicationServices services() {
return instance().getServices();
}
public Application(ApplicationLifecycleAdvisor advisor) {
this(null, advisor, null);
}
public Application(ApplicationDescriptor descriptor, ApplicationLifecycleAdvisor advisor) {
this(descriptor, advisor, null);
}
public Application(ApplicationDescriptor descriptor, ApplicationLifecycleAdvisor advisor,
ApplicationServices services) {
setDescriptor(descriptor);
setLifecycleAdvisor(advisor);
setServices(services);
this.windowManager = new WindowManager();
this.windowManager.addObserver(new CloseApplicationObserver());
Assert.state(!isLoaded(), "Only one instance of a Spring Rich Application allowed per VM.");
load(this);
}
public void setDescriptor(ApplicationDescriptor descriptor) {
this.descriptor = descriptor;
}
public ApplicationDescriptor getDescriptor() {
return descriptor;
}
public void setServices(ApplicationServices services) {
this.services = services;
}
private void setLifecycleAdvisor(ApplicationLifecycleAdvisor advisor) {
this.lifecycleAdvisor = advisor;
}
public void setApplicationContext(ApplicationContext context) {
getServices().setApplicationContext(context);
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.lifecycleAdvisor,
"The application advisor is required, for processing of application lifecycle events");
getLifecycleAdvisor().onPreInitialize(this);
}
public ApplicationLifecycleAdvisor getLifecycleAdvisor() {
return lifecycleAdvisor;
}
public ApplicationServices getServices() {
if (services == null) {
services = new ApplicationServices();
}
return services;
}
public String getName() {
if (descriptor != null && StringUtils.hasText(descriptor.getDisplayName())) {
return descriptor.getDisplayName();
} else {
return "Spring Rich Client Application";
}
}
public Image getImage() {
if (descriptor != null && descriptor.getImage() != null) {
return descriptor.getImage();
} else {
return Application.services().getImage(DEFAULT_APPLICATION_IMAGE_KEY);
}
}
public void openWindow(String pageDescriptorId) {
ApplicationWindow newWindow = initWindow(createNewWindow());
newWindow.showPage(pageDescriptorId);
// @TODO track active window...
this.activeWindow = newWindow;
}
private ApplicationWindow initWindow(ApplicationWindow window) {
windowManager.add(window);
return window;
}
protected ApplicationWindow createNewWindow() {
try {
return (ApplicationWindow) services().getBean(APPLICATION_WINDOW_BEAN_ID, ApplicationWindow.class);
} catch (NoSuchBeanDefinitionException e) {
return new DefaultApplicationWindow();
}
}
public WindowManager getWindowManager() {
return windowManager;
}
public ApplicationWindow getActiveWindow() {
return activeWindow;
}
public void close() {
if (windowManager.close()) {
if (getServices().getApplicationContext() instanceof ConfigurableApplicationContext) {
((ConfigurableApplicationContext) getServices().getApplicationContext()).close();
}
System.exit(0);
}
}
/*
* Closes the application once all windows have been closed.
*/
private class CloseApplicationObserver implements Observer {
boolean firstWindowCreated = false;
public void update(Observable o, Object arg) {
int numOpenWidows = windowManager.getWindows().length;
// make sure we only close the application after at least 1 window
// has been added
if (!firstWindowCreated && numOpenWidows > 0) {
firstWindowCreated = true;
} else if (firstWindowCreated && numOpenWidows == 0) {
close();
}
}
}
} | src/org/springframework/richclient/application/Application.java | /*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.richclient.application;
import java.awt.Image;
import java.util.Observable;
import java.util.Observer;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.richclient.application.config.ApplicationLifecycleAdvisor;
import org.springframework.richclient.application.support.DefaultApplicationWindow;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* A singleton workbench or shell of a rich client application.
* <p>
* The application provides a point of reference and context for an entire
* application. It provides an interface to open application windows.
*
* @author Keith Donald
*/
public class Application implements InitializingBean, ApplicationContextAware {
private static final String DEFAULT_APPLICATION_IMAGE_KEY = "applicationInfo.image";
private static final String APPLICATION_WINDOW_BEAN_ID = "applicationWindowPrototype";
private static Application SOLE_INSTANCE;
private ApplicationDescriptor descriptor;
private ApplicationServices services;
private ApplicationLifecycleAdvisor lifecycleAdvisor;
private ApplicationWindow activeWindow;
private WindowManager windowManager;
/**
* Load the single application instance.
*
* @param instance
* The application
*/
public static void load(Application instance) {
SOLE_INSTANCE = instance;
}
/**
* Return the single application instance.
*
* @return The application
*/
public static Application instance() {
Assert
.state(isLoaded(),
"The global rich client application instance has not yet been initialized; it must be created and loaded first.");
return SOLE_INSTANCE;
}
public static boolean isLoaded() {
return SOLE_INSTANCE != null;
}
/**
* Return a global service locator for application services.
*
* @return The application services locator.
*/
public static ApplicationServices services() {
return instance().getServices();
}
public Application(ApplicationLifecycleAdvisor advisor) {
this(null, advisor, null);
}
public Application(ApplicationDescriptor descriptor, ApplicationLifecycleAdvisor advisor) {
this(descriptor, advisor, null);
}
public Application(ApplicationDescriptor descriptor, ApplicationLifecycleAdvisor advisor,
ApplicationServices services) {
setDescriptor(descriptor);
setLifecycleAdvisor(advisor);
setServices(services);
this.windowManager = new WindowManager();
this.windowManager.addObserver(new CloseApplicationObserver());
Assert.state(!isLoaded(), "Only one instance of a Spring Rich Application allowed per VM.");
load(this);
}
public void setDescriptor(ApplicationDescriptor descriptor) {
this.descriptor = descriptor;
}
public void setServices(ApplicationServices services) {
this.services = services;
}
private void setLifecycleAdvisor(ApplicationLifecycleAdvisor advisor) {
this.lifecycleAdvisor = advisor;
}
public void setApplicationContext(ApplicationContext context) {
getServices().setApplicationContext(context);
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.lifecycleAdvisor,
"The application advisor is required, for processing of application lifecycle events");
getLifecycleAdvisor().onPreInitialize(this);
}
public ApplicationLifecycleAdvisor getLifecycleAdvisor() {
return lifecycleAdvisor;
}
public ApplicationServices getServices() {
if (services == null) {
services = new ApplicationServices();
}
return services;
}
public String getName() {
if (descriptor != null && StringUtils.hasText(descriptor.getDisplayName())) {
return descriptor.getDisplayName();
} else {
return "Spring Rich Client Application";
}
}
public Image getImage() {
if (descriptor != null && descriptor.getImage() != null) {
return descriptor.getImage();
} else {
return Application.services().getImage(DEFAULT_APPLICATION_IMAGE_KEY);
}
}
public void openWindow(String pageDescriptorId) {
ApplicationWindow newWindow = initWindow(createNewWindow());
newWindow.showPage(pageDescriptorId);
// @TODO track active window...
this.activeWindow = newWindow;
}
private ApplicationWindow initWindow(ApplicationWindow window) {
windowManager.add(window);
return window;
}
protected ApplicationWindow createNewWindow() {
try {
return (ApplicationWindow) services().getBean(APPLICATION_WINDOW_BEAN_ID, ApplicationWindow.class);
} catch (NoSuchBeanDefinitionException e) {
return new DefaultApplicationWindow();
}
}
public WindowManager getWindowManager() {
return windowManager;
}
public ApplicationWindow getActiveWindow() {
return activeWindow;
}
public void close() {
if (windowManager.close()) {
if (getServices().getApplicationContext() instanceof ConfigurableApplicationContext) {
((ConfigurableApplicationContext) getServices().getApplicationContext()).close();
}
System.exit(0);
}
}
/*
* Closes the application once all windows have been closed.
*/
private class CloseApplicationObserver implements Observer {
boolean firstWindowCreated = false;
public void update(Observable o, Object arg) {
int numOpenWidows = windowManager.getWindows().length;
// make sure we only close the application after at least 1 window
// has been added
if (!firstWindowCreated && numOpenWidows > 0) {
firstWindowCreated = true;
} else if (firstWindowCreated && numOpenWidows == 0) {
close();
}
}
}
} | Add a getDescriptor method
| src/org/springframework/richclient/application/Application.java | Add a getDescriptor method | <ide><path>rc/org/springframework/richclient/application/Application.java
<ide> this.descriptor = descriptor;
<ide> }
<ide>
<add> public ApplicationDescriptor getDescriptor() {
<add> return descriptor;
<add> }
<add>
<ide> public void setServices(ApplicationServices services) {
<ide> this.services = services;
<ide> } |
|
Java | lgpl-2.1 | ec0da5bb8cece767caa2ca768d6d3e8dfd9f9aa6 | 0 | biojava/biojava,pwrose/biojava,sbliven/biojava-sbliven,pwrose/biojava,sbliven/biojava-sbliven,paolopavan/biojava,lafita/biojava,zachcp/biojava,pwrose/biojava,sbliven/biojava-sbliven,heuermh/biojava,zachcp/biojava,zachcp/biojava,fionakim/biojava,paolopavan/biojava,emckee2006/biojava,andreasprlic/biojava,fionakim/biojava,lafita/biojava,biojava/biojava,fionakim/biojava,biojava/biojava,andreasprlic/biojava,heuermh/biojava,lafita/biojava,andreasprlic/biojava,emckee2006/biojava,paolopavan/biojava,andreasprlic/biojava,emckee2006/biojava,heuermh/biojava | /*
* PDB web development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
*
* Created on Jun 13, 2009
* Created by Andreas Prlic
*
*/
package org.biojava.nbio.structure.align.gui;
import org.biojava.nbio.structure.*;
import org.biojava.nbio.structure.align.gui.aligpanel.AligPanel;
import org.biojava.nbio.structure.align.gui.aligpanel.StatusDisplay;
import org.biojava.nbio.structure.align.gui.jmol.JmolTools;
import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol;
import org.biojava.nbio.structure.align.model.AFPChain;
import org.biojava.nbio.structure.align.util.AFPAlignmentDisplay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
/** A utility class for visualistion of structure alignments
*
* @author Andreas Prlic
*
*/
public class DisplayAFP
{
private static final Logger logger = LoggerFactory.getLogger(DisplayAFP.class);
//TODO: same as getEqrPos??? !!!
public static final List<Integer> getEQRAlignmentPos(AFPChain afpChain){
List<Integer> lst = new ArrayList<Integer>();
char[] s1 = afpChain.getAlnseq1();
char[] s2 = afpChain.getAlnseq2();
char[] symb = afpChain.getAlnsymb();
boolean isFatCat = afpChain.getAlgorithmName().startsWith("jFatCat");
for ( int i =0 ; i< s1.length; i++){
char c1 = s1[i];
char c2 = s2[i];
if ( isAlignedPosition(i,c1,c2,isFatCat, symb)) {
lst.add(i);
}
}
return lst;
}
private static boolean isAlignedPosition(int i, char c1, char c2, boolean isFatCat,char[]symb)
{
// if ( isFatCat){
char s = symb[i];
if ( c1 != '-' && c2 != '-' && s != ' '){
return true;
}
// } else {
//
// if ( c1 != '-' && c2 != '-')
// return true;
// }
return false;
}
public static final List<String> getPDBresnum(int aligPos, AFPChain afpChain, Atom[] ca){
List<String> lst = new ArrayList<String>();
if ( aligPos > 1) {
System.err.println("multiple alignments not supported yet!");
return lst;
}
int blockNum = afpChain.getBlockNum();
int[] optLen = afpChain.getOptLen();
int[][][] optAln = afpChain.getOptAln();
if ( optLen == null)
return lst;
for(int bk = 0; bk < blockNum; bk ++) {
for ( int i=0;i< optLen[bk];i++){
int pos = optAln[bk][aligPos][i];
if ( pos < ca.length) {
String pdbInfo = JmolTools.getPdbInfo(ca[pos]);
//lst.add(ca1[pos].getParent().getPDBCode());
lst.add(pdbInfo);
}
}
}
return lst;
}
/** get the block number for an aligned position
*
* @param afpChain
* @param aligPos
* @return
* @deprecated use AFPAlignmentDisplay.getBlockNrForAlignPos instead...
*/
@Deprecated
public static int getBlockNrForAlignPos(AFPChain afpChain, int aligPos){
return AFPAlignmentDisplay.getBlockNrForAlignPos(afpChain, aligPos);
}
/** return the atom at alignment position aligPos. at the present only works with block 0
* @param chainNr the number of the aligned pair. 0... first chain, 1... second chain.
* @param afpChain an afpChain object
* @param aligPos position on the alignment
* @param getPrevious gives the previous position if false, gives the next posible atom
* @return a CA atom that is at a particular position of the alignment
*/
public static final Atom getAtomForAligPos(AFPChain afpChain,int chainNr, int aligPos, Atom[] ca , boolean getPrevious ) throws StructureException{
int[] optLen = afpChain.getOptLen();
// int[][][] optAln = afpChain.getOptAln();
if ( optLen == null)
return null;
if (chainNr < 0 || chainNr > 1){
throw new StructureException("So far only pairwise alignments are supported, but you requested results for alinged chain nr " + chainNr);
}
//if ( afpChain.getAlgorithmName().startsWith("jFatCat")){
/// for FatCat algorithms...
int capos = getUngappedFatCatPos(afpChain, chainNr, aligPos);
if ( capos < 0) {
capos = getNextFatCatPos(afpChain, chainNr, aligPos,getPrevious);
//System.out.println(" got next" + capos + " for " + chainNr + " alignedPos: " + aligPos);
} else {
//System.out.println("got aligned fatcat position: " + capos + " " + chainNr + " for alig pos: " + aligPos);
}
if ( capos < 0) {
System.err.println("could not match position " + aligPos + " in chain " + chainNr +". Returing null...");
return null;
}
if ( capos > ca.length){
System.err.println("Atom array "+ chainNr + " does not have " + capos +" atoms. Returning null.");
return null;
}
return ca[capos];
//}
//
//
// int ungappedPos = getUngappedPos(afpChain, aligPos);
// System.out.println("getAtomForAligPOs " + aligPos + " " + ungappedPos );
// return ca[ungappedPos];
//
// if ( ungappedPos >= optAln[bk][chainNr].length)
// return null;
// int pos = optAln[bk][chainNr][ungappedPos];
// if ( pos > ca.length)
// return null;
// return ca[pos];
}
private static int getNextFatCatPos(AFPChain afpChain, int chainNr,
int aligPos, boolean getPrevious) {
char[] aseq;
if ( chainNr == 0 )
aseq = afpChain.getAlnseq1();
else
aseq = afpChain.getAlnseq2();
if ( aligPos > aseq.length)
return -1;
if ( aligPos < 0)
return -1;
int blockNum = afpChain.getBlockNum();
int[] optLen = afpChain.getOptLen();
int[][][] optAln = afpChain.getOptAln();
int p1, p2;
int p1b = 0;
int p2b = 0;
int len = 0;
boolean terminateNextMatch = false;
for(int i = 0; i < blockNum; i ++) {
for(int j = 0; j < optLen[i]; j ++) {
p1 = optAln[i][0][j];
p2 = optAln[i][1][j];
if(len > 0) {
int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1);
// lmax gives the length of an alignment gap
//System.out.println(" pos "+ len+" p1-p2: " + p1 + " - " + p2 + " lmax: " + lmax + " p1b-p2b:"+p1b + " " + p2b + " terminate? "+ terminateNextMatch);
for(int k = 0; k < lmax; k ++) {
if(k >= (p1 - p1b - 1)) {
// a gap position in chain 0
if ( aligPos == len && chainNr == 0 ){
if ( getPrevious)
return p1b;
else
terminateNextMatch = true;
}
}
else {
if ( aligPos == len && chainNr == 0)
return p1b+1+k;
}
if(k >= (p2 - p2b - 1)) {
// a gap position in chain 1
if ( aligPos == len && chainNr == 1){
if ( getPrevious)
return p2b;
else
terminateNextMatch = true;
}
}
else {
if ( aligPos == len && chainNr == 1) {
return p2b+1+k;
}
}
len++;
}
}
if ( aligPos == len && chainNr == 0)
return p1;
if ( aligPos == len && chainNr == 1)
return p2;
if ( terminateNextMatch)
if ( chainNr == 0)
return p1;
else
return p2;
if ( len > aligPos) {
if ( getPrevious) {
if ( chainNr == 0)
return p1b;
else
return p2b;
} else {
terminateNextMatch = true;
}
}
len++;
p1b = p1;
p2b = p2;
}
}
// we did not find an aligned position
return -1;
}
private static final int getUngappedFatCatPos(AFPChain afpChain, int chainNr, int aligPos){
char[] aseq;
if ( chainNr == 0 )
aseq = afpChain.getAlnseq1();
else
aseq = afpChain.getAlnseq2();
if ( aligPos > aseq.length)
return -1;
if ( aligPos < 0)
return -1;
int blockNum = afpChain.getBlockNum();
int[] optLen = afpChain.getOptLen();
int[][][] optAln = afpChain.getOptAln();
int p1, p2;
int p1b = 0;
int p2b = 0;
int len = 0;
for(int i = 0; i < blockNum; i ++) {
for(int j = 0; j < optLen[i]; j ++) {
p1 = optAln[i][0][j];
p2 = optAln[i][1][j];
if(len > 0) {
int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1);
// lmax gives the length of an alignment gap
//System.out.println(" p1-p2: " + p1 + " - " + p2 + " lmax: " + lmax + " p1b-p2b:"+p1b + " " + p2b);
for(int k = 0; k < lmax; k ++) {
if(k >= (p1 - p1b - 1)) {
// a gap position in chain 0
if ( aligPos == len && chainNr == 0){
return -1;
}
}
else {
if ( aligPos == len && chainNr == 0)
return p1b+1+k;
}
if(k >= (p2 - p2b - 1)) {
// a gap position in chain 1
if ( aligPos == len && chainNr == 1){
return -1;
}
}
else {
if ( aligPos == len && chainNr == 1) {
return p2b+1+k;
}
}
len++;
}
}
if ( aligPos == len && chainNr == 0)
return p1;
if ( aligPos == len && chainNr == 1)
return p2;
len++;
p1b = p1;
p2b = p2;
}
}
// we did not find an aligned position
return -1;
}
/** get an artifical List of chains containing the Atoms and groups.
* Does NOT rotate anything.
* @param ca
* @return a list of Chains that is built up from the Atoms in the ca array
* @throws StructureException
*/
private static final List<Chain> getAlignedModel(Atom[] ca){
List<Chain> model = new ArrayList<Chain>();
for ( Atom a: ca){
Group g = a.getGroup();
Chain parentC = g.getChain();
Chain newChain = null;
for ( Chain c : model) {
if ( c.getChainID().equals(parentC.getChainID())){
newChain = c;
break;
}
}
if ( newChain == null){
newChain = new ChainImpl();
newChain.setChainID(parentC.getChainID());
model.add(newChain);
}
newChain.addGroup(g);
}
return model;
}
/** Get an artifical Structure containing both chains.
* Does NOT rotate anything
* @param ca1
* @param ca2
* @return a structure object containing two models, one for each set of Atoms.
* @throws StructureException
*/
public static final Structure getAlignedStructure(Atom[] ca1, Atom[] ca2) throws StructureException{
Structure s = new StructureImpl();
List<Chain>model1 = getAlignedModel(ca1);
List<Chain>model2 = getAlignedModel(ca2);
s.addModel(model1);
s.addModel(model2);
return s;
}
public static final Atom[] getAtomArray(Atom[] ca,List<Group> hetatms, List<Group> nucleotides ) throws StructureException{
List<Atom> atoms = new ArrayList<Atom>();
for (Atom a: ca){
atoms.add(a);
}
logger.debug("got {} hetatoms", hetatms.size());
// we only add atom nr 1, since the getAlignedStructure method actually adds the parent group, and not the atoms...
for (Group g : hetatms){
if (g.size() < 1)
continue;
//if (debug)
// System.out.println("adding group " + g);
Atom a = g.getAtom(0);
//if (debug)
// System.out.println(a);
a.setGroup(g);
atoms.add(a);
}
for (Group g : nucleotides ){
if (g.size() < 1)
continue;
//if (debug)
// System.out.println("adding group " + g);
Atom a = g.getAtom(0);
//if (debug)
// System.out.println(a);
a.setGroup(g);
atoms.add(a);
}
Atom[] arr = (Atom[]) atoms.toArray(new Atom[atoms.size()]);
return arr;
}
/** Note: ca2, hetatoms2 and nucleotides2 should not be rotated. This will be done here...
* */
public static final StructureAlignmentJmol display(AFPChain afpChain,Group[] twistedGroups, Atom[] ca1, Atom[] ca2,List<Group> hetatms, List<Group> nucleotides, List<Group> hetatms2, List<Group> nucleotides2 ) throws StructureException{
List<Atom> twistedAs = new ArrayList<Atom>();
for ( Group g: twistedGroups){
if ( g == null )
continue;
if ( g.size() < 1)
continue;
Atom a = g.getAtom(0);
twistedAs.add(a);
}
Atom[] twistedAtoms = (Atom[])twistedAs.toArray(new Atom[twistedAs.size()]);
Atom[] arr1 = getAtomArray(ca1, hetatms, nucleotides);
Atom[] arr2 = getAtomArray(twistedAtoms, hetatms2, nucleotides2);
//
//if ( hetatms2.size() > 0)
// System.out.println("atom after:" + hetatms2.get(0).getAtom(0));
//if ( hetatms2.size() > 0)
// System.out.println("atom after:" + hetatms2.get(0).getAtom(0));
String title = afpChain.getAlgorithmName() + " V." +afpChain.getVersion() + " : " + afpChain.getName1() + " vs. " + afpChain.getName2();
//System.out.println(artificial.toPDB());
StructureAlignmentJmol jmol = new StructureAlignmentJmol(afpChain,arr1,arr2);
//jmol.setStructure(artificial);
//jmol.setTitle("Structure Alignment: " + afpChain.getName1() + " vs. " + afpChain.getName2());
jmol.setTitle(title);
return jmol;
}
public static void showAlignmentImage(AFPChain afpChain, Atom[] ca1, Atom[] ca2, StructureAlignmentJmol jmol) {
String result = afpChain.toFatcat(ca1, ca2);
//String rot = afpChain.toRotMat();
//DisplayAFP.showAlignmentImage(afpChain, result + AFPChain.newline + rot);
AligPanel me = new AligPanel();
me.setStructureAlignmentJmol(jmol);
me.setAFPChain(afpChain);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle(afpChain.getName1() + " vs. " + afpChain.getName2() + " | " + afpChain.getAlgorithmName() + " V. " + afpChain.getVersion());
me.setPreferredSize(new Dimension(me.getCoordManager().getPreferredWidth() , me.getCoordManager().getPreferredHeight()));
JMenuBar menu = MenuCreator.getAlignmentTextMenu(frame,me,afpChain);
frame.setJMenuBar(menu);
JScrollPane scroll = new JScrollPane(me);
scroll.setAutoscrolls(true);
StatusDisplay status = new StatusDisplay();
status.setAfpChain(afpChain);
status.setCa1(ca1);
status.setCa2(ca2);
me.setCa1(ca1);
me.setCa2(ca2);
me.addAlignmentPositionListener(status);
Box vBox = Box.createVerticalBox();
vBox.add(scroll);
vBox.add(status);
frame.getContentPane().add(vBox);
frame.pack();
frame.setVisible(true);
// make sure they get cleaned up correctly:
frame.addWindowListener(me);
frame.addWindowListener(status);
}
public static void showAlignmentImage(AFPChain afpChain, String result) {
JFrame frame = new JFrame();
String title = afpChain.getAlgorithmName() + " V."+afpChain.getVersion() + " : " + afpChain.getName1() + " vs. " + afpChain.getName2() ;
frame.setTitle(title);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
AlignmentTextPanel txtPanel = new AlignmentTextPanel();
txtPanel.setText(result);
JMenuBar menu = MenuCreator.getAlignmentTextMenu(frame,txtPanel,afpChain);
frame.setJMenuBar(menu);
JScrollPane js = new JScrollPane();
js.getViewport().add(txtPanel);
js.getViewport().setBorder(null);
//js.setViewportBorder(null);
//js.setBorder(null);
//js.setBackground(Color.white);
frame.getContentPane().add(js);
frame.pack();
frame.setVisible(true);
}
/** Create a "fake" Structure objects that contains the two sets of atoms aligned on top of each other.
*
* @param afpChain the container of the alignment
* @param ca1 atoms for protein 1
* @param ca2 atoms for protein 2
* @return a protein structure with 2 models.
* @throws StructureException
*/
public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1,
Atom[] ca2) throws StructureException{
if ( afpChain.getNrEQR() < 1){
return DisplayAFP.getAlignedStructure(ca1, ca2);
}
Group[] twistedGroups = StructureAlignmentDisplay.prepareGroupsForDisplay(afpChain,ca1, ca2);
List<Atom> twistedAs = new ArrayList<Atom>();
for ( Group g: twistedGroups){
if ( g == null )
continue;
if ( g.size() < 1)
continue;
Atom a = g.getAtom(0);
twistedAs.add(a);
}
Atom[] twistedAtoms = (Atom[])twistedAs.toArray(new Atom[twistedAs.size()]);
List<Group> hetatms = new ArrayList<Group>();
List<Group> nucs1 = new ArrayList<Group>();
Group g1 = ca1[0].getGroup();
Chain c1 = null;
if ( g1 != null) {
c1 = g1.getChain();
if ( c1 != null){
hetatms = c1.getAtomGroups(GroupType.HETATM);;
nucs1 = c1.getAtomGroups(GroupType.NUCLEOTIDE);
}
}
List<Group> hetatms2 = new ArrayList<Group>();
List<Group> nucs2 = new ArrayList<Group>();
Group g2 = ca2[0].getGroup();
Chain c2 = null;
if ( g2 != null){
c2 = g2.getChain();
if ( c2 != null){
hetatms2 = c2.getAtomGroups(GroupType.HETATM);
nucs2 = c2.getAtomGroups(GroupType.NUCLEOTIDE);
}
}
Atom[] arr1 = DisplayAFP.getAtomArray(ca1, hetatms, nucs1);
Atom[] arr2 = DisplayAFP.getAtomArray(twistedAtoms, hetatms2, nucs2);
Structure artificial = DisplayAFP.getAlignedStructure(arr1,arr2);
return artificial;
}
}
| biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java | /*
* PDB web development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
*
* Created on Jun 13, 2009
* Created by Andreas Prlic
*
*/
package org.biojava.nbio.structure.align.gui;
import org.biojava.nbio.structure.*;
import org.biojava.nbio.structure.align.gui.aligpanel.AligPanel;
import org.biojava.nbio.structure.align.gui.aligpanel.StatusDisplay;
import org.biojava.nbio.structure.align.gui.jmol.JmolTools;
import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol;
import org.biojava.nbio.structure.align.model.AFPChain;
import org.biojava.nbio.structure.align.util.AFPAlignmentDisplay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
/** A utility class for visualistion of structure alignments
*
* @author Andreas Prlic
*
*/
public class DisplayAFP
{
private static final Logger logger = LoggerFactory.getLogger(DisplayAFP.class);
//TODO: same as getEqrPos??? !!!
public static final List<Integer> getEQRAlignmentPos(AFPChain afpChain){
List<Integer> lst = new ArrayList<Integer>();
char[] s1 = afpChain.getAlnseq1();
char[] s2 = afpChain.getAlnseq2();
char[] symb = afpChain.getAlnsymb();
boolean isFatCat = afpChain.getAlgorithmName().startsWith("jFatCat");
for ( int i =0 ; i< s1.length; i++){
char c1 = s1[i];
char c2 = s2[i];
if ( isAlignedPosition(i,c1,c2,isFatCat, symb)) {
lst.add(i);
}
}
return lst;
}
private static boolean isAlignedPosition(int i, char c1, char c2, boolean isFatCat,char[]symb)
{
if ( isFatCat){
char s = symb[i];
if ( c1 != '-' && c2 != '-' && s != ' '){
return true;
}
} else {
if ( c1 != '-' && c2 != '-')
return true;
}
return false;
}
public static final List<String> getPDBresnum(int aligPos, AFPChain afpChain, Atom[] ca){
List<String> lst = new ArrayList<String>();
if ( aligPos > 1) {
System.err.println("multiple alignments not supported yet!");
return lst;
}
int blockNum = afpChain.getBlockNum();
int[] optLen = afpChain.getOptLen();
int[][][] optAln = afpChain.getOptAln();
if ( optLen == null)
return lst;
for(int bk = 0; bk < blockNum; bk ++) {
for ( int i=0;i< optLen[bk];i++){
int pos = optAln[bk][aligPos][i];
if ( pos < ca.length) {
String pdbInfo = JmolTools.getPdbInfo(ca[pos]);
//lst.add(ca1[pos].getParent().getPDBCode());
lst.add(pdbInfo);
}
}
}
return lst;
}
/** get the block number for an aligned position
*
* @param afpChain
* @param aligPos
* @return
* @deprecated use AFPAlignmentDisplay.getBlockNrForAlignPos instead...
*/
@Deprecated
public static int getBlockNrForAlignPos(AFPChain afpChain, int aligPos){
return AFPAlignmentDisplay.getBlockNrForAlignPos(afpChain, aligPos);
}
/** return the atom at alignment position aligPos. at the present only works with block 0
* @param chainNr the number of the aligned pair. 0... first chain, 1... second chain.
* @param afpChain an afpChain object
* @param aligPos position on the alignment
* @param getPrevious gives the previous position if false, gives the next posible atom
* @return a CA atom that is at a particular position of the alignment
*/
public static final Atom getAtomForAligPos(AFPChain afpChain,int chainNr, int aligPos, Atom[] ca , boolean getPrevious ) throws StructureException{
int[] optLen = afpChain.getOptLen();
// int[][][] optAln = afpChain.getOptAln();
if ( optLen == null)
return null;
if (chainNr < 0 || chainNr > 1){
throw new StructureException("So far only pairwise alignments are supported, but you requested results for alinged chain nr " + chainNr);
}
//if ( afpChain.getAlgorithmName().startsWith("jFatCat")){
/// for FatCat algorithms...
int capos = getUngappedFatCatPos(afpChain, chainNr, aligPos);
if ( capos < 0) {
capos = getNextFatCatPos(afpChain, chainNr, aligPos,getPrevious);
//System.out.println(" got next" + capos + " for " + chainNr + " alignedPos: " + aligPos);
} else {
//System.out.println("got aligned fatcat position: " + capos + " " + chainNr + " for alig pos: " + aligPos);
}
if ( capos < 0) {
System.err.println("could not match position " + aligPos + " in chain " + chainNr +". Returing null...");
return null;
}
if ( capos > ca.length){
System.err.println("Atom array "+ chainNr + " does not have " + capos +" atoms. Returning null.");
return null;
}
return ca[capos];
//}
//
//
// int ungappedPos = getUngappedPos(afpChain, aligPos);
// System.out.println("getAtomForAligPOs " + aligPos + " " + ungappedPos );
// return ca[ungappedPos];
//
// if ( ungappedPos >= optAln[bk][chainNr].length)
// return null;
// int pos = optAln[bk][chainNr][ungappedPos];
// if ( pos > ca.length)
// return null;
// return ca[pos];
}
private static int getNextFatCatPos(AFPChain afpChain, int chainNr,
int aligPos, boolean getPrevious) {
char[] aseq;
if ( chainNr == 0 )
aseq = afpChain.getAlnseq1();
else
aseq = afpChain.getAlnseq2();
if ( aligPos > aseq.length)
return -1;
if ( aligPos < 0)
return -1;
int blockNum = afpChain.getBlockNum();
int[] optLen = afpChain.getOptLen();
int[][][] optAln = afpChain.getOptAln();
int p1, p2;
int p1b = 0;
int p2b = 0;
int len = 0;
boolean terminateNextMatch = false;
for(int i = 0; i < blockNum; i ++) {
for(int j = 0; j < optLen[i]; j ++) {
p1 = optAln[i][0][j];
p2 = optAln[i][1][j];
if(len > 0) {
int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1);
// lmax gives the length of an alignment gap
//System.out.println(" pos "+ len+" p1-p2: " + p1 + " - " + p2 + " lmax: " + lmax + " p1b-p2b:"+p1b + " " + p2b + " terminate? "+ terminateNextMatch);
for(int k = 0; k < lmax; k ++) {
if(k >= (p1 - p1b - 1)) {
// a gap position in chain 0
if ( aligPos == len && chainNr == 0 ){
if ( getPrevious)
return p1b;
else
terminateNextMatch = true;
}
}
else {
if ( aligPos == len && chainNr == 0)
return p1b+1+k;
}
if(k >= (p2 - p2b - 1)) {
// a gap position in chain 1
if ( aligPos == len && chainNr == 1){
if ( getPrevious)
return p2b;
else
terminateNextMatch = true;
}
}
else {
if ( aligPos == len && chainNr == 1) {
return p2b+1+k;
}
}
len++;
}
}
if ( aligPos == len && chainNr == 0)
return p1;
if ( aligPos == len && chainNr == 1)
return p2;
if ( terminateNextMatch)
if ( chainNr == 0)
return p1;
else
return p2;
if ( len > aligPos) {
if ( getPrevious) {
if ( chainNr == 0)
return p1b;
else
return p2b;
} else {
terminateNextMatch = true;
}
}
len++;
p1b = p1;
p2b = p2;
}
}
// we did not find an aligned position
return -1;
}
private static final int getUngappedFatCatPos(AFPChain afpChain, int chainNr, int aligPos){
char[] aseq;
if ( chainNr == 0 )
aseq = afpChain.getAlnseq1();
else
aseq = afpChain.getAlnseq2();
if ( aligPos > aseq.length)
return -1;
if ( aligPos < 0)
return -1;
int blockNum = afpChain.getBlockNum();
int[] optLen = afpChain.getOptLen();
int[][][] optAln = afpChain.getOptAln();
int p1, p2;
int p1b = 0;
int p2b = 0;
int len = 0;
for(int i = 0; i < blockNum; i ++) {
for(int j = 0; j < optLen[i]; j ++) {
p1 = optAln[i][0][j];
p2 = optAln[i][1][j];
if(len > 0) {
int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1);
// lmax gives the length of an alignment gap
//System.out.println(" p1-p2: " + p1 + " - " + p2 + " lmax: " + lmax + " p1b-p2b:"+p1b + " " + p2b);
for(int k = 0; k < lmax; k ++) {
if(k >= (p1 - p1b - 1)) {
// a gap position in chain 0
if ( aligPos == len && chainNr == 0){
return -1;
}
}
else {
if ( aligPos == len && chainNr == 0)
return p1b+1+k;
}
if(k >= (p2 - p2b - 1)) {
// a gap position in chain 1
if ( aligPos == len && chainNr == 1){
return -1;
}
}
else {
if ( aligPos == len && chainNr == 1) {
return p2b+1+k;
}
}
len++;
}
}
if ( aligPos == len && chainNr == 0)
return p1;
if ( aligPos == len && chainNr == 1)
return p2;
len++;
p1b = p1;
p2b = p2;
}
}
// we did not find an aligned position
return -1;
}
/** get an artifical List of chains containing the Atoms and groups.
* Does NOT rotate anything.
* @param ca
* @return a list of Chains that is built up from the Atoms in the ca array
* @throws StructureException
*/
private static final List<Chain> getAlignedModel(Atom[] ca){
List<Chain> model = new ArrayList<Chain>();
for ( Atom a: ca){
Group g = a.getGroup();
Chain parentC = g.getChain();
Chain newChain = null;
for ( Chain c : model) {
if ( c.getChainID().equals(parentC.getChainID())){
newChain = c;
break;
}
}
if ( newChain == null){
newChain = new ChainImpl();
newChain.setChainID(parentC.getChainID());
model.add(newChain);
}
newChain.addGroup(g);
}
return model;
}
/** Get an artifical Structure containing both chains.
* Does NOT rotate anything
* @param ca1
* @param ca2
* @return a structure object containing two models, one for each set of Atoms.
* @throws StructureException
*/
public static final Structure getAlignedStructure(Atom[] ca1, Atom[] ca2) throws StructureException{
Structure s = new StructureImpl();
List<Chain>model1 = getAlignedModel(ca1);
List<Chain>model2 = getAlignedModel(ca2);
s.addModel(model1);
s.addModel(model2);
return s;
}
public static final Atom[] getAtomArray(Atom[] ca,List<Group> hetatms, List<Group> nucleotides ) throws StructureException{
List<Atom> atoms = new ArrayList<Atom>();
for (Atom a: ca){
atoms.add(a);
}
logger.debug("got {} hetatoms", hetatms.size());
// we only add atom nr 1, since the getAlignedStructure method actually adds the parent group, and not the atoms...
for (Group g : hetatms){
if (g.size() < 1)
continue;
//if (debug)
// System.out.println("adding group " + g);
Atom a = g.getAtom(0);
//if (debug)
// System.out.println(a);
a.setGroup(g);
atoms.add(a);
}
for (Group g : nucleotides ){
if (g.size() < 1)
continue;
//if (debug)
// System.out.println("adding group " + g);
Atom a = g.getAtom(0);
//if (debug)
// System.out.println(a);
a.setGroup(g);
atoms.add(a);
}
Atom[] arr = (Atom[]) atoms.toArray(new Atom[atoms.size()]);
return arr;
}
/** Note: ca2, hetatoms2 and nucleotides2 should not be rotated. This will be done here...
* */
public static final StructureAlignmentJmol display(AFPChain afpChain,Group[] twistedGroups, Atom[] ca1, Atom[] ca2,List<Group> hetatms, List<Group> nucleotides, List<Group> hetatms2, List<Group> nucleotides2 ) throws StructureException{
List<Atom> twistedAs = new ArrayList<Atom>();
for ( Group g: twistedGroups){
if ( g == null )
continue;
if ( g.size() < 1)
continue;
Atom a = g.getAtom(0);
twistedAs.add(a);
}
Atom[] twistedAtoms = (Atom[])twistedAs.toArray(new Atom[twistedAs.size()]);
Atom[] arr1 = getAtomArray(ca1, hetatms, nucleotides);
Atom[] arr2 = getAtomArray(twistedAtoms, hetatms2, nucleotides2);
//
//if ( hetatms2.size() > 0)
// System.out.println("atom after:" + hetatms2.get(0).getAtom(0));
//if ( hetatms2.size() > 0)
// System.out.println("atom after:" + hetatms2.get(0).getAtom(0));
String title = afpChain.getAlgorithmName() + " V." +afpChain.getVersion() + " : " + afpChain.getName1() + " vs. " + afpChain.getName2();
//System.out.println(artificial.toPDB());
StructureAlignmentJmol jmol = new StructureAlignmentJmol(afpChain,arr1,arr2);
//jmol.setStructure(artificial);
//jmol.setTitle("Structure Alignment: " + afpChain.getName1() + " vs. " + afpChain.getName2());
jmol.setTitle(title);
return jmol;
}
public static void showAlignmentImage(AFPChain afpChain, Atom[] ca1, Atom[] ca2, StructureAlignmentJmol jmol) {
String result = afpChain.toFatcat(ca1, ca2);
//String rot = afpChain.toRotMat();
//DisplayAFP.showAlignmentImage(afpChain, result + AFPChain.newline + rot);
AligPanel me = new AligPanel();
me.setStructureAlignmentJmol(jmol);
me.setAFPChain(afpChain);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle(afpChain.getName1() + " vs. " + afpChain.getName2() + " | " + afpChain.getAlgorithmName() + " V. " + afpChain.getVersion());
me.setPreferredSize(new Dimension(me.getCoordManager().getPreferredWidth() , me.getCoordManager().getPreferredHeight()));
JMenuBar menu = MenuCreator.getAlignmentTextMenu(frame,me,afpChain);
frame.setJMenuBar(menu);
JScrollPane scroll = new JScrollPane(me);
scroll.setAutoscrolls(true);
StatusDisplay status = new StatusDisplay();
status.setAfpChain(afpChain);
status.setCa1(ca1);
status.setCa2(ca2);
me.setCa1(ca1);
me.setCa2(ca2);
me.addAlignmentPositionListener(status);
Box vBox = Box.createVerticalBox();
vBox.add(scroll);
vBox.add(status);
frame.getContentPane().add(vBox);
frame.pack();
frame.setVisible(true);
// make sure they get cleaned up correctly:
frame.addWindowListener(me);
frame.addWindowListener(status);
}
public static void showAlignmentImage(AFPChain afpChain, String result) {
JFrame frame = new JFrame();
String title = afpChain.getAlgorithmName() + " V."+afpChain.getVersion() + " : " + afpChain.getName1() + " vs. " + afpChain.getName2() ;
frame.setTitle(title);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
AlignmentTextPanel txtPanel = new AlignmentTextPanel();
txtPanel.setText(result);
JMenuBar menu = MenuCreator.getAlignmentTextMenu(frame,txtPanel,afpChain);
frame.setJMenuBar(menu);
JScrollPane js = new JScrollPane();
js.getViewport().add(txtPanel);
js.getViewport().setBorder(null);
//js.setViewportBorder(null);
//js.setBorder(null);
//js.setBackground(Color.white);
frame.getContentPane().add(js);
frame.pack();
frame.setVisible(true);
}
/** Create a "fake" Structure objects that contains the two sets of atoms aligned on top of each other.
*
* @param afpChain the container of the alignment
* @param ca1 atoms for protein 1
* @param ca2 atoms for protein 2
* @return a protein structure with 2 models.
* @throws StructureException
*/
public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1,
Atom[] ca2) throws StructureException{
if ( afpChain.getNrEQR() < 1){
return DisplayAFP.getAlignedStructure(ca1, ca2);
}
Group[] twistedGroups = StructureAlignmentDisplay.prepareGroupsForDisplay(afpChain,ca1, ca2);
List<Atom> twistedAs = new ArrayList<Atom>();
for ( Group g: twistedGroups){
if ( g == null )
continue;
if ( g.size() < 1)
continue;
Atom a = g.getAtom(0);
twistedAs.add(a);
}
Atom[] twistedAtoms = (Atom[])twistedAs.toArray(new Atom[twistedAs.size()]);
List<Group> hetatms = new ArrayList<Group>();
List<Group> nucs1 = new ArrayList<Group>();
Group g1 = ca1[0].getGroup();
Chain c1 = null;
if ( g1 != null) {
c1 = g1.getChain();
if ( c1 != null){
hetatms = c1.getAtomGroups(GroupType.HETATM);;
nucs1 = c1.getAtomGroups(GroupType.NUCLEOTIDE);
}
}
List<Group> hetatms2 = new ArrayList<Group>();
List<Group> nucs2 = new ArrayList<Group>();
Group g2 = ca2[0].getGroup();
Chain c2 = null;
if ( g2 != null){
c2 = g2.getChain();
if ( c2 != null){
hetatms2 = c2.getAtomGroups(GroupType.HETATM);
nucs2 = c2.getAtomGroups(GroupType.NUCLEOTIDE);
}
}
Atom[] arr1 = DisplayAFP.getAtomArray(ca1, hetatms, nucs1);
Atom[] arr2 = DisplayAFP.getAtomArray(twistedAtoms, hetatms2, nucs2);
Structure artificial = DisplayAFP.getAlignedStructure(arr1,arr2);
return artificial;
}
}
| Changed the DisplayAFP, line 76, to color correctly the alignment
(because if the alignment is not FatCat the unaligned residues were
colored as well). | biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java | Changed the DisplayAFP, line 76, to color correctly the alignment (because if the alignment is not FatCat the unaligned residues were colored as well). | <ide><path>iojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java
<ide>
<ide> private static boolean isAlignedPosition(int i, char c1, char c2, boolean isFatCat,char[]symb)
<ide> {
<del> if ( isFatCat){
<add>// if ( isFatCat){
<ide> char s = symb[i];
<ide> if ( c1 != '-' && c2 != '-' && s != ' '){
<ide> return true;
<ide> }
<del> } else {
<del>
<del> if ( c1 != '-' && c2 != '-')
<del> return true;
<del> }
<add>// } else {
<add>//
<add>// if ( c1 != '-' && c2 != '-')
<add>// return true;
<add>// }
<ide>
<ide> return false;
<ide> |
|
Java | apache-2.0 | db98f2739fb1bc6bfeb72198959b81d809b64208 | 0 | tjhart/swivel,tjhart/swivel,tjhart/swivel | package swivel.model;
import org.codehaus.jackson.map.ObjectMapper;
import org.hamcrest.Matcher;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
import static swivel.model.matchers.ContentMatcher.hasContent;
import static swivel.model.matchers.ContentTypeMatcher.hasContentType;
import static swivel.model.matchers.HeaderMatcher.hasHeader;
import static swivel.model.matchers.ParameterMapMatcher.hasParameterMap;
import static swivel.model.matchers.RemoteAddrMatcher.hasRemoteAddr;
import static swivel.model.matchers.RequestMethodMatcher.hasMethod;
import static swivel.model.matchers.RequestedURIPathMatcher.hasURIPath;
import static swivel.model.matchers.ScriptMatcher.scriptMatches;
public class RequestMatcherBuilder {
public static final String METHOD_KEY = "method";
public static final String REMOTE_ADDR_KEY = "remoteAddr";
public static final String CONTENT_TYPE_KEY = "contentType";
public static final String CONTENT_KEY = "content";
public static final String SCRIPT_KEY = "when";
public static final int STATIC_MATCHER_COUNT = 3;
public static final int OPTIONAL_MATCHER_COUNT = 5;
protected ObjectMapper objectMapper = new ObjectMapper();
@SuppressWarnings("unchecked")
public Matcher<HttpServletRequest> buildMatcher(final HttpServletRequest expectationRequest)
throws IOException {
Map<String, Object> json = objectMapper.readValue(expectationRequest.getInputStream(), Map.class);
List<Matcher<HttpServletRequest>> matchers = new ArrayList<Matcher<HttpServletRequest>>(STATIC_MATCHER_COUNT);
matchers.add(hasMethod(equalTo(json.get(METHOD_KEY))));
matchers.add(hasURIPath(equalTo(expectationRequest.getPathInfo())));
matchers.add(buildOptionalMatcher(expectationRequest, json));
return allOf(matchers.toArray(new Matcher[matchers.size()]));
}
@SuppressWarnings("unchecked")
protected Matcher<HttpServletRequest> buildOptionalMatcher(HttpServletRequest expectationRequest,
Map<String, Object> json) {
try {
List<Matcher<HttpServletRequest>> result =
new ArrayList<Matcher<HttpServletRequest>>(OPTIONAL_MATCHER_COUNT);
Map<String, String[]> parameterMap = expectationRequest.getParameterMap();
if (!parameterMap.isEmpty()) {
result.add(hasParameterMap(equalTo(convertParameterMap(parameterMap))));
}
if (json.containsKey(REMOTE_ADDR_KEY)) {
String remoteAddr = (String) json.get(REMOTE_ADDR_KEY);
result.add(
anyOf(hasRemoteAddr(equalTo(remoteAddr)), hasHeader("X-Forwarded-For", hasItem(remoteAddr))));
}
if (json.containsKey(CONTENT_TYPE_KEY)) {
result.add(hasContentType(equalTo(json.get(CONTENT_TYPE_KEY))));
}
if (json.containsKey(CONTENT_KEY)) {
result.add(hasContent(equalTo(json.get(CONTENT_KEY))));
}
if (json.containsKey(SCRIPT_KEY)) {
result.add(scriptMatches((String) json.get(SCRIPT_KEY)));
}
return allOf(result.toArray(new Matcher[result.size()]));
} catch (ScriptException e) {
throw new RuntimeException(e);
}
}
private Map<String, List<String>> convertParameterMap(Map<String, String[]> parameterMap) {
Map<String, List<String>> result = new HashMap<String, List<String>>(parameterMap.size());
for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
result.put(stringEntry.getKey(), Arrays.asList(stringEntry.getValue()));
}
return result;
}
}
| swivel-server/src/main/java/swivel/model/RequestMatcherBuilder.java | package swivel.model;
import swivel.model.matchers.ContentTypeMatcher;
import swivel.model.matchers.HeaderMatcher;
import swivel.model.matchers.ParameterMapMatcher;
import swivel.model.matchers.RemoteAddrMatcher;
import swivel.model.matchers.RequestMethodMatcher;
import swivel.model.matchers.RequestedURIPathMatcher;
import org.codehaus.jackson.map.ObjectMapper;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
import swivel.model.matchers.ContentTypeMatcher;
import swivel.model.matchers.HeaderMatcher;
import swivel.model.matchers.ParameterMapMatcher;
import swivel.model.matchers.RemoteAddrMatcher;
import swivel.model.matchers.RequestMethodMatcher;
import swivel.model.matchers.RequestedURIPathMatcher;
import swivel.model.matchers.ScriptMatcher;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static swivel.model.matchers.ContentMatcher.hasContent;
import static swivel.model.matchers.ScriptMatcher.scriptMatches;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
public class RequestMatcherBuilder {
public static final String METHOD_KEY = "method";
public static final String REMOTE_ADDR_KEY = "remoteAddr";
public static final String CONTENT_TYPE_KEY = "contentType";
public static final String CONTENT_KEY = "content";
public static final String SCRIPT_KEY = "when";
public static final int STATIC_MATCHER_COUNT = 3;
public static final int OPTIONAL_MATCHER_COUNT = 5;
protected ObjectMapper objectMapper = new ObjectMapper();
@SuppressWarnings("unchecked")
public Matcher<HttpServletRequest> buildMatcher(final HttpServletRequest expectationRequest)
throws IOException {
Map<String, Object> json = objectMapper.readValue(expectationRequest.getInputStream(), Map.class);
List<Matcher<HttpServletRequest>> matchers = new ArrayList<Matcher<HttpServletRequest>>(STATIC_MATCHER_COUNT);
matchers.add(RequestMethodMatcher.hasMethod(equalTo(json.get(METHOD_KEY))));
matchers.add(RequestedURIPathMatcher.hasURIPath(equalTo(expectationRequest.getPathInfo())));
matchers.add(buildOptionalMatcher(expectationRequest, json));
return allOf(matchers.toArray(new Matcher[matchers.size()]));
}
@SuppressWarnings("unchecked")
protected Matcher<HttpServletRequest> buildOptionalMatcher(HttpServletRequest expectationRequest,
Map<String, Object> json) {
try {
List<Matcher<HttpServletRequest>> result =
new ArrayList<Matcher<HttpServletRequest>>(OPTIONAL_MATCHER_COUNT);
Map<String, String[]> parameterMap = expectationRequest.getParameterMap();
if (!parameterMap.isEmpty()) {
result.add(ParameterMapMatcher.hasParameterMap(equalTo(convertParameterMap(parameterMap))));
}
if (json.containsKey(REMOTE_ADDR_KEY)) {
String remoteAddr = (String) json.get(REMOTE_ADDR_KEY);
result.add(CoreMatchers.anyOf(RemoteAddrMatcher.hasRemoteAddr(equalTo(remoteAddr)),
HeaderMatcher.hasHeader("X-Forwarded-For", hasItem(remoteAddr))));
}
if (json.containsKey(CONTENT_TYPE_KEY)) {
result.add(ContentTypeMatcher.hasContentType(equalTo(json.get(CONTENT_TYPE_KEY))));
}
if (json.containsKey(CONTENT_KEY)) {
result.add(hasContent(equalTo(json.get(CONTENT_KEY))));
}
if (json.containsKey(SCRIPT_KEY)) {
result.add(ScriptMatcher.scriptMatches((String) json.get(SCRIPT_KEY)));
}
return allOf(result.toArray(new Matcher[result.size()]));
} catch (ScriptException e) {
throw new RuntimeException(e);
}
}
private Map<String, List<String>> convertParameterMap(Map<String, String[]> parameterMap) {
Map<String, List<String>> result = new HashMap<String, List<String>>(parameterMap.size());
for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
result.put(stringEntry.getKey(), Arrays.asList(stringEntry.getValue()));
}
return result;
}
}
| Why did my static imports go away?
| swivel-server/src/main/java/swivel/model/RequestMatcherBuilder.java | Why did my static imports go away? | <ide><path>wivel-server/src/main/java/swivel/model/RequestMatcherBuilder.java
<ide> package swivel.model;
<ide>
<del>import swivel.model.matchers.ContentTypeMatcher;
<del>import swivel.model.matchers.HeaderMatcher;
<del>import swivel.model.matchers.ParameterMapMatcher;
<del>import swivel.model.matchers.RemoteAddrMatcher;
<del>import swivel.model.matchers.RequestMethodMatcher;
<del>import swivel.model.matchers.RequestedURIPathMatcher;
<ide> import org.codehaus.jackson.map.ObjectMapper;
<del>import org.hamcrest.CoreMatchers;
<ide> import org.hamcrest.Matcher;
<del>import swivel.model.matchers.ContentTypeMatcher;
<del>import swivel.model.matchers.HeaderMatcher;
<del>import swivel.model.matchers.ParameterMapMatcher;
<del>import swivel.model.matchers.RemoteAddrMatcher;
<del>import swivel.model.matchers.RequestMethodMatcher;
<del>import swivel.model.matchers.RequestedURIPathMatcher;
<del>import swivel.model.matchers.ScriptMatcher;
<ide>
<ide> import javax.script.ScriptException;
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<del>import static swivel.model.matchers.ContentMatcher.hasContent;
<del>import static swivel.model.matchers.ScriptMatcher.scriptMatches;
<ide> import static org.hamcrest.CoreMatchers.allOf;
<ide> import static org.hamcrest.CoreMatchers.anyOf;
<ide> import static org.hamcrest.CoreMatchers.equalTo;
<ide> import static org.hamcrest.CoreMatchers.hasItem;
<add>import static swivel.model.matchers.ContentMatcher.hasContent;
<add>import static swivel.model.matchers.ContentTypeMatcher.hasContentType;
<add>import static swivel.model.matchers.HeaderMatcher.hasHeader;
<add>import static swivel.model.matchers.ParameterMapMatcher.hasParameterMap;
<add>import static swivel.model.matchers.RemoteAddrMatcher.hasRemoteAddr;
<add>import static swivel.model.matchers.RequestMethodMatcher.hasMethod;
<add>import static swivel.model.matchers.RequestedURIPathMatcher.hasURIPath;
<add>import static swivel.model.matchers.ScriptMatcher.scriptMatches;
<ide>
<ide> public class RequestMatcherBuilder {
<ide> public static final String METHOD_KEY = "method";
<ide> Map<String, Object> json = objectMapper.readValue(expectationRequest.getInputStream(), Map.class);
<ide>
<ide> List<Matcher<HttpServletRequest>> matchers = new ArrayList<Matcher<HttpServletRequest>>(STATIC_MATCHER_COUNT);
<del> matchers.add(RequestMethodMatcher.hasMethod(equalTo(json.get(METHOD_KEY))));
<del> matchers.add(RequestedURIPathMatcher.hasURIPath(equalTo(expectationRequest.getPathInfo())));
<add> matchers.add(hasMethod(equalTo(json.get(METHOD_KEY))));
<add> matchers.add(hasURIPath(equalTo(expectationRequest.getPathInfo())));
<ide>
<ide> matchers.add(buildOptionalMatcher(expectationRequest, json));
<ide> return allOf(matchers.toArray(new Matcher[matchers.size()]));
<ide> new ArrayList<Matcher<HttpServletRequest>>(OPTIONAL_MATCHER_COUNT);
<ide> Map<String, String[]> parameterMap = expectationRequest.getParameterMap();
<ide> if (!parameterMap.isEmpty()) {
<del> result.add(ParameterMapMatcher.hasParameterMap(equalTo(convertParameterMap(parameterMap))));
<add> result.add(hasParameterMap(equalTo(convertParameterMap(parameterMap))));
<ide> }
<ide> if (json.containsKey(REMOTE_ADDR_KEY)) {
<ide> String remoteAddr = (String) json.get(REMOTE_ADDR_KEY);
<del> result.add(CoreMatchers.anyOf(RemoteAddrMatcher.hasRemoteAddr(equalTo(remoteAddr)),
<del> HeaderMatcher.hasHeader("X-Forwarded-For", hasItem(remoteAddr))));
<add> result.add(
<add> anyOf(hasRemoteAddr(equalTo(remoteAddr)), hasHeader("X-Forwarded-For", hasItem(remoteAddr))));
<ide> }
<ide> if (json.containsKey(CONTENT_TYPE_KEY)) {
<del> result.add(ContentTypeMatcher.hasContentType(equalTo(json.get(CONTENT_TYPE_KEY))));
<add> result.add(hasContentType(equalTo(json.get(CONTENT_TYPE_KEY))));
<ide> }
<ide> if (json.containsKey(CONTENT_KEY)) {
<ide> result.add(hasContent(equalTo(json.get(CONTENT_KEY))));
<ide> }
<ide> if (json.containsKey(SCRIPT_KEY)) {
<del> result.add(ScriptMatcher.scriptMatches((String) json.get(SCRIPT_KEY)));
<add> result.add(scriptMatches((String) json.get(SCRIPT_KEY)));
<ide> }
<ide> return allOf(result.toArray(new Matcher[result.size()]));
<ide> } catch (ScriptException e) { |
|
Java | mit | 5bbf7ef4330e8afa4830d159d0b59cf376ba5077 | 0 | noveogroup/android-logger | /*
* Copyright (c) 2013 Noveo Group
*
* 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.
*
* Except as contained in this notice, the name(s) of the above copyright holders
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization.
*
* 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.noveogroup.android.log;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Formatter;
/**
* The basic implementation of {@link Handler} interface.
* <p/>
* This log handler is configured with a logging level, a tag and
* a message patterns.
* <p/>
* The logging level parameter is the minimal level of log messages printed
* by this handler instance. The logging level can be {@code null} which
* means no messages should be printed using this logger.
* <p/>
* <b>Attention</b>: Android may set its own requirement for logging level
* using {@link Log#isLoggable(String, int)} method. This logger doesn't take
* it into account in {@link #isEnabled(Logger.Level)} method.
* <p/>
* The patterns are format strings written according to a special rules described
* below. Log messages will be formatted and printed as it is specified in
* the tag and the message pattern. The tag pattern configures log tag used
* to print messages. The message pattern configures a head of the message but
* not whole message printed to log.
* <p/>
* <table border=1>
* <tr>
* <th>The tag pattern</th>
* <td>TAG</td>
* </tr>
* <tr>
* <th>The message pattern</th>
* <td>%d{yyyy-MM-dd}: </td>
* </tr>
* <tr>
* <th>Resulting tag</th>
* <td>TAG</td>
* </tr>
* <tr>
* <th>Resulting message</th>
* <td>2013-07-12: <incoming message></td>
* </tr>
* </table>
* <p/>
* The tag and the message patterns are wrote according to similar rules.
* So we will show only one pattern in further examples.
* <p/>
* The patterns is strings that contains a set of placeholders and other
* special marks. Each special mark should start with '%' sign. To escape
* this sign you can double it.
* <p/>
* The list of special marks and placeholders:
* <table border=1>
* <caption>Conversion marks</caption>
* <tr>
* <th>Mark</th><th>Effect</th>
* </tr>
* <tr>
* <td>%%</td>
* <td>Escapes special sign. Prints just one '%' instead.</td>
* </tr>
* <tr>
* <td>%n</td>
* <td>Prints a new line character '\n'.</td>
* </tr>
* <tr>
* <td>%d{date format} %date{date format}</td>
* <td>Prints date/time of a message. Date format
* should be supported by {@link SimpleDateFormat}.
* Default date format is "yyyy-MM-dd HH:mm:ss.SSS".</td>
* </tr>
* <tr>
* <td>%p %level</td>
* <td>Prints logging level of a message.</td>
* </tr>
* <tr>
* <td>%c{count.length} %logger{count.length}</td>
* <td>Prints a name of the logger. The algorithm will shorten some part of
* full logger name to the specified length. You can find examples below.
* <table border=1>
* <tr>
* <th>Conversion specifier</th>
* <th>Logger name</th>
* <th>Result</th>
* </tr>
* <tr>
* <td>%logger</td>
* <td>com.example.android.MainActivity</td>
* <td>com.example.android.MainActivity</td>
* </tr>
* <tr>
* <td>%logger{2}</td>
* <td>com.example.android.MainActivity</td>
* <td>com.example</td>
* </tr>
* <tr>
* <td>%logger{-2}</td>
* <td>com.example.android.MainActivity</td>
* <td>android.MainActivity</td>
* </tr>
* <tr>
* <td>%logger{.30}</td>
* <td>com.example.android.MainActivity</td>
* <td>*.example.android.MainActivity</td>
* </tr>
* <tr>
* <td>%logger{.15}</td>
* <td>com.example.android.MainActivity</td>
* <td>*.MainActivity</td>
* </tr>
* <tr>
* <td>%logger{3.18}</td>
* <td>com.example.android.MainActivity</td>
* <td>*.example.android</td>
* </tr>
* <tr>
* <td>%logger{-3.10}</td>
* <td>com.example.android.MainActivity$SubClass</td>
* <td>MainActivity$SubClass</td>
* </tr>
* </table>
* </td>
* </tr>
* <tr>
* <td>%C{count.length} %caller{count.length}</td>
* <td>Prints information about a caller class which causes the logging event.
* Additional parameters 'count' and 'length' means the same as
* the parameters of %logger. Examples:
* <table border=1>
* <tr>
* <th>Conversion specifier</th>
* <th>Caller</th>
* <th>Result</th>
* </tr>
* <tr>
* <td>%caller</td>
* <td>Class com.example.android.MainActivity at line 154</td>
* <td>com.example.android.MainActivity:154</td>
* </tr>
* <tr>
* <td>%caller{-3.15}</td>
* <td>Class com.example.android.MainActivity at line 154</td>
* <td>MainActivity:154</td>
* </tr>
* </table>
* </td>
* </tr>
* <tr>
* <td>%(...)</td>
* <td>Special mark used to grouping parts of message. Format modifiers
* (if specified) are applied on whole group. Examples:
* <table border=1>
* <tr>
* <th>Example</th>
* <th>Result</th>
* </tr>
* <tr>
* <td>[%50(%d %caller{-3.15})]</td>
* <td><pre>[ 2013-07-12 19:45:26.315 MainActivity:154]</pre></td>
* </tr>
* <tr>
* <td>[%-50(%d %caller{-3.15})]</td>
* <td><pre>[2013-07-12 19:45:26.315 MainActivity:154 ]</pre></td>
* </tr>
* </table>
* </td>
* </tr>
* </table>
* <p/>
* After special sign '%' user can add format modifiers. The modifiers
* is similar to standard modifiers of {@link Formatter} conversions.
* <table border=1>
* <tr>
* <th>Example</th>
* <th>Result</th>
* </tr>
* <tr> <td>%6(text)</td> <td><pre>' text'</pre></td> </tr>
* <tr> <td>%-6(text)</td> <td><pre>'text '</pre></td> </tr>
* <tr> <td>%.3(text)</td> <td><pre>'tex'</pre></td> </tr>
* <tr> <td>%.-3(text)</td> <td><pre>'ext'</pre></td> </tr>
* </table>
*/
public class PatternHandler implements Handler {
private final Logger.Level level;
private final String tagPattern;
private final String messagePattern;
/**
* Creates new {@link PatternHandler}.
*
* @param level the level.
* @param tagPattern the tag pattern.
* @param messagePattern the message pattern.
*/
public PatternHandler(Logger.Level level, String tagPattern, String messagePattern) {
this.level = level;
this.tagPattern = tagPattern;
this.messagePattern = messagePattern;
}
/**
* Returns the level.
*
* @return the level.
*/
public Logger.Level getLevel() {
return level;
}
/**
* Returns the tag messagePattern.
*
* @return the tag messagePattern.
*/
public String getTagPattern() {
return tagPattern;
}
/**
* Returns the message messagePattern.
*
* @return the message messagePattern.
*/
public String getMessagePattern() {
return messagePattern;
}
@Override
public boolean isEnabled(Logger.Level level) {
return this.level != null && level != null && this.level.includes(level);
}
@Override
public void print(String loggerName, Logger.Level level,
Throwable throwable, String messageFormat, Object... args) throws IllegalArgumentException {
if (isEnabled(level)) {
String message;
if (messageFormat == null) {
if (args != null && args.length > 0) {
throw new IllegalArgumentException("message format is not set but arguments are presented");
}
if (throwable == null) {
message = "";
} else {
message = Log.getStackTraceString(throwable);
}
} else {
if (throwable == null) {
message = String.format(messageFormat, args);
} else {
message = String.format(messageFormat, args) + '\n' + Log.getStackTraceString(throwable);
}
}
// todo implement it
Log.println(level.intValue(),
(tagPattern == null ? "" : tagPattern),
(messagePattern == null ? "" : messagePattern) + message);
}
}
}
| src/main/java/com/noveogroup/android/log/PatternHandler.java | /*
* Copyright (c) 2013 Noveo Group
*
* 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.
*
* Except as contained in this notice, the name(s) of the above copyright holders
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization.
*
* 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.noveogroup.android.log;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Formatter;
/**
* The basic implementation of {@link Handler} interface.
* <p/>
* This log handler is configured with a logging level, a tag and
* a message patterns.
* <p/>
* The logging level parameter is the minimal level of log messages printed
* by this handler instance. The logging level can be {@code null} which
* means no messages should be printed using this logger.
* <p/>
* <b>Attention</b>: Android may set its own requirement for logging level
* using {@link Log#isLoggable(String, int)} method. This logger doesn't take
* it into account in {@link #isEnabled(Logger.Level)} method.
* <p/>
* The patterns are format strings written according to a special rules described
* below. Log messages will be formatted and printed as it is specified in
* the tag and the message pattern. The tag pattern configures log tag used
* to print messages. The message pattern configures a head of the message but
* not whole message printed to log.
* <p/>
* <table border=1>
* <tr>
* <th>The tag pattern</th>
* <td>TAG</td>
* </tr>
* <tr>
* <th>The message pattern</th>
* <td>%d{yyyy-MM-dd}: </td>
* </tr>
* <tr>
* <th>Resulting tag</th>
* <td>TAG</td>
* </tr>
* <tr>
* <th>Resulting message</th>
* <td>2013-07-12: <incoming message></td>
* </tr>
* </table>
* <p/>
* The tag and the message patterns are wrote according to similar rules.
* So we will show only one pattern in further examples.
* <p/>
* The patterns is strings that contains a set of placeholders and other
* special marks. Each special mark should start with '%' sign. To escape
* this sign you can double it.
* <p/>
* The list of special marks and placeholders:
* <table border=1>
* <caption>Conversion marks</caption>
* <tr>
* <th>Mark</th><th>Effect</th>
* </tr>
* <tr>
* <td>%%</td>
* <td>Escapes special sign. Prints just one '%' instead.</td>
* </tr>
* <tr>
* <td>%n</td>
* <td>Prints a new line character '\n'.</td>
* </tr>
* <tr>
* <td>%d{date format} %date{date format}</td>
* <td>Prints date/time of a message. Date format
* should be supported by {@link SimpleDateFormat}.
* Default date format is "yyyy-MM-dd HH:mm:ss.SSS".</td>
* </tr>
* <tr>
* <td>%p %level</td>
* <td>Prints logging level of a message.</td>
* </tr>
* <tr>
* <td>%c{count.length} %logger{count.length}</td>
* <td>Prints a name of the logger. The algorithm will shorten some part of
* full logger name to the specified length. You can find examples below.
* <table border=1>
* <tr>
* <th>Conversion specifier</th>
* <th>Logger name</th>
* <th>Result</th>
* </tr>
* <tr>
* <td>%logger</td>
* <td>com.example.android.MainActivity</td>
* <td>com.example.android.MainActivity</td>
* </tr>
* <tr>
* <td>%logger{2}</td>
* <td>com.example.android.MainActivity</td>
* <td>com.example</td>
* </tr>
* <tr>
* <td>%logger{-2}</td>
* <td>com.example.android.MainActivity</td>
* <td>android.MainActivity</td>
* </tr>
* <tr>
* <td>%logger{.30}</td>
* <td>com.example.android.MainActivity</td>
* <td>*.example.android.MainActivity</td>
* </tr>
* <tr>
* <td>%logger{.15}</td>
* <td>com.example.android.MainActivity</td>
* <td>*.MainActivity</td>
* </tr>
* <tr>
* <td>%logger{3.18}</td>
* <td>com.example.android.MainActivity</td>
* <td>*.example.android</td>
* </tr>
* <tr>
* <td>%logger{-3.10}</td>
* <td>com.example.android.MainActivity$SubClass</td>
* <td>MainActivity$SubClass</td>
* </tr>
* </table>
* </td>
* </tr>
* <tr>
* <td>%C{count.length} %caller{count.length}</td>
* <td>Prints information about a caller class which causes the logging event.
* Additional parameters 'count' and 'length' means the same as
* the parameters of %logger. Examples:
* <table border=1>
* <tr>
* <th>Conversion specifier</th>
* <th>Caller</th>
* <th>Result</th>
* </tr>
* <tr>
* <td>%caller</td>
* <td>Class com.example.android.MainActivity at line 154</td>
* <td>com.example.android.MainActivity:154</td>
* </tr>
* <tr>
* <td>%caller{-3.15}</td>
* <td>Class com.example.android.MainActivity at line 154</td>
* <td>MainActivity:154</td>
* </tr>
* </table>
* </td>
* </tr>
* <tr>
* <td>%(...)</td>
* <td>Special mark used to grouping parts of message. Format modifiers
* (if specified) are applied on whole group. Examples:
* <table border=1>
* <tr>
* <th>Example</th>
* <th>Result</th>
* </tr>
* <tr>
* <td>[%50(%d %caller{-3.15})]</td>
* <td><pre>[ 2013-07-12 19:45:26.315 MainActivity:154]</pre></td>
* </tr>
* <tr>
* <td>[%-50(%d %caller{-3.15})]</td>
* <td><pre>[2013-07-12 19:45:26.315 MainActivity:154 ]</pre></td>
* </tr>
* </table>
* </td>
* </tr>
* </table>
* <p/>
* After special sign '%' user can add format modifiers. The modifiers
* is similar to standard modifiers of {@link Formatter} conversions.
* <table border=1>
* <tr>
* <th>Example</th>
* <th>Result</th>
* </tr>
* <tr> <td>%6(text)</td> <td><pre>' text'</pre></td> </tr>
* <tr> <td>%-6(text)</td> <td><pre>'text '</pre></td> </tr>
* <tr> <td>%.3(text)</td> <td><pre>'tex'</pre></td> </tr>
* <tr> <td>%.-3(text)</td> <td><pre>'ext'</pre></td> </tr>
* </table>
*/
public class PatternHandler implements Handler {
private final Logger.Level level;
private final String tagPattern;
private final String messagePattern;
/**
* Creates new {@link PatternHandler}.
*
* @param level the level.
* @param tagPattern the tag pattern.
* @param messagePattern the message pattern.
*/
public PatternHandler(Logger.Level level, String tagPattern, String messagePattern) {
this.level = level;
this.tagPattern = tagPattern;
this.messagePattern = messagePattern;
}
/**
* Returns the level.
*
* @return the level.
*/
public Logger.Level getLevel() {
return level;
}
/**
* Returns the tag messagePattern.
*
* @return the tag messagePattern.
*/
public String getTagPattern() {
return tagPattern;
}
/**
* Returns the message messagePattern.
*
* @return the message messagePattern.
*/
public String getMessagePattern() {
return messagePattern;
}
@Override
public boolean isEnabled(Logger.Level level) {
return this.level != null && level != null && this.level.includes(level);
}
@Override
public void print(String loggerName, Logger.Level level,
Throwable throwable, String messageFormat, Object... args) throws IllegalArgumentException {
if (isEnabled(level)) {
String message;
if (messageFormat == null) {
if (args != null && args.length > 0) {
throw new IllegalArgumentException("message format is not set but arguments are presented");
}
if (throwable == null) {
message = "";
} else {
message = Log.getStackTraceString(throwable);
}
} else {
if (throwable == null) {
message = String.format(messageFormat, args);
} else {
message = String.format(messageFormat, args) + '\n' + Log.getStackTraceString(throwable);
}
}
// todo implement it
Log.println(level.intValue(), tagPattern, messagePattern + message);
}
}
}
| fix draft of PatternHandler
| src/main/java/com/noveogroup/android/log/PatternHandler.java | fix draft of PatternHandler | <ide><path>rc/main/java/com/noveogroup/android/log/PatternHandler.java
<ide> }
<ide>
<ide> // todo implement it
<del> Log.println(level.intValue(), tagPattern, messagePattern + message);
<add> Log.println(level.intValue(),
<add> (tagPattern == null ? "" : tagPattern),
<add> (messagePattern == null ? "" : messagePattern) + message);
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | cd3dd4cb3a6a9c2ffec70c6459a9cde5e3e5dcb2 | 0 | opentable/rbush,landonb/rbush,mourner/rbush,mourner/rbush,josl/rbush,landonb/rbush,korczis/rbush,josl/rbush,MazeMap/rbush,korczis/rbush,opentable/rbush,MazeMap/rbush | var rbush = require('../rbush.js'),
assert = require('assert');
describe('rbush', function () { 'use strict';
function assertSortedEqual(a, b, compare) {
assert.deepEqual(a.sort(compare), b.sort(compare));
}
var data = [[0,0,0,0],[10,10,10,10],[20,20,20,20],[25,0,25,0],[35,10,35,10],[45,20,45,20],[0,25,0,25],[10,35,10,35],
[20,45,20,45],[25,25,25,25],[35,35,35,35],[45,45,45,45],[50,0,50,0],[60,10,60,10],[70,20,70,20],[75,0,75,0],
[85,10,85,10],[95,20,95,20],[50,25,50,25],[60,35,60,35],[70,45,70,45],[75,25,75,25],[85,35,85,35],[95,45,95,45],
[0,50,0,50],[10,60,10,60],[20,70,20,70],[25,50,25,50],[35,60,35,60],[45,70,45,70],[0,75,0,75],[10,85,10,85],
[20,95,20,95],[25,75,25,75],[35,85,35,85],[45,95,45,95],[50,50,50,50],[60,60,60,60],[70,70,70,70],[75,50,75,50],
[85,60,85,60],[95,70,95,70],[50,75,50,75],[60,85,60,85],[70,95,70,95],[75,75,75,75],[85,85,85,85],[95,95,95,95]];
var testTree = {'children':[{
'children':[
{'children':[[0,0,0,0],[10,10,10,10],[20,20,20,20],[25,0,25,0]], 'leaf':true,'bbox':[0,0,25,20], 'height': 1},
{'children':[[35,10,35,10],[45,20,45,20],[50,0,50,0],[60,10,60,10]], 'leaf':true,'bbox':[35,0,60,20], 'height': 1},
{'children':[[0,25,0,25],[10,35,10,35],[20,45,20,45],[25,25,25,25]], 'leaf':true,'bbox':[0,25,25,45], 'height': 1},
{'children':[[35,35,35,35],[45,45,45,45],[50,25,50,25],[60,35,60,35]],'leaf':true,'bbox':[35,25,60,45],'height': 1}
], 'bbox':[0,0,60,45], 'height': 2
}, {
'children': [
{'children':[[0,50,0,50],[10,60,10,60],[20,70,20,70],[25,50,25,50]], 'leaf':true,'bbox':[0,50,25,70], 'height': 1},
{'children':[[35,60,35,60],[45,70,45,70],[50,50,50,50],[60,60,60,60]],'leaf':true,'bbox':[35,50,60,70],'height': 1},
{'children':[[0,75,0,75],[10,85,10,85],[20,95,20,95],[25,75,25,75]], 'leaf':true,'bbox':[0,75,25,95], 'height': 1},
{'children':[[35,85,35,85],[45,95,45,95],[50,75,50,75],[60,85,60,85]],'leaf':true,'bbox':[35,75,60,95],'height': 1}
], 'bbox':[0,50,60,95], 'height': 2
}, {
'children': [
{'children':[[70,20,70,20],[70,45,70,45],[75,0,75,0],[75,25,75,25]], 'leaf':true,'bbox':[70,0,75,45], 'height': 1},
{'children':[[85,10,85,10],[85,35,85,35],[95,20,95,20],[95,45,95,45]],'leaf':true,'bbox':[85,10,95,45],'height': 1},
{'children':[[70,70,70,70],[70,95,70,95],[75,50,75,50],[75,75,75,75]],'leaf':true,'bbox':[70,50,75,95],'height': 1},
{'children':[[85,60,85,60],[85,85,85,85],[95,70,95,70],[95,95,95,95]],'leaf':true,'bbox':[85,60,95,95],'height': 1}
], 'bbox':[70,0,95,95], 'height': 2
}], 'bbox':[0,0,95,95], 'height': 3};
describe('constructor', function () {
it('accepts a format argument to customize the data format', function () {
var tree = rbush(4, ['.minLng', '.minLat', '.maxLng', '.maxLat']);
assert.deepEqual(tree.toBBox({minLng: 1, minLat: 2, maxLng: 3, maxLat: 4}), [1, 2, 3, 4]);
});
});
describe('toBBox, compareMinX, compareMinY', function () {
it('can be overriden to allow custom data structures', function () {
var tree = rbush(4);
tree.toBBox = function (item) {
return [item.minLng, item.minLat, item.maxLng, item.maxLat];
};
tree.compareMinX = function (a, b) {
return a.minLng - b.minLng;
};
tree.compareMinY = function (a, b) {
return a.minLat - b.minLat;
};
var data = [
{minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
{minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
{minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
{minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
];
tree.load(data);
function byLngLat (a, b) {
return a.minLng - b.minLng || a.minLat - b.minLat;
}
assertSortedEqual(tree.search([-180, -90, 180, 90]), [
{minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
{minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
{minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
{minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
], byLngLat);
assertSortedEqual(tree.search([-180, -90, 0, 90]), [
{minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
{minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
], byLngLat);
assertSortedEqual(tree.search([0, -90, 180, 90]), [
{minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
{minLng: 105, minLat: -55, maxLng: 115, maxLat: -45}
], byLngLat);
assertSortedEqual(tree.search([-180, 0, 180, 90]), [
{minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
{minLng: 105, minLat: 45, maxLng: 115, maxLat: 55}
], byLngLat);
assertSortedEqual(tree.search([-180, -90, 180, 0]), [
{minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
{minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
], byLngLat);
});
});
describe('load', function () {
it('bulk-loads the given data given max node entries and forms a proper search tree', function () {
var tree = rbush(4).load(data);
assert.deepEqual(tree.toJSON(), testTree);
});
it('uses standard insertion when given a low number of items', function () {
var tree = rbush(8)
.load(data)
.load(data.slice(0, 3));
var tree2 = rbush(8)
.load(data)
.insert(data[0])
.insert(data[1])
.insert(data[2]);
assert.deepEqual(tree.toJSON(), tree2.toJSON());
});
});
describe('search', function () {
it('finds matching points in the tree given a bbox', function () {
var tree = rbush(4).load(data);
var result = tree.search([40, 20, 80, 70]);
assertSortedEqual(result, [
[70,20,70,20],[75,25,75,25],[45,45,45,45],[50,50,50,50],[60,60,60,60],[70,70,70,70],
[45,20,45,20],[45,70,45,70],[75,50,75,50],[50,25,50,25],[60,35,60,35],[70,45,70,45]
]);
});
});
describe('all', function() {
it('returns all points in the tree', function() {
var tree = rbush(4).load(data);
var result = tree.all();
assertSortedEqual(result, data);
});
});
describe('toJSON & fromJSON', function () {
it('exports and imports search tree in JSON format', function () {
var tree = rbush(4);
tree.fromJSON(testTree);
var tree2 = rbush(4).load(data);
assert.deepEqual(tree.toJSON(), tree2.toJSON());
});
});
describe('insert', function () {
it('adds an item to an existing tree correctly', function () {
var tree = rbush(4).load([
[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2]
]);
tree.insert([3, 3, 3, 3]);
assert.deepEqual(tree.toJSON(), {
'children':[[0,0,0,0],[1,1,1,1],[2,2,2,2],[3,3,3,3]],
'leaf':true,
'height':1,
'bbox':[0,0,3,3]
});
tree.insert([1, 1, 2, 2]);
assert.deepEqual(tree.toJSON(), {
'children':[
{'children':[[0,0,0,0],[1,1,1,1]],'leaf':true,'height':1,'bbox':[0,0,1,1]},
{'children':[[1,1,2,2],[2,2,2,2],[3,3,3,3]],'height':1,'leaf':true,'bbox':[1,1,3,3]}
],
'height':2,
'bbox':[0,0,3,3]
});
});
});
});
| test/test.js | var rbush = require('../rbush.js'),
assert = require('assert');
describe('rbush', function () { 'use strict';
var data = [[0,0,0,0],[10,10,10,10],[20,20,20,20],[25,0,25,0],[35,10,35,10],[45,20,45,20],[0,25,0,25],[10,35,10,35],
[20,45,20,45],[25,25,25,25],[35,35,35,35],[45,45,45,45],[50,0,50,0],[60,10,60,10],[70,20,70,20],[75,0,75,0],
[85,10,85,10],[95,20,95,20],[50,25,50,25],[60,35,60,35],[70,45,70,45],[75,25,75,25],[85,35,85,35],[95,45,95,45],
[0,50,0,50],[10,60,10,60],[20,70,20,70],[25,50,25,50],[35,60,35,60],[45,70,45,70],[0,75,0,75],[10,85,10,85],
[20,95,20,95],[25,75,25,75],[35,85,35,85],[45,95,45,95],[50,50,50,50],[60,60,60,60],[70,70,70,70],[75,50,75,50],
[85,60,85,60],[95,70,95,70],[50,75,50,75],[60,85,60,85],[70,95,70,95],[75,75,75,75],[85,85,85,85],[95,95,95,95]];
var testTree = {'children':[{
'children':[
{'children':[[0,0,0,0],[10,10,10,10],[20,20,20,20],[25,0,25,0]], 'leaf':true,'bbox':[0,0,25,20], 'height': 1},
{'children':[[35,10,35,10],[45,20,45,20],[50,0,50,0],[60,10,60,10]], 'leaf':true,'bbox':[35,0,60,20], 'height': 1},
{'children':[[0,25,0,25],[10,35,10,35],[20,45,20,45],[25,25,25,25]], 'leaf':true,'bbox':[0,25,25,45], 'height': 1},
{'children':[[35,35,35,35],[45,45,45,45],[50,25,50,25],[60,35,60,35]],'leaf':true,'bbox':[35,25,60,45],'height': 1}
], 'bbox':[0,0,60,45], 'height': 2
}, {
'children': [
{'children':[[0,50,0,50],[10,60,10,60],[20,70,20,70],[25,50,25,50]], 'leaf':true,'bbox':[0,50,25,70], 'height': 1},
{'children':[[35,60,35,60],[45,70,45,70],[50,50,50,50],[60,60,60,60]],'leaf':true,'bbox':[35,50,60,70],'height': 1},
{'children':[[0,75,0,75],[10,85,10,85],[20,95,20,95],[25,75,25,75]], 'leaf':true,'bbox':[0,75,25,95], 'height': 1},
{'children':[[35,85,35,85],[45,95,45,95],[50,75,50,75],[60,85,60,85]],'leaf':true,'bbox':[35,75,60,95],'height': 1}
], 'bbox':[0,50,60,95], 'height': 2
}, {
'children': [
{'children':[[70,20,70,20],[70,45,70,45],[75,0,75,0],[75,25,75,25]], 'leaf':true,'bbox':[70,0,75,45], 'height': 1},
{'children':[[85,10,85,10],[85,35,85,35],[95,20,95,20],[95,45,95,45]],'leaf':true,'bbox':[85,10,95,45],'height': 1},
{'children':[[70,70,70,70],[70,95,70,95],[75,50,75,50],[75,75,75,75]],'leaf':true,'bbox':[70,50,75,95],'height': 1},
{'children':[[85,60,85,60],[85,85,85,85],[95,70,95,70],[95,95,95,95]],'leaf':true,'bbox':[85,60,95,95],'height': 1}
], 'bbox':[70,0,95,95], 'height': 2
}], 'bbox':[0,0,95,95], 'height': 3};
describe('constructor', function () {
it('accepts a format argument to customize the data format', function () {
var tree = rbush(4, ['.minLng', '.minLat', '.maxLng', '.maxLat']);
assert.deepEqual(tree.toBBox({minLng: 1, minLat: 2, maxLng: 3, maxLat: 4}), [1, 2, 3, 4]);
});
});
describe('override toBBox, compareMinX, compareMinY', function () {
it('allows custom data structures to be transformed', function () {
var tree = rbush(4);
tree.toBBox = function (item) {
return [item.minLng, item.minLat, item.maxLng, item.maxLat];
};
tree.compareMinX = function (a, b) {
return a.minLng - b.minLng;
};
tree.compareMinY = function (a, b) {
return a.minLat - b.minLat;
};
var data = [
{minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
{minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
{minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
{minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
];
tree.load(data);
function byLngLat (a, b) {
return a.minLng - b.minLng || a.minLat - b.minLat;
}
assert.deepEqual(tree.search([-180, -90, 180, 90]).sort(byLngLat), [
{minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
{minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
{minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
{minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
].sort(byLngLat));
assert.deepEqual(tree.search([-180, -90, 0, 90]).sort(byLngLat), [
{minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
{minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
].sort(byLngLat));
assert.deepEqual(tree.search([0, -90, 180, 90]).sort(byLngLat), [
{minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
{minLng: 105, minLat: -55, maxLng: 115, maxLat: -45}
].sort(byLngLat));
assert.deepEqual(tree.search([-180, 0, 180, 90]).sort(byLngLat), [
{minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
{minLng: 105, minLat: 45, maxLng: 115, maxLat: 55}
].sort(byLngLat));
assert.deepEqual(tree.search([-180, -90, 180, 0]).sort(byLngLat), [
{minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
{minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
].sort(byLngLat));
});
});
describe('load', function () {
it('bulk-loads the given data given max node entries and forms a proper search tree', function () {
var tree = rbush(4).load(data);
assert.deepEqual(tree.toJSON(), testTree);
});
});
describe('search', function () {
it('finds matching points in the tree given a bbox', function () {
var tree = rbush(4).load(data);
var result = tree.search([40, 20, 80, 70]);
assert.deepEqual(result.sort(), [
[70,20,70,20],[75,25,75,25],[45,45,45,45],[50,50,50,50],[60,60,60,60],[70,70,70,70],
[45,20,45,20],[45,70,45,70],[75,50,75,50],[50,25,50,25],[60,35,60,35],[70,45,70,45]
].sort());
});
});
describe('all', function() {
it('returns all points in the tree', function() {
var tree = rbush(4).load(data);
var result = tree.all();
assert.deepEqual(result.sort(), data.sort());
});
});
describe('toJSON & fromJSON', function () {
it('exports and imports search tree in JSON format', function () {
var tree = rbush(4);
tree.fromJSON(testTree);
var tree2 = rbush(4).load(data);
assert.deepEqual(tree.toJSON(), tree2.toJSON());
});
});
describe('addOne', function () {
it('adds an item to an existing tree');
});
});
| better test coverage #6
| test/test.js | better test coverage #6 | <ide><path>est/test.js
<ide> assert = require('assert');
<ide>
<ide> describe('rbush', function () { 'use strict';
<add>
<add> function assertSortedEqual(a, b, compare) {
<add> assert.deepEqual(a.sort(compare), b.sort(compare));
<add> }
<ide>
<ide> var data = [[0,0,0,0],[10,10,10,10],[20,20,20,20],[25,0,25,0],[35,10,35,10],[45,20,45,20],[0,25,0,25],[10,35,10,35],
<ide> [20,45,20,45],[25,25,25,25],[35,35,35,35],[45,45,45,45],[50,0,50,0],[60,10,60,10],[70,20,70,20],[75,0,75,0],
<ide> ], 'bbox':[70,0,95,95], 'height': 2
<ide> }], 'bbox':[0,0,95,95], 'height': 3};
<ide>
<add>
<ide> describe('constructor', function () {
<ide> it('accepts a format argument to customize the data format', function () {
<ide>
<ide> });
<ide> });
<ide>
<del> describe('override toBBox, compareMinX, compareMinY', function () {
<del> it('allows custom data structures to be transformed', function () {
<add> describe('toBBox, compareMinX, compareMinY', function () {
<add> it('can be overriden to allow custom data structures', function () {
<ide>
<ide> var tree = rbush(4);
<ide> tree.toBBox = function (item) {
<ide> };
<ide>
<ide> var data = [
<del> {minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
<del> {minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
<del> {minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
<add> {minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
<add> {minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
<add> {minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
<ide> {minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
<ide> ];
<ide>
<ide> return a.minLng - b.minLng || a.minLat - b.minLat;
<ide> }
<ide>
<del> assert.deepEqual(tree.search([-180, -90, 180, 90]).sort(byLngLat), [
<add> assertSortedEqual(tree.search([-180, -90, 180, 90]), [
<add> {minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
<add> {minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
<add> {minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
<add> {minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
<add> ], byLngLat);
<add>
<add> assertSortedEqual(tree.search([-180, -90, 0, 90]), [
<add> {minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
<add> {minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
<add> ], byLngLat);
<add>
<add> assertSortedEqual(tree.search([0, -90, 180, 90]), [
<add> {minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
<add> {minLng: 105, minLat: -55, maxLng: 115, maxLat: -45}
<add> ], byLngLat);
<add>
<add> assertSortedEqual(tree.search([-180, 0, 180, 90]), [
<ide> {minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
<del> {minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
<del> {minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
<add> {minLng: 105, minLat: 45, maxLng: 115, maxLat: 55}
<add> ], byLngLat);
<add>
<add> assertSortedEqual(tree.search([-180, -90, 180, 0]), [
<add> {minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
<ide> {minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
<del> ].sort(byLngLat));
<del>
<del> assert.deepEqual(tree.search([-180, -90, 0, 90]).sort(byLngLat), [
<del> {minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
<del> {minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
<del> ].sort(byLngLat));
<del>
<del> assert.deepEqual(tree.search([0, -90, 180, 90]).sort(byLngLat), [
<del> {minLng: 105, minLat: 45, maxLng: 115, maxLat: 55},
<del> {minLng: 105, minLat: -55, maxLng: 115, maxLat: -45}
<del> ].sort(byLngLat));
<del>
<del> assert.deepEqual(tree.search([-180, 0, 180, 90]).sort(byLngLat), [
<del> {minLng: -115, minLat: 45, maxLng: -105, maxLat: 55},
<del> {minLng: 105, minLat: 45, maxLng: 115, maxLat: 55}
<del> ].sort(byLngLat));
<del>
<del> assert.deepEqual(tree.search([-180, -90, 180, 0]).sort(byLngLat), [
<del> {minLng: 105, minLat: -55, maxLng: 115, maxLat: -45},
<del> {minLng: -115, minLat: -55, maxLng: -105, maxLat: -45}
<del> ].sort(byLngLat));
<add> ], byLngLat);
<ide>
<ide> });
<ide> });
<ide> var tree = rbush(4).load(data);
<ide> assert.deepEqual(tree.toJSON(), testTree);
<ide> });
<add> it('uses standard insertion when given a low number of items', function () {
<add>
<add> var tree = rbush(8)
<add> .load(data)
<add> .load(data.slice(0, 3));
<add>
<add> var tree2 = rbush(8)
<add> .load(data)
<add> .insert(data[0])
<add> .insert(data[1])
<add> .insert(data[2]);
<add>
<add> assert.deepEqual(tree.toJSON(), tree2.toJSON());
<add> });
<ide> });
<ide>
<ide> describe('search', function () {
<ide> var tree = rbush(4).load(data);
<ide> var result = tree.search([40, 20, 80, 70]);
<ide>
<del> assert.deepEqual(result.sort(), [
<add> assertSortedEqual(result, [
<ide> [70,20,70,20],[75,25,75,25],[45,45,45,45],[50,50,50,50],[60,60,60,60],[70,70,70,70],
<ide> [45,20,45,20],[45,70,45,70],[75,50,75,50],[50,25,50,25],[60,35,60,35],[70,45,70,45]
<del> ].sort());
<add> ]);
<ide> });
<ide> });
<ide>
<ide> var tree = rbush(4).load(data);
<ide> var result = tree.all();
<ide>
<del> assert.deepEqual(result.sort(), data.sort());
<add> assertSortedEqual(result, data);
<ide> });
<ide> });
<ide>
<ide> });
<ide> });
<ide>
<del> describe('addOne', function () {
<del> it('adds an item to an existing tree');
<add> describe('insert', function () {
<add> it('adds an item to an existing tree correctly', function () {
<add> var tree = rbush(4).load([
<add> [0, 0, 0, 0],
<add> [1, 1, 1, 1],
<add> [2, 2, 2, 2]
<add> ]);
<add> tree.insert([3, 3, 3, 3]);
<add>
<add> assert.deepEqual(tree.toJSON(), {
<add> 'children':[[0,0,0,0],[1,1,1,1],[2,2,2,2],[3,3,3,3]],
<add> 'leaf':true,
<add> 'height':1,
<add> 'bbox':[0,0,3,3]
<add> });
<add>
<add> tree.insert([1, 1, 2, 2]);
<add>
<add> assert.deepEqual(tree.toJSON(), {
<add> 'children':[
<add> {'children':[[0,0,0,0],[1,1,1,1]],'leaf':true,'height':1,'bbox':[0,0,1,1]},
<add> {'children':[[1,1,2,2],[2,2,2,2],[3,3,3,3]],'height':1,'leaf':true,'bbox':[1,1,3,3]}
<add> ],
<add> 'height':2,
<add> 'bbox':[0,0,3,3]
<add> });
<add> });
<ide> });
<ide> }); |
|
Java | apache-2.0 | error: pathspec 'litho-widget/src/main/java/com/facebook/litho/widget/EmptyComponentSpec.java' did not match any file(s) known to git
| a248db3f81effc49cb39b63cba1ef00513196076 | 1 | facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho | /*
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.litho.widget;
import com.facebook.litho.Component;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.annotations.LayoutSpec;
import com.facebook.litho.annotations.OnCreateLayout;
/** A component that doesn't render anything. */
@LayoutSpec
class EmptyComponentSpec {
@OnCreateLayout
static Component onCreateLayout(ComponentContext c) {
return null;
}
}
| litho-widget/src/main/java/com/facebook/litho/widget/EmptyComponentSpec.java | Introduce EmptyComponent
Summary: Introduce Empty component as part of the widget library
Reviewed By: IanChilds, mihaelao
Differential Revision: D6871856
fbshipit-source-id: eeab2c0f229c7b8315957829faf823bb73b6313b
| litho-widget/src/main/java/com/facebook/litho/widget/EmptyComponentSpec.java | Introduce EmptyComponent | <ide><path>itho-widget/src/main/java/com/facebook/litho/widget/EmptyComponentSpec.java
<add>/*
<add> * Copyright (c) 2017-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.litho.widget;
<add>
<add>import com.facebook.litho.Component;
<add>import com.facebook.litho.ComponentContext;
<add>import com.facebook.litho.annotations.LayoutSpec;
<add>import com.facebook.litho.annotations.OnCreateLayout;
<add>
<add>/** A component that doesn't render anything. */
<add>@LayoutSpec
<add>class EmptyComponentSpec {
<add>
<add> @OnCreateLayout
<add> static Component onCreateLayout(ComponentContext c) {
<add> return null;
<add> }
<add>} |
|
Java | apache-2.0 | 6337b44cfe2e9490d67ff020ea70c9ea55b1bf29 | 0 | bryazginkos/gwt-websocket-lib,bryazginkos/gwt-websocket-lib | package ru.kosdev.gwtwebsocket.client;
/**
* Created by kos on 27.07.2015.
*/
public class WSConfigurationValidator {
public static void validate(WSConfiguration configuration) {
if (configuration == null) throw new IllegalArgumentException("Websocket configuration is null");
if (configuration.getGClass() == null) throw new IllegalArgumentException("Websocket G class is null. Use G.getClass");
if (configuration.getSClass() == null) throw new IllegalArgumentException("Websocket S class is null. Use S.getClass");
if (configuration.getUrl() == null) throw new IllegalArgumentException("Websocket URL is null");
if (configuration.getSubscribeUrl() == null) throw new IllegalArgumentException("Websocket subscribe URL is null");
if (configuration.getAutoBeanFactory() == null) throw new IllegalArgumentException("Websocket autoBeanFactory is null");
}
}
| src/main/java/ru/kosdev/gwtwebsocket/client/WSConfigurationValidator.java | package ru.kosdev.gwtwebsocket.client;
/**
* Created by kos on 27.07.2015.
*/
public class WSConfigurationValidator {
public static void validate(WSConfiguration configuration) {
if (configuration == null) throw new IllegalArgumentException("Websocket configuration is null");
if (configuration.getCallback() == null) throw new IllegalArgumentException("Websocket Callback is null");
if (configuration.getGClass() == null) throw new IllegalArgumentException("Websocket G class is null. Use G.getClass");
if (configuration.getSClass() == null) throw new IllegalArgumentException("Websocket S class is null. Use S.getClass");
if (configuration.getUrl() == null) throw new IllegalArgumentException("Websocket URL is null");
if (configuration.getSubscribeUrl() == null) throw new IllegalArgumentException("Websocket subscribe URL is null");
if (configuration.getAutoBeanFactory() == null) throw new IllegalArgumentException("Websocket autoBeanFactory is null");
}
}
| build fix
| src/main/java/ru/kosdev/gwtwebsocket/client/WSConfigurationValidator.java | build fix | <ide><path>rc/main/java/ru/kosdev/gwtwebsocket/client/WSConfigurationValidator.java
<ide>
<ide> public static void validate(WSConfiguration configuration) {
<ide> if (configuration == null) throw new IllegalArgumentException("Websocket configuration is null");
<del> if (configuration.getCallback() == null) throw new IllegalArgumentException("Websocket Callback is null");
<ide> if (configuration.getGClass() == null) throw new IllegalArgumentException("Websocket G class is null. Use G.getClass");
<ide> if (configuration.getSClass() == null) throw new IllegalArgumentException("Websocket S class is null. Use S.getClass");
<ide> if (configuration.getUrl() == null) throw new IllegalArgumentException("Websocket URL is null"); |
|
Java | mit | error: pathspec 'src/main/java/mho/wheels/concurrency/ResultCache.java' did not match any file(s) known to git
| e7d0bbb1f2aeb45e58f06f9e0930267a3e5258e3 | 1 | mhogrefe/wheels | package mho.wheels.concurrency;
import mho.wheels.structures.Pair;
import mho.wheels.testing.Testing;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.function.Function;
import java.util.function.Predicate;
public class ResultCache<A, B> {
private static final int MAX_SIZE = Testing.LARGE_LIMIT;
private final @NotNull Function<A, B> function;
private final @NotNull Predicate<A> largeEnough;
public final @NotNull HashMap<A, B> resultMap;
public final @NotNull HashMap<A, Pair<Integer, Long>> costMap;
public final @NotNull PriorityQueue<Pair<Long, A>> costQueue;
public ResultCache(@NotNull Function<A, B> function, @NotNull Predicate<A> largeEnough) {
this.function = function;
this.largeEnough = largeEnough;
resultMap = new HashMap<>();
costMap = new HashMap<>();
costQueue = new PriorityQueue<>((p, q) -> Long.compare(p.a, q.a));
}
public @NotNull B get(A input) {
if (!largeEnough.test(input)) {
return function.apply(input);
}
B result;
result = resultMap.get(input);
if (result != null) {
synchronized (this) {
if (!resultMap.containsKey(input)) {
Pair<Integer, Long> costPair = costMap.remove(input);
costMap.put(input, new Pair<>(costPair.a + 1, costPair.b));
long cost = costPair.b * costPair.a;
costQueue.remove(new Pair<>(cost, input));
cost += costPair.b;
costQueue.add(new Pair<>(cost, input));
}
}
return result;
} else {
long startTime = System.currentTimeMillis();
result = function.apply(input);
long totalTime = System.currentTimeMillis() - startTime;
if (totalTime < 10) {
return result;
}
synchronized (this) {
if (!resultMap.containsKey(input)) {
if (costQueue.size() == MAX_SIZE) {
dumpCheapestResult();
}
resultMap.put(input, result);
costMap.put(input, new Pair<>(1, totalTime));
costQueue.add(new Pair<>(totalTime, input));
}
return result;
}
}
}
private void dumpCheapestResult() {
Pair<Long, A> cheapest = costQueue.poll();
resultMap.remove(cheapest.b);
costMap.remove(cheapest.b);
}
}
| src/main/java/mho/wheels/concurrency/ResultCache.java | added ResultCache
| src/main/java/mho/wheels/concurrency/ResultCache.java | added ResultCache | <ide><path>rc/main/java/mho/wheels/concurrency/ResultCache.java
<add>package mho.wheels.concurrency;
<add>
<add>import mho.wheels.structures.Pair;
<add>import mho.wheels.testing.Testing;
<add>import org.jetbrains.annotations.NotNull;
<add>
<add>import java.util.HashMap;
<add>import java.util.PriorityQueue;
<add>import java.util.function.Function;
<add>import java.util.function.Predicate;
<add>
<add>public class ResultCache<A, B> {
<add> private static final int MAX_SIZE = Testing.LARGE_LIMIT;
<add>
<add> private final @NotNull Function<A, B> function;
<add> private final @NotNull Predicate<A> largeEnough;
<add> public final @NotNull HashMap<A, B> resultMap;
<add> public final @NotNull HashMap<A, Pair<Integer, Long>> costMap;
<add> public final @NotNull PriorityQueue<Pair<Long, A>> costQueue;
<add>
<add> public ResultCache(@NotNull Function<A, B> function, @NotNull Predicate<A> largeEnough) {
<add> this.function = function;
<add> this.largeEnough = largeEnough;
<add> resultMap = new HashMap<>();
<add> costMap = new HashMap<>();
<add> costQueue = new PriorityQueue<>((p, q) -> Long.compare(p.a, q.a));
<add> }
<add>
<add> public @NotNull B get(A input) {
<add> if (!largeEnough.test(input)) {
<add> return function.apply(input);
<add> }
<add> B result;
<add> result = resultMap.get(input);
<add> if (result != null) {
<add> synchronized (this) {
<add> if (!resultMap.containsKey(input)) {
<add> Pair<Integer, Long> costPair = costMap.remove(input);
<add> costMap.put(input, new Pair<>(costPair.a + 1, costPair.b));
<add> long cost = costPair.b * costPair.a;
<add> costQueue.remove(new Pair<>(cost, input));
<add> cost += costPair.b;
<add> costQueue.add(new Pair<>(cost, input));
<add> }
<add> }
<add> return result;
<add> } else {
<add> long startTime = System.currentTimeMillis();
<add> result = function.apply(input);
<add> long totalTime = System.currentTimeMillis() - startTime;
<add> if (totalTime < 10) {
<add> return result;
<add> }
<add> synchronized (this) {
<add> if (!resultMap.containsKey(input)) {
<add> if (costQueue.size() == MAX_SIZE) {
<add> dumpCheapestResult();
<add> }
<add> resultMap.put(input, result);
<add> costMap.put(input, new Pair<>(1, totalTime));
<add> costQueue.add(new Pair<>(totalTime, input));
<add> }
<add> return result;
<add> }
<add> }
<add> }
<add>
<add> private void dumpCheapestResult() {
<add> Pair<Long, A> cheapest = costQueue.poll();
<add> resultMap.remove(cheapest.b);
<add> costMap.remove(cheapest.b);
<add> }
<add>} |
|
Java | apache-2.0 | ff8b3ebfb84dcc8d6eb0d0786a53cd855f82402d | 0 | google/ExoPlayer,saki4510t/ExoPlayer,tntcrowd/ExoPlayer,google/ExoPlayer,amzn/exoplayer-amazon-port,superbderrick/ExoPlayer,androidx/media,google/ExoPlayer,androidx/media,saki4510t/ExoPlayer,ened/ExoPlayer,superbderrick/ExoPlayer,stari4ek/ExoPlayer,androidx/media,superbderrick/ExoPlayer,tntcrowd/ExoPlayer,stari4ek/ExoPlayer,amzn/exoplayer-amazon-port,saki4510t/ExoPlayer,tntcrowd/ExoPlayer,ened/ExoPlayer,amzn/exoplayer-amazon-port,stari4ek/ExoPlayer,ened/ExoPlayer | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.video;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.media.MediaCodec;
import android.media.MediaCodecInfo.CodecCapabilities;
import android.media.MediaCrypto;
import android.media.MediaFormat;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Surface;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.PlayerMessage.Target;
import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.FrameworkMediaCrypto;
import com.google.android.exoplayer2.mediacodec.MediaCodecInfo;
import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer;
import com.google.android.exoplayer2.mediacodec.MediaCodecSelector;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil.DecoderQueryException;
import com.google.android.exoplayer2.mediacodec.MediaFormatUtil;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.TraceUtil;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener.EventDispatcher;
import java.nio.ByteBuffer;
/**
* Decodes and renders video using {@link MediaCodec}.
*
* <p>This renderer accepts the following messages sent via {@link ExoPlayer#createMessage(Target)}
* on the playback thread:
*
* <ul>
* <li>Message with type {@link C#MSG_SET_SURFACE} to set the output surface. The message payload
* should be the target {@link Surface}, or null.
* <li>Message with type {@link C#MSG_SET_SCALING_MODE} to set the video scaling mode. The message
* payload should be one of the integer scaling modes in {@link C.VideoScalingMode}. Note that
* the scaling mode only applies if the {@link Surface} targeted by this renderer is owned by
* a {@link android.view.SurfaceView}.
* </ul>
*/
@TargetApi(16)
public class MediaCodecVideoRenderer extends MediaCodecRenderer {
private static final String TAG = "MediaCodecVideoRenderer";
private static final String KEY_CROP_LEFT = "crop-left";
private static final String KEY_CROP_RIGHT = "crop-right";
private static final String KEY_CROP_BOTTOM = "crop-bottom";
private static final String KEY_CROP_TOP = "crop-top";
// Long edge length in pixels for standard video formats, in decreasing in order.
private static final int[] STANDARD_LONG_EDGE_VIDEO_PX = new int[] {
1920, 1600, 1440, 1280, 960, 854, 640, 540, 480};
// Generally there is zero or one pending output stream offset. We track more offsets to allow for
// pending output streams that have fewer frames than the codec latency.
private static final int MAX_PENDING_OUTPUT_STREAM_OFFSET_COUNT = 10;
private final Context context;
private final VideoFrameReleaseTimeHelper frameReleaseTimeHelper;
private final EventDispatcher eventDispatcher;
private final long allowedJoiningTimeMs;
private final int maxDroppedFramesToNotify;
private final boolean deviceNeedsAutoFrcWorkaround;
private final long[] pendingOutputStreamOffsetsUs;
private final long[] pendingOutputStreamSwitchTimesUs;
private CodecMaxValues codecMaxValues;
private boolean codecNeedsSetOutputSurfaceWorkaround;
private Surface surface;
private Surface dummySurface;
@C.VideoScalingMode
private int scalingMode;
private boolean renderedFirstFrame;
private long initialPositionUs;
private long joiningDeadlineMs;
private long droppedFrameAccumulationStartTimeMs;
private int droppedFrames;
private int consecutiveDroppedFrameCount;
private int buffersInCodecCount;
private long lastRenderTimeUs;
private int pendingRotationDegrees;
private float pendingPixelWidthHeightRatio;
private int currentWidth;
private int currentHeight;
private int currentUnappliedRotationDegrees;
private float currentPixelWidthHeightRatio;
private int reportedWidth;
private int reportedHeight;
private int reportedUnappliedRotationDegrees;
private float reportedPixelWidthHeightRatio;
private boolean tunneling;
private int tunnelingAudioSessionId;
/* package */ OnFrameRenderedListenerV23 tunnelingOnFrameRenderedListener;
private long lastInputTimeUs;
private long outputStreamOffsetUs;
private int pendingOutputStreamOffsetCount;
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector) {
this(context, mediaCodecSelector, 0);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs) {
this(
context,
mediaCodecSelector,
allowedJoiningTimeMs,
/* eventHandler= */ null,
/* eventListener= */ null,
-1);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
* null if delivery of events is not required.
* @param eventListener A listener of events. May be null if delivery of events is not required.
* @param maxDroppedFrameCountToNotify The maximum number of frames that can be dropped between
* invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs, @Nullable Handler eventHandler,
@Nullable VideoRendererEventListener eventListener, int maxDroppedFrameCountToNotify) {
this(
context,
mediaCodecSelector,
allowedJoiningTimeMs,
/* drmSessionManager= */ null,
/* playClearSamplesWithoutKeys= */ false,
eventHandler,
eventListener,
maxDroppedFrameCountToNotify);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
* @param drmSessionManager For use with encrypted content. May be null if support for encrypted
* content is not required.
* @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
* For example a media file may start with a short clear region so as to allow playback to
* begin in parallel with key acquisition. This parameter specifies whether the renderer is
* permitted to play clear regions of encrypted media files before {@code drmSessionManager}
* has obtained the keys necessary to decrypt encrypted regions of the media.
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
* null if delivery of events is not required.
* @param eventListener A listener of events. May be null if delivery of events is not required.
* @param maxDroppedFramesToNotify The maximum number of frames that can be dropped between
* invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs,
@Nullable DrmSessionManager<FrameworkMediaCrypto> drmSessionManager,
boolean playClearSamplesWithoutKeys, @Nullable Handler eventHandler,
@Nullable VideoRendererEventListener eventListener, int maxDroppedFramesToNotify) {
super(C.TRACK_TYPE_VIDEO, mediaCodecSelector, drmSessionManager, playClearSamplesWithoutKeys);
this.allowedJoiningTimeMs = allowedJoiningTimeMs;
this.maxDroppedFramesToNotify = maxDroppedFramesToNotify;
this.context = context.getApplicationContext();
frameReleaseTimeHelper = new VideoFrameReleaseTimeHelper(context);
eventDispatcher = new EventDispatcher(eventHandler, eventListener);
deviceNeedsAutoFrcWorkaround = deviceNeedsAutoFrcWorkaround();
pendingOutputStreamOffsetsUs = new long[MAX_PENDING_OUTPUT_STREAM_OFFSET_COUNT];
pendingOutputStreamSwitchTimesUs = new long[MAX_PENDING_OUTPUT_STREAM_OFFSET_COUNT];
outputStreamOffsetUs = C.TIME_UNSET;
lastInputTimeUs = C.TIME_UNSET;
joiningDeadlineMs = C.TIME_UNSET;
currentWidth = Format.NO_VALUE;
currentHeight = Format.NO_VALUE;
currentPixelWidthHeightRatio = Format.NO_VALUE;
pendingPixelWidthHeightRatio = Format.NO_VALUE;
scalingMode = C.VIDEO_SCALING_MODE_DEFAULT;
clearReportedVideoSize();
}
@Override
protected int supportsFormat(MediaCodecSelector mediaCodecSelector,
DrmSessionManager<FrameworkMediaCrypto> drmSessionManager, Format format)
throws DecoderQueryException {
String mimeType = format.sampleMimeType;
if (!MimeTypes.isVideo(mimeType)) {
return FORMAT_UNSUPPORTED_TYPE;
}
boolean requiresSecureDecryption = false;
DrmInitData drmInitData = format.drmInitData;
if (drmInitData != null) {
for (int i = 0; i < drmInitData.schemeDataCount; i++) {
requiresSecureDecryption |= drmInitData.get(i).requiresSecureDecryption;
}
}
MediaCodecInfo decoderInfo = mediaCodecSelector.getDecoderInfo(mimeType,
requiresSecureDecryption);
if (decoderInfo == null) {
return requiresSecureDecryption && mediaCodecSelector.getDecoderInfo(mimeType, false) != null
? FORMAT_UNSUPPORTED_DRM : FORMAT_UNSUPPORTED_SUBTYPE;
}
if (!supportsFormatDrm(drmSessionManager, drmInitData)) {
return FORMAT_UNSUPPORTED_DRM;
}
boolean decoderCapable = decoderInfo.isCodecSupported(format.codecs);
if (decoderCapable && format.width > 0 && format.height > 0) {
if (Util.SDK_INT >= 21) {
decoderCapable = decoderInfo.isVideoSizeAndRateSupportedV21(format.width, format.height,
format.frameRate);
} else {
decoderCapable = format.width * format.height <= MediaCodecUtil.maxH264DecodableFrameSize();
if (!decoderCapable) {
Log.d(TAG, "FalseCheck [legacyFrameSize, " + format.width + "x" + format.height + "] ["
+ Util.DEVICE_DEBUG_INFO + "]");
}
}
}
int adaptiveSupport = decoderInfo.adaptive ? ADAPTIVE_SEAMLESS : ADAPTIVE_NOT_SEAMLESS;
int tunnelingSupport = decoderInfo.tunneling ? TUNNELING_SUPPORTED : TUNNELING_NOT_SUPPORTED;
int formatSupport = decoderCapable ? FORMAT_HANDLED : FORMAT_EXCEEDS_CAPABILITIES;
return adaptiveSupport | tunnelingSupport | formatSupport;
}
@Override
protected void onEnabled(boolean joining) throws ExoPlaybackException {
super.onEnabled(joining);
tunnelingAudioSessionId = getConfiguration().tunnelingAudioSessionId;
tunneling = tunnelingAudioSessionId != C.AUDIO_SESSION_ID_UNSET;
eventDispatcher.enabled(decoderCounters);
frameReleaseTimeHelper.enable();
}
@Override
protected void onStreamChanged(Format[] formats, long offsetUs) throws ExoPlaybackException {
if (outputStreamOffsetUs == C.TIME_UNSET) {
outputStreamOffsetUs = offsetUs;
} else {
if (pendingOutputStreamOffsetCount == pendingOutputStreamOffsetsUs.length) {
Log.w(TAG, "Too many stream changes, so dropping offset: "
+ pendingOutputStreamOffsetsUs[pendingOutputStreamOffsetCount - 1]);
} else {
pendingOutputStreamOffsetCount++;
}
pendingOutputStreamOffsetsUs[pendingOutputStreamOffsetCount - 1] = offsetUs;
pendingOutputStreamSwitchTimesUs[pendingOutputStreamOffsetCount - 1] = lastInputTimeUs;
}
super.onStreamChanged(formats, offsetUs);
}
@Override
protected void onPositionReset(long positionUs, boolean joining) throws ExoPlaybackException {
super.onPositionReset(positionUs, joining);
clearRenderedFirstFrame();
initialPositionUs = C.TIME_UNSET;
consecutiveDroppedFrameCount = 0;
lastInputTimeUs = C.TIME_UNSET;
if (pendingOutputStreamOffsetCount != 0) {
outputStreamOffsetUs = pendingOutputStreamOffsetsUs[pendingOutputStreamOffsetCount - 1];
pendingOutputStreamOffsetCount = 0;
}
if (joining) {
setJoiningDeadlineMs();
} else {
joiningDeadlineMs = C.TIME_UNSET;
}
}
@Override
public boolean isReady() {
if (super.isReady() && (renderedFirstFrame || (dummySurface != null && surface == dummySurface)
|| getCodec() == null || tunneling)) {
// Ready. If we were joining then we've now joined, so clear the joining deadline.
joiningDeadlineMs = C.TIME_UNSET;
return true;
} else if (joiningDeadlineMs == C.TIME_UNSET) {
// Not joining.
return false;
} else if (SystemClock.elapsedRealtime() < joiningDeadlineMs) {
// Joining and still within the joining deadline.
return true;
} else {
// The joining deadline has been exceeded. Give up and clear the deadline.
joiningDeadlineMs = C.TIME_UNSET;
return false;
}
}
@Override
protected void onStarted() {
super.onStarted();
droppedFrames = 0;
droppedFrameAccumulationStartTimeMs = SystemClock.elapsedRealtime();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
}
@Override
protected void onStopped() {
joiningDeadlineMs = C.TIME_UNSET;
maybeNotifyDroppedFrames();
super.onStopped();
}
@Override
protected void onDisabled() {
currentWidth = Format.NO_VALUE;
currentHeight = Format.NO_VALUE;
currentPixelWidthHeightRatio = Format.NO_VALUE;
pendingPixelWidthHeightRatio = Format.NO_VALUE;
outputStreamOffsetUs = C.TIME_UNSET;
lastInputTimeUs = C.TIME_UNSET;
pendingOutputStreamOffsetCount = 0;
clearReportedVideoSize();
clearRenderedFirstFrame();
frameReleaseTimeHelper.disable();
tunnelingOnFrameRenderedListener = null;
tunneling = false;
try {
super.onDisabled();
} finally {
decoderCounters.ensureUpdated();
eventDispatcher.disabled(decoderCounters);
}
}
@Override
public void handleMessage(int messageType, Object message) throws ExoPlaybackException {
if (messageType == C.MSG_SET_SURFACE) {
setSurface((Surface) message);
} else if (messageType == C.MSG_SET_SCALING_MODE) {
scalingMode = (Integer) message;
MediaCodec codec = getCodec();
if (codec != null) {
codec.setVideoScalingMode(scalingMode);
}
} else {
super.handleMessage(messageType, message);
}
}
private void setSurface(Surface surface) throws ExoPlaybackException {
if (surface == null) {
// Use a dummy surface if possible.
if (dummySurface != null) {
surface = dummySurface;
} else {
MediaCodecInfo codecInfo = getCodecInfo();
if (codecInfo != null && shouldUseDummySurface(codecInfo)) {
dummySurface = DummySurface.newInstanceV17(context, codecInfo.secure);
surface = dummySurface;
}
}
}
// We only need to update the codec if the surface has changed.
if (this.surface != surface) {
this.surface = surface;
@State int state = getState();
if (state == STATE_ENABLED || state == STATE_STARTED) {
MediaCodec codec = getCodec();
if (Util.SDK_INT >= 23 && codec != null && surface != null
&& !codecNeedsSetOutputSurfaceWorkaround) {
setOutputSurfaceV23(codec, surface);
} else {
releaseCodec();
maybeInitCodec();
}
}
if (surface != null && surface != dummySurface) {
// If we know the video size, report it again immediately.
maybeRenotifyVideoSizeChanged();
// We haven't rendered to the new surface yet.
clearRenderedFirstFrame();
if (state == STATE_STARTED) {
setJoiningDeadlineMs();
}
} else {
// The surface has been removed.
clearReportedVideoSize();
clearRenderedFirstFrame();
}
} else if (surface != null && surface != dummySurface) {
// The surface is set and unchanged. If we know the video size and/or have already rendered to
// the surface, report these again immediately.
maybeRenotifyVideoSizeChanged();
maybeRenotifyRenderedFirstFrame();
}
}
@Override
protected boolean shouldInitCodec(MediaCodecInfo codecInfo) {
return surface != null || shouldUseDummySurface(codecInfo);
}
@Override
protected void configureCodec(MediaCodecInfo codecInfo, MediaCodec codec, Format format,
MediaCrypto crypto) throws DecoderQueryException {
codecMaxValues = getCodecMaxValues(codecInfo, format, getStreamFormats());
MediaFormat mediaFormat = getMediaFormat(format, codecMaxValues, deviceNeedsAutoFrcWorkaround,
tunnelingAudioSessionId);
if (surface == null) {
Assertions.checkState(shouldUseDummySurface(codecInfo));
if (dummySurface == null) {
dummySurface = DummySurface.newInstanceV17(context, codecInfo.secure);
}
surface = dummySurface;
}
codec.configure(mediaFormat, surface, crypto, 0);
if (Util.SDK_INT >= 23 && tunneling) {
tunnelingOnFrameRenderedListener = new OnFrameRenderedListenerV23(codec);
}
}
@Override
protected @KeepCodecResult int canKeepCodec(
MediaCodec codec, MediaCodecInfo codecInfo, Format oldFormat, Format newFormat) {
if (areAdaptationCompatible(codecInfo.adaptive, oldFormat, newFormat)
&& newFormat.width <= codecMaxValues.width
&& newFormat.height <= codecMaxValues.height
&& getMaxInputSize(newFormat) <= codecMaxValues.inputSize) {
return oldFormat.initializationDataEquals(newFormat)
? KEEP_CODEC_RESULT_YES_WITHOUT_RECONFIGURATION
: KEEP_CODEC_RESULT_YES_WITH_RECONFIGURATION;
}
return KEEP_CODEC_RESULT_NO;
}
@CallSuper
@Override
protected void releaseCodec() {
try {
super.releaseCodec();
} finally {
buffersInCodecCount = 0;
if (dummySurface != null) {
if (surface == dummySurface) {
surface = null;
}
dummySurface.release();
dummySurface = null;
}
}
}
@CallSuper
@Override
protected void flushCodec() throws ExoPlaybackException {
super.flushCodec();
buffersInCodecCount = 0;
}
@Override
protected void onCodecInitialized(String name, long initializedTimestampMs,
long initializationDurationMs) {
eventDispatcher.decoderInitialized(name, initializedTimestampMs, initializationDurationMs);
codecNeedsSetOutputSurfaceWorkaround = codecNeedsSetOutputSurfaceWorkaround(name);
}
@Override
protected void onInputFormatChanged(Format newFormat) throws ExoPlaybackException {
super.onInputFormatChanged(newFormat);
eventDispatcher.inputFormatChanged(newFormat);
pendingPixelWidthHeightRatio = newFormat.pixelWidthHeightRatio;
pendingRotationDegrees = newFormat.rotationDegrees;
}
/**
* Called immediately before an input buffer is queued into the codec.
*
* @param buffer The buffer to be queued.
*/
@CallSuper
@Override
protected void onQueueInputBuffer(DecoderInputBuffer buffer) {
buffersInCodecCount++;
lastInputTimeUs = Math.max(buffer.timeUs, lastInputTimeUs);
if (Util.SDK_INT < 23 && tunneling) {
maybeNotifyRenderedFirstFrame();
}
}
@Override
protected void onOutputFormatChanged(MediaCodec codec, MediaFormat outputFormat) {
boolean hasCrop = outputFormat.containsKey(KEY_CROP_RIGHT)
&& outputFormat.containsKey(KEY_CROP_LEFT) && outputFormat.containsKey(KEY_CROP_BOTTOM)
&& outputFormat.containsKey(KEY_CROP_TOP);
currentWidth = hasCrop
? outputFormat.getInteger(KEY_CROP_RIGHT) - outputFormat.getInteger(KEY_CROP_LEFT) + 1
: outputFormat.getInteger(MediaFormat.KEY_WIDTH);
currentHeight = hasCrop
? outputFormat.getInteger(KEY_CROP_BOTTOM) - outputFormat.getInteger(KEY_CROP_TOP) + 1
: outputFormat.getInteger(MediaFormat.KEY_HEIGHT);
currentPixelWidthHeightRatio = pendingPixelWidthHeightRatio;
if (Util.SDK_INT >= 21) {
// On API level 21 and above the decoder applies the rotation when rendering to the surface.
// Hence currentUnappliedRotation should always be 0. For 90 and 270 degree rotations, we need
// to flip the width, height and pixel aspect ratio to reflect the rotation that was applied.
if (pendingRotationDegrees == 90 || pendingRotationDegrees == 270) {
int rotatedHeight = currentWidth;
currentWidth = currentHeight;
currentHeight = rotatedHeight;
currentPixelWidthHeightRatio = 1 / currentPixelWidthHeightRatio;
}
} else {
// On API level 20 and below the decoder does not apply the rotation.
currentUnappliedRotationDegrees = pendingRotationDegrees;
}
// Must be applied each time the output format changes.
codec.setVideoScalingMode(scalingMode);
}
@Override
protected boolean processOutputBuffer(long positionUs, long elapsedRealtimeUs, MediaCodec codec,
ByteBuffer buffer, int bufferIndex, int bufferFlags, long bufferPresentationTimeUs,
boolean shouldSkip) throws ExoPlaybackException {
if (initialPositionUs == C.TIME_UNSET) {
initialPositionUs = positionUs;
}
long presentationTimeUs = bufferPresentationTimeUs - outputStreamOffsetUs;
if (shouldSkip) {
skipOutputBuffer(codec, bufferIndex, presentationTimeUs);
return true;
}
long earlyUs = bufferPresentationTimeUs - positionUs;
if (surface == dummySurface) {
// Skip frames in sync with playback, so we'll be at the right frame if the mode changes.
if (isBufferLate(earlyUs)) {
skipOutputBuffer(codec, bufferIndex, presentationTimeUs);
return true;
}
return false;
}
long elapsedRealtimeNowUs = SystemClock.elapsedRealtime() * 1000;
boolean isStarted = getState() == STATE_STARTED;
if (!renderedFirstFrame
|| (isStarted
&& shouldForceRenderOutputBuffer(earlyUs, elapsedRealtimeNowUs - lastRenderTimeUs))) {
if (Util.SDK_INT >= 21) {
renderOutputBufferV21(codec, bufferIndex, presentationTimeUs, System.nanoTime());
} else {
renderOutputBuffer(codec, bufferIndex, presentationTimeUs);
}
return true;
}
if (!isStarted || positionUs == initialPositionUs) {
return false;
}
// Fine-grained adjustment of earlyUs based on the elapsed time since the start of the current
// iteration of the rendering loop.
long elapsedSinceStartOfLoopUs = elapsedRealtimeNowUs - elapsedRealtimeUs;
earlyUs -= elapsedSinceStartOfLoopUs;
// Compute the buffer's desired release time in nanoseconds.
long systemTimeNs = System.nanoTime();
long unadjustedFrameReleaseTimeNs = systemTimeNs + (earlyUs * 1000);
// Apply a timestamp adjustment, if there is one.
long adjustedReleaseTimeNs = frameReleaseTimeHelper.adjustReleaseTime(
bufferPresentationTimeUs, unadjustedFrameReleaseTimeNs);
earlyUs = (adjustedReleaseTimeNs - systemTimeNs) / 1000;
if (shouldDropBuffersToKeyframe(earlyUs, elapsedRealtimeUs)
&& maybeDropBuffersToKeyframe(codec, bufferIndex, presentationTimeUs, positionUs)) {
return false;
} else if (shouldDropOutputBuffer(earlyUs, elapsedRealtimeUs)) {
dropOutputBuffer(codec, bufferIndex, presentationTimeUs);
return true;
}
if (Util.SDK_INT >= 21) {
// Let the underlying framework time the release.
if (earlyUs < 50000) {
renderOutputBufferV21(codec, bufferIndex, presentationTimeUs, adjustedReleaseTimeNs);
return true;
}
} else {
// We need to time the release ourselves.
if (earlyUs < 30000) {
if (earlyUs > 11000) {
// We're a little too early to render the frame. Sleep until the frame can be rendered.
// Note: The 11ms threshold was chosen fairly arbitrarily.
try {
// Subtracting 10000 rather than 11000 ensures the sleep time will be at least 1ms.
Thread.sleep((earlyUs - 10000) / 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
renderOutputBuffer(codec, bufferIndex, presentationTimeUs);
return true;
}
}
// We're either not playing, or it's not time to render the frame yet.
return false;
}
/**
* Called when an output buffer is successfully processed.
*
* @param presentationTimeUs The timestamp associated with the output buffer.
*/
@CallSuper
@Override
protected void onProcessedOutputBuffer(long presentationTimeUs) {
buffersInCodecCount--;
while (pendingOutputStreamOffsetCount != 0
&& presentationTimeUs >= pendingOutputStreamSwitchTimesUs[0]) {
outputStreamOffsetUs = pendingOutputStreamOffsetsUs[0];
pendingOutputStreamOffsetCount--;
System.arraycopy(
pendingOutputStreamOffsetsUs,
/* srcPos= */ 1,
pendingOutputStreamOffsetsUs,
/* destPos= */ 0,
pendingOutputStreamOffsetCount);
System.arraycopy(
pendingOutputStreamSwitchTimesUs,
/* srcPos= */ 1,
pendingOutputStreamSwitchTimesUs,
/* destPos= */ 0,
pendingOutputStreamOffsetCount);
}
}
/**
* Returns whether the buffer being processed should be dropped.
*
* @param earlyUs The time until the buffer should be presented in microseconds. A negative value
* indicates that the buffer is late.
* @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds,
* measured at the start of the current iteration of the rendering loop.
*/
protected boolean shouldDropOutputBuffer(long earlyUs, long elapsedRealtimeUs) {
return isBufferLate(earlyUs);
}
/**
* Returns whether to drop all buffers from the buffer being processed to the keyframe at or after
* the current playback position, if possible.
*
* @param earlyUs The time until the current buffer should be presented in microseconds. A
* negative value indicates that the buffer is late.
* @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds,
* measured at the start of the current iteration of the rendering loop.
*/
protected boolean shouldDropBuffersToKeyframe(long earlyUs, long elapsedRealtimeUs) {
return isBufferVeryLate(earlyUs);
}
/**
* Returns whether to force rendering an output buffer.
*
* @param earlyUs The time until the current buffer should be presented in microseconds. A
* negative value indicates that the buffer is late.
* @param elapsedSinceLastRenderUs The elapsed time since the last output buffer was rendered, in
* microseconds.
* @return Returns whether to force rendering an output buffer.
*/
protected boolean shouldForceRenderOutputBuffer(long earlyUs, long elapsedSinceLastRenderUs) {
return isBufferLate(earlyUs) && elapsedSinceLastRenderUs > 100000;
}
/**
* Skips the output buffer with the specified index.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to skip.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void skipOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
TraceUtil.beginSection("skipVideoBuffer");
codec.releaseOutputBuffer(index, false);
TraceUtil.endSection();
decoderCounters.skippedOutputBufferCount++;
}
/**
* Drops the output buffer with the specified index.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void dropOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
TraceUtil.beginSection("dropVideoBuffer");
codec.releaseOutputBuffer(index, false);
TraceUtil.endSection();
updateDroppedBufferCounters(1);
}
/**
* Drops frames from the current output buffer to the next keyframe at or before the playback
* position. If no such keyframe exists, as the playback position is inside the same group of
* pictures as the buffer being processed, returns {@code false}. Returns {@code true} otherwise.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
* @param positionUs The current playback position, in microseconds.
* @return Whether any buffers were dropped.
* @throws ExoPlaybackException If an error occurs flushing the codec.
*/
protected boolean maybeDropBuffersToKeyframe(MediaCodec codec, int index, long presentationTimeUs,
long positionUs) throws ExoPlaybackException {
int droppedSourceBufferCount = skipSource(positionUs);
if (droppedSourceBufferCount == 0) {
return false;
}
decoderCounters.droppedToKeyframeCount++;
// We dropped some buffers to catch up, so update the decoder counters and flush the codec,
// which releases all pending buffers buffers including the current output buffer.
updateDroppedBufferCounters(buffersInCodecCount + droppedSourceBufferCount);
flushCodec();
return true;
}
/**
* Updates decoder counters to reflect that {@code droppedBufferCount} additional buffers were
* dropped.
*
* @param droppedBufferCount The number of additional dropped buffers.
*/
protected void updateDroppedBufferCounters(int droppedBufferCount) {
decoderCounters.droppedBufferCount += droppedBufferCount;
droppedFrames += droppedBufferCount;
consecutiveDroppedFrameCount += droppedBufferCount;
decoderCounters.maxConsecutiveDroppedBufferCount = Math.max(consecutiveDroppedFrameCount,
decoderCounters.maxConsecutiveDroppedBufferCount);
if (droppedFrames >= maxDroppedFramesToNotify) {
maybeNotifyDroppedFrames();
}
}
/**
* Renders the output buffer with the specified index. This method is only called if the platform
* API version of the device is less than 21.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void renderOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
maybeNotifyVideoSizeChanged();
TraceUtil.beginSection("releaseOutputBuffer");
codec.releaseOutputBuffer(index, true);
TraceUtil.endSection();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
decoderCounters.renderedOutputBufferCount++;
consecutiveDroppedFrameCount = 0;
maybeNotifyRenderedFirstFrame();
}
/**
* Renders the output buffer with the specified index. This method is only called if the platform
* API version of the device is 21 or later.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
* @param releaseTimeNs The wallclock time at which the frame should be displayed, in nanoseconds.
*/
@TargetApi(21)
protected void renderOutputBufferV21(
MediaCodec codec, int index, long presentationTimeUs, long releaseTimeNs) {
maybeNotifyVideoSizeChanged();
TraceUtil.beginSection("releaseOutputBuffer");
codec.releaseOutputBuffer(index, releaseTimeNs);
TraceUtil.endSection();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
decoderCounters.renderedOutputBufferCount++;
consecutiveDroppedFrameCount = 0;
maybeNotifyRenderedFirstFrame();
}
private boolean shouldUseDummySurface(MediaCodecInfo codecInfo) {
return Util.SDK_INT >= 23
&& !tunneling
&& !codecNeedsSetOutputSurfaceWorkaround(codecInfo.name)
&& (!codecInfo.secure || DummySurface.isSecureSupported(context));
}
private void setJoiningDeadlineMs() {
joiningDeadlineMs = allowedJoiningTimeMs > 0
? (SystemClock.elapsedRealtime() + allowedJoiningTimeMs) : C.TIME_UNSET;
}
private void clearRenderedFirstFrame() {
renderedFirstFrame = false;
// The first frame notification is triggered by renderOutputBuffer or renderOutputBufferV21 for
// non-tunneled playback, onQueueInputBuffer for tunneled playback prior to API level 23, and
// OnFrameRenderedListenerV23.onFrameRenderedListener for tunneled playback on API level 23 and
// above.
if (Util.SDK_INT >= 23 && tunneling) {
MediaCodec codec = getCodec();
// If codec is null then the listener will be instantiated in configureCodec.
if (codec != null) {
tunnelingOnFrameRenderedListener = new OnFrameRenderedListenerV23(codec);
}
}
}
/* package */ void maybeNotifyRenderedFirstFrame() {
if (!renderedFirstFrame) {
renderedFirstFrame = true;
eventDispatcher.renderedFirstFrame(surface);
}
}
private void maybeRenotifyRenderedFirstFrame() {
if (renderedFirstFrame) {
eventDispatcher.renderedFirstFrame(surface);
}
}
private void clearReportedVideoSize() {
reportedWidth = Format.NO_VALUE;
reportedHeight = Format.NO_VALUE;
reportedPixelWidthHeightRatio = Format.NO_VALUE;
reportedUnappliedRotationDegrees = Format.NO_VALUE;
}
private void maybeNotifyVideoSizeChanged() {
if ((currentWidth != Format.NO_VALUE || currentHeight != Format.NO_VALUE)
&& (reportedWidth != currentWidth || reportedHeight != currentHeight
|| reportedUnappliedRotationDegrees != currentUnappliedRotationDegrees
|| reportedPixelWidthHeightRatio != currentPixelWidthHeightRatio)) {
eventDispatcher.videoSizeChanged(currentWidth, currentHeight, currentUnappliedRotationDegrees,
currentPixelWidthHeightRatio);
reportedWidth = currentWidth;
reportedHeight = currentHeight;
reportedUnappliedRotationDegrees = currentUnappliedRotationDegrees;
reportedPixelWidthHeightRatio = currentPixelWidthHeightRatio;
}
}
private void maybeRenotifyVideoSizeChanged() {
if (reportedWidth != Format.NO_VALUE || reportedHeight != Format.NO_VALUE) {
eventDispatcher.videoSizeChanged(reportedWidth, reportedHeight,
reportedUnappliedRotationDegrees, reportedPixelWidthHeightRatio);
}
}
private void maybeNotifyDroppedFrames() {
if (droppedFrames > 0) {
long now = SystemClock.elapsedRealtime();
long elapsedMs = now - droppedFrameAccumulationStartTimeMs;
eventDispatcher.droppedFrames(droppedFrames, elapsedMs);
droppedFrames = 0;
droppedFrameAccumulationStartTimeMs = now;
}
}
private static boolean isBufferLate(long earlyUs) {
// Class a buffer as late if it should have been presented more than 30 ms ago.
return earlyUs < -30000;
}
private static boolean isBufferVeryLate(long earlyUs) {
// Class a buffer as very late if it should have been presented more than 500 ms ago.
return earlyUs < -500000;
}
@TargetApi(23)
private static void setOutputSurfaceV23(MediaCodec codec, Surface surface) {
codec.setOutputSurface(surface);
}
@TargetApi(21)
private static void configureTunnelingV21(MediaFormat mediaFormat, int tunnelingAudioSessionId) {
mediaFormat.setFeatureEnabled(CodecCapabilities.FEATURE_TunneledPlayback, true);
mediaFormat.setInteger(MediaFormat.KEY_AUDIO_SESSION_ID, tunnelingAudioSessionId);
}
/**
* Returns the framework {@link MediaFormat} that should be used to configure the decoder.
*
* @param format The format of media.
* @param codecMaxValues Codec max values that should be used when configuring the decoder.
* @param deviceNeedsAutoFrcWorkaround Whether the device is known to enable frame-rate conversion
* logic that negatively impacts ExoPlayer.
* @param tunnelingAudioSessionId The audio session id to use for tunneling, or {@link
* C#AUDIO_SESSION_ID_UNSET} if tunneling should not be enabled.
* @return The framework {@link MediaFormat} that should be used to configure the decoder.
*/
@SuppressLint("InlinedApi")
protected MediaFormat getMediaFormat(
Format format,
CodecMaxValues codecMaxValues,
boolean deviceNeedsAutoFrcWorkaround,
int tunnelingAudioSessionId) {
MediaFormat mediaFormat = new MediaFormat();
// Set format parameters that should always be set.
mediaFormat.setString(MediaFormat.KEY_MIME, format.sampleMimeType);
mediaFormat.setInteger(MediaFormat.KEY_WIDTH, format.width);
mediaFormat.setInteger(MediaFormat.KEY_HEIGHT, format.height);
MediaFormatUtil.setCsdBuffers(mediaFormat, format.initializationData);
// Set format parameters that may be unset.
MediaFormatUtil.maybeSetFloat(mediaFormat, MediaFormat.KEY_FRAME_RATE, format.frameRate);
MediaFormatUtil.maybeSetInteger(mediaFormat, MediaFormat.KEY_ROTATION, format.rotationDegrees);
MediaFormatUtil.maybeSetColorInfo(mediaFormat, format.colorInfo);
// Set codec max values.
mediaFormat.setInteger(MediaFormat.KEY_MAX_WIDTH, codecMaxValues.width);
mediaFormat.setInteger(MediaFormat.KEY_MAX_HEIGHT, codecMaxValues.height);
MediaFormatUtil.maybeSetInteger(
mediaFormat, MediaFormat.KEY_MAX_INPUT_SIZE, codecMaxValues.inputSize);
// Set codec configuration values.
if (Util.SDK_INT >= 23) {
mediaFormat.setInteger(MediaFormat.KEY_PRIORITY, 0 /* realtime priority */);
}
if (deviceNeedsAutoFrcWorkaround) {
mediaFormat.setInteger("auto-frc", 0);
}
if (tunnelingAudioSessionId != C.AUDIO_SESSION_ID_UNSET) {
configureTunnelingV21(mediaFormat, tunnelingAudioSessionId);
}
return mediaFormat;
}
/**
* Returns {@link CodecMaxValues} suitable for configuring a codec for {@code format} in a way
* that will allow possible adaptation to other compatible formats in {@code streamFormats}.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param format The format for which the codec is being configured.
* @param streamFormats The possible stream formats.
* @return Suitable {@link CodecMaxValues}.
* @throws DecoderQueryException If an error occurs querying {@code codecInfo}.
*/
protected CodecMaxValues getCodecMaxValues(
MediaCodecInfo codecInfo, Format format, Format[] streamFormats)
throws DecoderQueryException {
int maxWidth = format.width;
int maxHeight = format.height;
int maxInputSize = getMaxInputSize(format);
if (streamFormats.length == 1) {
// The single entry in streamFormats must correspond to the format for which the codec is
// being configured.
return new CodecMaxValues(maxWidth, maxHeight, maxInputSize);
}
boolean haveUnknownDimensions = false;
for (Format streamFormat : streamFormats) {
if (areAdaptationCompatible(codecInfo.adaptive, format, streamFormat)) {
haveUnknownDimensions |=
(streamFormat.width == Format.NO_VALUE || streamFormat.height == Format.NO_VALUE);
maxWidth = Math.max(maxWidth, streamFormat.width);
maxHeight = Math.max(maxHeight, streamFormat.height);
maxInputSize = Math.max(maxInputSize, getMaxInputSize(streamFormat));
}
}
if (haveUnknownDimensions) {
Log.w(TAG, "Resolutions unknown. Codec max resolution: " + maxWidth + "x" + maxHeight);
Point codecMaxSize = getCodecMaxSize(codecInfo, format);
if (codecMaxSize != null) {
maxWidth = Math.max(maxWidth, codecMaxSize.x);
maxHeight = Math.max(maxHeight, codecMaxSize.y);
maxInputSize =
Math.max(maxInputSize, getMaxInputSize(format.sampleMimeType, maxWidth, maxHeight));
Log.w(TAG, "Codec max resolution adjusted to: " + maxWidth + "x" + maxHeight);
}
}
return new CodecMaxValues(maxWidth, maxHeight, maxInputSize);
}
/**
* Returns a maximum video size to use when configuring a codec for {@code format} in a way
* that will allow possible adaptation to other compatible formats that are expected to have the
* same aspect ratio, but whose sizes are unknown.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param format The format for which the codec is being configured.
* @return The maximum video size to use, or null if the size of {@code format} should be used.
* @throws DecoderQueryException If an error occurs querying {@code codecInfo}.
*/
private static Point getCodecMaxSize(MediaCodecInfo codecInfo, Format format)
throws DecoderQueryException {
boolean isVerticalVideo = format.height > format.width;
int formatLongEdgePx = isVerticalVideo ? format.height : format.width;
int formatShortEdgePx = isVerticalVideo ? format.width : format.height;
float aspectRatio = (float) formatShortEdgePx / formatLongEdgePx;
for (int longEdgePx : STANDARD_LONG_EDGE_VIDEO_PX) {
int shortEdgePx = (int) (longEdgePx * aspectRatio);
if (longEdgePx <= formatLongEdgePx || shortEdgePx <= formatShortEdgePx) {
// Don't return a size not larger than the format for which the codec is being configured.
return null;
} else if (Util.SDK_INT >= 21) {
Point alignedSize = codecInfo.alignVideoSizeV21(isVerticalVideo ? shortEdgePx : longEdgePx,
isVerticalVideo ? longEdgePx : shortEdgePx);
float frameRate = format.frameRate;
if (codecInfo.isVideoSizeAndRateSupportedV21(alignedSize.x, alignedSize.y, frameRate)) {
return alignedSize;
}
} else {
// Conservatively assume the codec requires 16px width and height alignment.
longEdgePx = Util.ceilDivide(longEdgePx, 16) * 16;
shortEdgePx = Util.ceilDivide(shortEdgePx, 16) * 16;
if (longEdgePx * shortEdgePx <= MediaCodecUtil.maxH264DecodableFrameSize()) {
return new Point(isVerticalVideo ? shortEdgePx : longEdgePx,
isVerticalVideo ? longEdgePx : shortEdgePx);
}
}
}
return null;
}
/**
* Returns a maximum input buffer size for a given format.
*
* @param format The format.
* @return A maximum input buffer size in bytes, or {@link Format#NO_VALUE} if a maximum could not
* be determined.
*/
private static int getMaxInputSize(Format format) {
if (format.maxInputSize != Format.NO_VALUE) {
// The format defines an explicit maximum input size. Add the total size of initialization
// data buffers, as they may need to be queued in the same input buffer as the largest sample.
int totalInitializationDataSize = 0;
int initializationDataCount = format.initializationData.size();
for (int i = 0; i < initializationDataCount; i++) {
totalInitializationDataSize += format.initializationData.get(i).length;
}
return format.maxInputSize + totalInitializationDataSize;
} else {
// Calculated maximum input sizes are overestimates, so it's not necessary to add the size of
// initialization data.
return getMaxInputSize(format.sampleMimeType, format.width, format.height);
}
}
/**
* Returns a maximum input size for a given mime type, width and height.
*
* @param sampleMimeType The format mime type.
* @param width The width in pixels.
* @param height The height in pixels.
* @return A maximum input size in bytes, or {@link Format#NO_VALUE} if a maximum could not be
* determined.
*/
private static int getMaxInputSize(String sampleMimeType, int width, int height) {
if (width == Format.NO_VALUE || height == Format.NO_VALUE) {
// We can't infer a maximum input size without video dimensions.
return Format.NO_VALUE;
}
// Attempt to infer a maximum input size from the format.
int maxPixels;
int minCompressionRatio;
switch (sampleMimeType) {
case MimeTypes.VIDEO_H263:
case MimeTypes.VIDEO_MP4V:
maxPixels = width * height;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_H264:
if ("BRAVIA 4K 2015".equals(Util.MODEL)) {
// The Sony BRAVIA 4k TV has input buffers that are too small for the calculated 4k video
// maximum input size, so use the default value.
return Format.NO_VALUE;
}
// Round up width/height to an integer number of macroblocks.
maxPixels = Util.ceilDivide(width, 16) * Util.ceilDivide(height, 16) * 16 * 16;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_VP8:
// VPX does not specify a ratio so use the values from the platform's SoftVPX.cpp.
maxPixels = width * height;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_H265:
case MimeTypes.VIDEO_VP9:
maxPixels = width * height;
minCompressionRatio = 4;
break;
default:
// Leave the default max input size.
return Format.NO_VALUE;
}
// Estimate the maximum input size assuming three channel 4:2:0 subsampled input frames.
return (maxPixels * 3) / (2 * minCompressionRatio);
}
/**
* Returns whether a codec with suitable {@link CodecMaxValues} will support adaptation between
* two {@link Format}s.
*
* @param codecIsAdaptive Whether the codec supports seamless resolution switches.
* @param first The first format.
* @param second The second format.
* @return Whether the codec will support adaptation between the two {@link Format}s.
*/
private static boolean areAdaptationCompatible(
boolean codecIsAdaptive, Format first, Format second) {
return first.sampleMimeType.equals(second.sampleMimeType)
&& first.rotationDegrees == second.rotationDegrees
&& (codecIsAdaptive || (first.width == second.width && first.height == second.height))
&& Util.areEqual(first.colorInfo, second.colorInfo);
}
/**
* Returns whether the device is known to enable frame-rate conversion logic that negatively
* impacts ExoPlayer.
* <p>
* If true is returned then we explicitly disable the feature.
*
* @return True if the device is known to enable frame-rate conversion logic that negatively
* impacts ExoPlayer. False otherwise.
*/
private static boolean deviceNeedsAutoFrcWorkaround() {
// nVidia Shield prior to M tries to adjust the playback rate to better map the frame-rate of
// content to the refresh rate of the display. For example playback of 23.976fps content is
// adjusted to play at 1.001x speed when the output display is 60Hz. Unfortunately the
// implementation causes ExoPlayer's reported playback position to drift out of sync. Captions
// also lose sync [Internal: b/26453592].
return Util.SDK_INT <= 22 && "foster".equals(Util.DEVICE) && "NVIDIA".equals(Util.MANUFACTURER);
}
/**
* Returns whether the device is known to implement {@link MediaCodec#setOutputSurface(Surface)}
* incorrectly.
* <p>
* If true is returned then we fall back to releasing and re-instantiating the codec instead.
*/
private static boolean codecNeedsSetOutputSurfaceWorkaround(String name) {
// Work around https://github.com/google/ExoPlayer/issues/3236,
// https://github.com/google/ExoPlayer/issues/3355,
// https://github.com/google/ExoPlayer/issues/3439,
// https://github.com/google/ExoPlayer/issues/3724,
// https://github.com/google/ExoPlayer/issues/3835,
// https://github.com/google/ExoPlayer/issues/4006,
// https://github.com/google/ExoPlayer/issues/4084,
// https://github.com/google/ExoPlayer/issues/4104.
// https://github.com/google/ExoPlayer/issues/4134.
// https://github.com/google/ExoPlayer/issues/4315
return (("deb".equals(Util.DEVICE) // Nexus 7 (2013)
|| "flo".equals(Util.DEVICE) // Nexus 7 (2013)
|| "mido".equals(Util.DEVICE) // Redmi Note 4
|| "santoni".equals(Util.DEVICE)) // Redmi 4X
&& "OMX.qcom.video.decoder.avc".equals(name))
|| (("tcl_eu".equals(Util.DEVICE) // TCL Percee TV
|| "SVP-DTV15".equals(Util.DEVICE) // Sony Bravia 4K 2015
|| "BRAVIA_ATV2".equals(Util.DEVICE) // Sony Bravia 4K GB
|| Util.DEVICE.startsWith("panell_") // Motorola Moto C Plus
|| "F3311".equals(Util.DEVICE) // Sony Xperia E5
|| "M5c".equals(Util.DEVICE) // Meizu M5C
|| "QM16XE_U".equals(Util.DEVICE) // Philips QM163E
|| "A7010a48".equals(Util.DEVICE) // Lenovo K4 Note
|| "woods_f".equals(Util.MODEL) // Moto E (4)
|| "watson".equals(Util.DEVICE)) // Moto C
&& "OMX.MTK.VIDEO.DECODER.AVC".equals(name))
|| (("ALE-L21".equals(Util.MODEL) // Huawei P8 Lite
|| "CAM-L21".equals(Util.MODEL)) // Huawei Y6II
&& "OMX.k3.video.decoder.avc".equals(name))
|| (("HUAWEI VNS-L21".equals(Util.MODEL)) // Huawei P9 Lite
&& "OMX.IMG.MSVDX.Decoder.AVC".equals(name));
}
protected static final class CodecMaxValues {
public final int width;
public final int height;
public final int inputSize;
public CodecMaxValues(int width, int height, int inputSize) {
this.width = width;
this.height = height;
this.inputSize = inputSize;
}
}
@TargetApi(23)
private final class OnFrameRenderedListenerV23 implements MediaCodec.OnFrameRenderedListener {
private OnFrameRenderedListenerV23(MediaCodec codec) {
codec.setOnFrameRenderedListener(this, new Handler());
}
@Override
public void onFrameRendered(@NonNull MediaCodec codec, long presentationTimeUs, long nanoTime) {
if (this != tunnelingOnFrameRenderedListener) {
// Stale event.
return;
}
maybeNotifyRenderedFirstFrame();
}
}
}
| library/core/src/main/java/com/google/android/exoplayer2/video/MediaCodecVideoRenderer.java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.video;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.media.MediaCodec;
import android.media.MediaCodecInfo.CodecCapabilities;
import android.media.MediaCrypto;
import android.media.MediaFormat;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Surface;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.PlayerMessage.Target;
import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.FrameworkMediaCrypto;
import com.google.android.exoplayer2.mediacodec.MediaCodecInfo;
import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer;
import com.google.android.exoplayer2.mediacodec.MediaCodecSelector;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil.DecoderQueryException;
import com.google.android.exoplayer2.mediacodec.MediaFormatUtil;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.TraceUtil;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener.EventDispatcher;
import java.nio.ByteBuffer;
/**
* Decodes and renders video using {@link MediaCodec}.
*
* <p>This renderer accepts the following messages sent via {@link ExoPlayer#createMessage(Target)}
* on the playback thread:
*
* <ul>
* <li>Message with type {@link C#MSG_SET_SURFACE} to set the output surface. The message payload
* should be the target {@link Surface}, or null.
* <li>Message with type {@link C#MSG_SET_SCALING_MODE} to set the video scaling mode. The message
* payload should be one of the integer scaling modes in {@link C.VideoScalingMode}. Note that
* the scaling mode only applies if the {@link Surface} targeted by this renderer is owned by
* a {@link android.view.SurfaceView}.
* </ul>
*/
@TargetApi(16)
public class MediaCodecVideoRenderer extends MediaCodecRenderer {
private static final String TAG = "MediaCodecVideoRenderer";
private static final String KEY_CROP_LEFT = "crop-left";
private static final String KEY_CROP_RIGHT = "crop-right";
private static final String KEY_CROP_BOTTOM = "crop-bottom";
private static final String KEY_CROP_TOP = "crop-top";
// Long edge length in pixels for standard video formats, in decreasing in order.
private static final int[] STANDARD_LONG_EDGE_VIDEO_PX = new int[] {
1920, 1600, 1440, 1280, 960, 854, 640, 540, 480};
// Generally there is zero or one pending output stream offset. We track more offsets to allow for
// pending output streams that have fewer frames than the codec latency.
private static final int MAX_PENDING_OUTPUT_STREAM_OFFSET_COUNT = 10;
private final Context context;
private final VideoFrameReleaseTimeHelper frameReleaseTimeHelper;
private final EventDispatcher eventDispatcher;
private final long allowedJoiningTimeMs;
private final int maxDroppedFramesToNotify;
private final boolean deviceNeedsAutoFrcWorkaround;
private final long[] pendingOutputStreamOffsetsUs;
private final long[] pendingOutputStreamSwitchTimesUs;
private CodecMaxValues codecMaxValues;
private boolean codecNeedsSetOutputSurfaceWorkaround;
private Surface surface;
private Surface dummySurface;
@C.VideoScalingMode
private int scalingMode;
private boolean renderedFirstFrame;
private long initialPositionUs;
private long joiningDeadlineMs;
private long droppedFrameAccumulationStartTimeMs;
private int droppedFrames;
private int consecutiveDroppedFrameCount;
private int buffersInCodecCount;
private long lastRenderTimeUs;
private int pendingRotationDegrees;
private float pendingPixelWidthHeightRatio;
private int currentWidth;
private int currentHeight;
private int currentUnappliedRotationDegrees;
private float currentPixelWidthHeightRatio;
private int reportedWidth;
private int reportedHeight;
private int reportedUnappliedRotationDegrees;
private float reportedPixelWidthHeightRatio;
private boolean tunneling;
private int tunnelingAudioSessionId;
/* package */ OnFrameRenderedListenerV23 tunnelingOnFrameRenderedListener;
private long lastInputTimeUs;
private long outputStreamOffsetUs;
private int pendingOutputStreamOffsetCount;
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector) {
this(context, mediaCodecSelector, 0);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs) {
this(
context,
mediaCodecSelector,
allowedJoiningTimeMs,
/* eventHandler= */ null,
/* eventListener= */ null,
-1);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
* null if delivery of events is not required.
* @param eventListener A listener of events. May be null if delivery of events is not required.
* @param maxDroppedFrameCountToNotify The maximum number of frames that can be dropped between
* invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs, @Nullable Handler eventHandler,
@Nullable VideoRendererEventListener eventListener, int maxDroppedFrameCountToNotify) {
this(
context,
mediaCodecSelector,
allowedJoiningTimeMs,
/* drmSessionManager= */ null,
/* playClearSamplesWithoutKeys= */ false,
eventHandler,
eventListener,
maxDroppedFrameCountToNotify);
}
/**
* @param context A context.
* @param mediaCodecSelector A decoder selector.
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
* can attempt to seamlessly join an ongoing playback.
* @param drmSessionManager For use with encrypted content. May be null if support for encrypted
* content is not required.
* @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
* For example a media file may start with a short clear region so as to allow playback to
* begin in parallel with key acquisition. This parameter specifies whether the renderer is
* permitted to play clear regions of encrypted media files before {@code drmSessionManager}
* has obtained the keys necessary to decrypt encrypted regions of the media.
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
* null if delivery of events is not required.
* @param eventListener A listener of events. May be null if delivery of events is not required.
* @param maxDroppedFramesToNotify The maximum number of frames that can be dropped between
* invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}.
*/
public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
long allowedJoiningTimeMs,
@Nullable DrmSessionManager<FrameworkMediaCrypto> drmSessionManager,
boolean playClearSamplesWithoutKeys, @Nullable Handler eventHandler,
@Nullable VideoRendererEventListener eventListener, int maxDroppedFramesToNotify) {
super(C.TRACK_TYPE_VIDEO, mediaCodecSelector, drmSessionManager, playClearSamplesWithoutKeys);
this.allowedJoiningTimeMs = allowedJoiningTimeMs;
this.maxDroppedFramesToNotify = maxDroppedFramesToNotify;
this.context = context.getApplicationContext();
frameReleaseTimeHelper = new VideoFrameReleaseTimeHelper(context);
eventDispatcher = new EventDispatcher(eventHandler, eventListener);
deviceNeedsAutoFrcWorkaround = deviceNeedsAutoFrcWorkaround();
pendingOutputStreamOffsetsUs = new long[MAX_PENDING_OUTPUT_STREAM_OFFSET_COUNT];
pendingOutputStreamSwitchTimesUs = new long[MAX_PENDING_OUTPUT_STREAM_OFFSET_COUNT];
outputStreamOffsetUs = C.TIME_UNSET;
lastInputTimeUs = C.TIME_UNSET;
joiningDeadlineMs = C.TIME_UNSET;
currentWidth = Format.NO_VALUE;
currentHeight = Format.NO_VALUE;
currentPixelWidthHeightRatio = Format.NO_VALUE;
pendingPixelWidthHeightRatio = Format.NO_VALUE;
scalingMode = C.VIDEO_SCALING_MODE_DEFAULT;
clearReportedVideoSize();
}
@Override
protected int supportsFormat(MediaCodecSelector mediaCodecSelector,
DrmSessionManager<FrameworkMediaCrypto> drmSessionManager, Format format)
throws DecoderQueryException {
String mimeType = format.sampleMimeType;
if (!MimeTypes.isVideo(mimeType)) {
return FORMAT_UNSUPPORTED_TYPE;
}
boolean requiresSecureDecryption = false;
DrmInitData drmInitData = format.drmInitData;
if (drmInitData != null) {
for (int i = 0; i < drmInitData.schemeDataCount; i++) {
requiresSecureDecryption |= drmInitData.get(i).requiresSecureDecryption;
}
}
MediaCodecInfo decoderInfo = mediaCodecSelector.getDecoderInfo(mimeType,
requiresSecureDecryption);
if (decoderInfo == null) {
return requiresSecureDecryption && mediaCodecSelector.getDecoderInfo(mimeType, false) != null
? FORMAT_UNSUPPORTED_DRM : FORMAT_UNSUPPORTED_SUBTYPE;
}
if (!supportsFormatDrm(drmSessionManager, drmInitData)) {
return FORMAT_UNSUPPORTED_DRM;
}
boolean decoderCapable = decoderInfo.isCodecSupported(format.codecs);
if (decoderCapable && format.width > 0 && format.height > 0) {
if (Util.SDK_INT >= 21) {
decoderCapable = decoderInfo.isVideoSizeAndRateSupportedV21(format.width, format.height,
format.frameRate);
} else {
decoderCapable = format.width * format.height <= MediaCodecUtil.maxH264DecodableFrameSize();
if (!decoderCapable) {
Log.d(TAG, "FalseCheck [legacyFrameSize, " + format.width + "x" + format.height + "] ["
+ Util.DEVICE_DEBUG_INFO + "]");
}
}
}
int adaptiveSupport = decoderInfo.adaptive ? ADAPTIVE_SEAMLESS : ADAPTIVE_NOT_SEAMLESS;
int tunnelingSupport = decoderInfo.tunneling ? TUNNELING_SUPPORTED : TUNNELING_NOT_SUPPORTED;
int formatSupport = decoderCapable ? FORMAT_HANDLED : FORMAT_EXCEEDS_CAPABILITIES;
return adaptiveSupport | tunnelingSupport | formatSupport;
}
@Override
protected void onEnabled(boolean joining) throws ExoPlaybackException {
super.onEnabled(joining);
tunnelingAudioSessionId = getConfiguration().tunnelingAudioSessionId;
tunneling = tunnelingAudioSessionId != C.AUDIO_SESSION_ID_UNSET;
eventDispatcher.enabled(decoderCounters);
frameReleaseTimeHelper.enable();
}
@Override
protected void onStreamChanged(Format[] formats, long offsetUs) throws ExoPlaybackException {
if (outputStreamOffsetUs == C.TIME_UNSET) {
outputStreamOffsetUs = offsetUs;
} else {
if (pendingOutputStreamOffsetCount == pendingOutputStreamOffsetsUs.length) {
Log.w(TAG, "Too many stream changes, so dropping offset: "
+ pendingOutputStreamOffsetsUs[pendingOutputStreamOffsetCount - 1]);
} else {
pendingOutputStreamOffsetCount++;
}
pendingOutputStreamOffsetsUs[pendingOutputStreamOffsetCount - 1] = offsetUs;
pendingOutputStreamSwitchTimesUs[pendingOutputStreamOffsetCount - 1] = lastInputTimeUs;
}
super.onStreamChanged(formats, offsetUs);
}
@Override
protected void onPositionReset(long positionUs, boolean joining) throws ExoPlaybackException {
super.onPositionReset(positionUs, joining);
clearRenderedFirstFrame();
initialPositionUs = C.TIME_UNSET;
consecutiveDroppedFrameCount = 0;
lastInputTimeUs = C.TIME_UNSET;
if (pendingOutputStreamOffsetCount != 0) {
outputStreamOffsetUs = pendingOutputStreamOffsetsUs[pendingOutputStreamOffsetCount - 1];
pendingOutputStreamOffsetCount = 0;
}
if (joining) {
setJoiningDeadlineMs();
} else {
joiningDeadlineMs = C.TIME_UNSET;
}
}
@Override
public boolean isReady() {
if (super.isReady() && (renderedFirstFrame || (dummySurface != null && surface == dummySurface)
|| getCodec() == null || tunneling)) {
// Ready. If we were joining then we've now joined, so clear the joining deadline.
joiningDeadlineMs = C.TIME_UNSET;
return true;
} else if (joiningDeadlineMs == C.TIME_UNSET) {
// Not joining.
return false;
} else if (SystemClock.elapsedRealtime() < joiningDeadlineMs) {
// Joining and still within the joining deadline.
return true;
} else {
// The joining deadline has been exceeded. Give up and clear the deadline.
joiningDeadlineMs = C.TIME_UNSET;
return false;
}
}
@Override
protected void onStarted() {
super.onStarted();
droppedFrames = 0;
droppedFrameAccumulationStartTimeMs = SystemClock.elapsedRealtime();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
}
@Override
protected void onStopped() {
joiningDeadlineMs = C.TIME_UNSET;
maybeNotifyDroppedFrames();
super.onStopped();
}
@Override
protected void onDisabled() {
currentWidth = Format.NO_VALUE;
currentHeight = Format.NO_VALUE;
currentPixelWidthHeightRatio = Format.NO_VALUE;
pendingPixelWidthHeightRatio = Format.NO_VALUE;
outputStreamOffsetUs = C.TIME_UNSET;
lastInputTimeUs = C.TIME_UNSET;
pendingOutputStreamOffsetCount = 0;
clearReportedVideoSize();
clearRenderedFirstFrame();
frameReleaseTimeHelper.disable();
tunnelingOnFrameRenderedListener = null;
tunneling = false;
try {
super.onDisabled();
} finally {
decoderCounters.ensureUpdated();
eventDispatcher.disabled(decoderCounters);
}
}
@Override
public void handleMessage(int messageType, Object message) throws ExoPlaybackException {
if (messageType == C.MSG_SET_SURFACE) {
setSurface((Surface) message);
} else if (messageType == C.MSG_SET_SCALING_MODE) {
scalingMode = (Integer) message;
MediaCodec codec = getCodec();
if (codec != null) {
codec.setVideoScalingMode(scalingMode);
}
} else {
super.handleMessage(messageType, message);
}
}
private void setSurface(Surface surface) throws ExoPlaybackException {
if (surface == null) {
// Use a dummy surface if possible.
if (dummySurface != null) {
surface = dummySurface;
} else {
MediaCodecInfo codecInfo = getCodecInfo();
if (codecInfo != null && shouldUseDummySurface(codecInfo)) {
dummySurface = DummySurface.newInstanceV17(context, codecInfo.secure);
surface = dummySurface;
}
}
}
// We only need to update the codec if the surface has changed.
if (this.surface != surface) {
this.surface = surface;
@State int state = getState();
if (state == STATE_ENABLED || state == STATE_STARTED) {
MediaCodec codec = getCodec();
if (Util.SDK_INT >= 23 && codec != null && surface != null
&& !codecNeedsSetOutputSurfaceWorkaround) {
setOutputSurfaceV23(codec, surface);
} else {
releaseCodec();
maybeInitCodec();
}
}
if (surface != null && surface != dummySurface) {
// If we know the video size, report it again immediately.
maybeRenotifyVideoSizeChanged();
// We haven't rendered to the new surface yet.
clearRenderedFirstFrame();
if (state == STATE_STARTED) {
setJoiningDeadlineMs();
}
} else {
// The surface has been removed.
clearReportedVideoSize();
clearRenderedFirstFrame();
}
} else if (surface != null && surface != dummySurface) {
// The surface is set and unchanged. If we know the video size and/or have already rendered to
// the surface, report these again immediately.
maybeRenotifyVideoSizeChanged();
maybeRenotifyRenderedFirstFrame();
}
}
@Override
protected boolean shouldInitCodec(MediaCodecInfo codecInfo) {
return surface != null || shouldUseDummySurface(codecInfo);
}
@Override
protected void configureCodec(MediaCodecInfo codecInfo, MediaCodec codec, Format format,
MediaCrypto crypto) throws DecoderQueryException {
codecMaxValues = getCodecMaxValues(codecInfo, format, getStreamFormats());
MediaFormat mediaFormat = getMediaFormat(format, codecMaxValues, deviceNeedsAutoFrcWorkaround,
tunnelingAudioSessionId);
if (surface == null) {
Assertions.checkState(shouldUseDummySurface(codecInfo));
if (dummySurface == null) {
dummySurface = DummySurface.newInstanceV17(context, codecInfo.secure);
}
surface = dummySurface;
}
codec.configure(mediaFormat, surface, crypto, 0);
if (Util.SDK_INT >= 23 && tunneling) {
tunnelingOnFrameRenderedListener = new OnFrameRenderedListenerV23(codec);
}
}
@Override
protected @KeepCodecResult int canKeepCodec(
MediaCodec codec, MediaCodecInfo codecInfo, Format oldFormat, Format newFormat) {
if (areAdaptationCompatible(codecInfo.adaptive, oldFormat, newFormat)
&& newFormat.width <= codecMaxValues.width
&& newFormat.height <= codecMaxValues.height
&& getMaxInputSize(newFormat) <= codecMaxValues.inputSize) {
return oldFormat.initializationDataEquals(newFormat)
? KEEP_CODEC_RESULT_YES_WITHOUT_RECONFIGURATION
: KEEP_CODEC_RESULT_YES_WITH_RECONFIGURATION;
}
return KEEP_CODEC_RESULT_NO;
}
@CallSuper
@Override
protected void releaseCodec() {
try {
super.releaseCodec();
} finally {
buffersInCodecCount = 0;
if (dummySurface != null) {
if (surface == dummySurface) {
surface = null;
}
dummySurface.release();
dummySurface = null;
}
}
}
@CallSuper
@Override
protected void flushCodec() throws ExoPlaybackException {
super.flushCodec();
buffersInCodecCount = 0;
}
@Override
protected void onCodecInitialized(String name, long initializedTimestampMs,
long initializationDurationMs) {
eventDispatcher.decoderInitialized(name, initializedTimestampMs, initializationDurationMs);
codecNeedsSetOutputSurfaceWorkaround = codecNeedsSetOutputSurfaceWorkaround(name);
}
@Override
protected void onInputFormatChanged(Format newFormat) throws ExoPlaybackException {
super.onInputFormatChanged(newFormat);
eventDispatcher.inputFormatChanged(newFormat);
pendingPixelWidthHeightRatio = newFormat.pixelWidthHeightRatio;
pendingRotationDegrees = newFormat.rotationDegrees;
}
/**
* Called immediately before an input buffer is queued into the codec.
*
* @param buffer The buffer to be queued.
*/
@CallSuper
@Override
protected void onQueueInputBuffer(DecoderInputBuffer buffer) {
buffersInCodecCount++;
lastInputTimeUs = Math.max(buffer.timeUs, lastInputTimeUs);
if (Util.SDK_INT < 23 && tunneling) {
maybeNotifyRenderedFirstFrame();
}
}
@Override
protected void onOutputFormatChanged(MediaCodec codec, MediaFormat outputFormat) {
boolean hasCrop = outputFormat.containsKey(KEY_CROP_RIGHT)
&& outputFormat.containsKey(KEY_CROP_LEFT) && outputFormat.containsKey(KEY_CROP_BOTTOM)
&& outputFormat.containsKey(KEY_CROP_TOP);
currentWidth = hasCrop
? outputFormat.getInteger(KEY_CROP_RIGHT) - outputFormat.getInteger(KEY_CROP_LEFT) + 1
: outputFormat.getInteger(MediaFormat.KEY_WIDTH);
currentHeight = hasCrop
? outputFormat.getInteger(KEY_CROP_BOTTOM) - outputFormat.getInteger(KEY_CROP_TOP) + 1
: outputFormat.getInteger(MediaFormat.KEY_HEIGHT);
currentPixelWidthHeightRatio = pendingPixelWidthHeightRatio;
if (Util.SDK_INT >= 21) {
// On API level 21 and above the decoder applies the rotation when rendering to the surface.
// Hence currentUnappliedRotation should always be 0. For 90 and 270 degree rotations, we need
// to flip the width, height and pixel aspect ratio to reflect the rotation that was applied.
if (pendingRotationDegrees == 90 || pendingRotationDegrees == 270) {
int rotatedHeight = currentWidth;
currentWidth = currentHeight;
currentHeight = rotatedHeight;
currentPixelWidthHeightRatio = 1 / currentPixelWidthHeightRatio;
}
} else {
// On API level 20 and below the decoder does not apply the rotation.
currentUnappliedRotationDegrees = pendingRotationDegrees;
}
// Must be applied each time the output format changes.
codec.setVideoScalingMode(scalingMode);
}
@Override
protected boolean processOutputBuffer(long positionUs, long elapsedRealtimeUs, MediaCodec codec,
ByteBuffer buffer, int bufferIndex, int bufferFlags, long bufferPresentationTimeUs,
boolean shouldSkip) throws ExoPlaybackException {
if (initialPositionUs == C.TIME_UNSET) {
initialPositionUs = positionUs;
}
long presentationTimeUs = bufferPresentationTimeUs - outputStreamOffsetUs;
if (shouldSkip) {
skipOutputBuffer(codec, bufferIndex, presentationTimeUs);
return true;
}
long earlyUs = bufferPresentationTimeUs - positionUs;
if (surface == dummySurface) {
// Skip frames in sync with playback, so we'll be at the right frame if the mode changes.
if (isBufferLate(earlyUs)) {
skipOutputBuffer(codec, bufferIndex, presentationTimeUs);
return true;
}
return false;
}
long elapsedRealtimeNowUs = SystemClock.elapsedRealtime() * 1000;
boolean isStarted = getState() == STATE_STARTED;
if (!renderedFirstFrame
|| (isStarted
&& shouldForceRenderOutputBuffer(earlyUs, elapsedRealtimeNowUs - lastRenderTimeUs))) {
if (Util.SDK_INT >= 21) {
renderOutputBufferV21(codec, bufferIndex, presentationTimeUs, System.nanoTime());
} else {
renderOutputBuffer(codec, bufferIndex, presentationTimeUs);
}
return true;
}
if (!isStarted || positionUs == initialPositionUs) {
return false;
}
// Fine-grained adjustment of earlyUs based on the elapsed time since the start of the current
// iteration of the rendering loop.
long elapsedSinceStartOfLoopUs = elapsedRealtimeNowUs - elapsedRealtimeUs;
earlyUs -= elapsedSinceStartOfLoopUs;
// Compute the buffer's desired release time in nanoseconds.
long systemTimeNs = System.nanoTime();
long unadjustedFrameReleaseTimeNs = systemTimeNs + (earlyUs * 1000);
// Apply a timestamp adjustment, if there is one.
long adjustedReleaseTimeNs = frameReleaseTimeHelper.adjustReleaseTime(
bufferPresentationTimeUs, unadjustedFrameReleaseTimeNs);
earlyUs = (adjustedReleaseTimeNs - systemTimeNs) / 1000;
if (shouldDropBuffersToKeyframe(earlyUs, elapsedRealtimeUs)
&& maybeDropBuffersToKeyframe(codec, bufferIndex, presentationTimeUs, positionUs)) {
return false;
} else if (shouldDropOutputBuffer(earlyUs, elapsedRealtimeUs)) {
dropOutputBuffer(codec, bufferIndex, presentationTimeUs);
return true;
}
if (Util.SDK_INT >= 21) {
// Let the underlying framework time the release.
if (earlyUs < 50000) {
renderOutputBufferV21(codec, bufferIndex, presentationTimeUs, adjustedReleaseTimeNs);
return true;
}
} else {
// We need to time the release ourselves.
if (earlyUs < 30000) {
if (earlyUs > 11000) {
// We're a little too early to render the frame. Sleep until the frame can be rendered.
// Note: The 11ms threshold was chosen fairly arbitrarily.
try {
// Subtracting 10000 rather than 11000 ensures the sleep time will be at least 1ms.
Thread.sleep((earlyUs - 10000) / 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
renderOutputBuffer(codec, bufferIndex, presentationTimeUs);
return true;
}
}
// We're either not playing, or it's not time to render the frame yet.
return false;
}
/**
* Called when an output buffer is successfully processed.
*
* @param presentationTimeUs The timestamp associated with the output buffer.
*/
@CallSuper
@Override
protected void onProcessedOutputBuffer(long presentationTimeUs) {
buffersInCodecCount--;
while (pendingOutputStreamOffsetCount != 0
&& presentationTimeUs >= pendingOutputStreamSwitchTimesUs[0]) {
outputStreamOffsetUs = pendingOutputStreamOffsetsUs[0];
pendingOutputStreamOffsetCount--;
System.arraycopy(
pendingOutputStreamOffsetsUs,
/* srcPos= */ 1,
pendingOutputStreamOffsetsUs,
/* destPos= */ 0,
pendingOutputStreamOffsetCount);
System.arraycopy(
pendingOutputStreamSwitchTimesUs,
/* srcPos= */ 1,
pendingOutputStreamSwitchTimesUs,
/* destPos= */ 0,
pendingOutputStreamOffsetCount);
}
}
/**
* Returns whether the buffer being processed should be dropped.
*
* @param earlyUs The time until the buffer should be presented in microseconds. A negative value
* indicates that the buffer is late.
* @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds,
* measured at the start of the current iteration of the rendering loop.
*/
protected boolean shouldDropOutputBuffer(long earlyUs, long elapsedRealtimeUs) {
return isBufferLate(earlyUs);
}
/**
* Returns whether to drop all buffers from the buffer being processed to the keyframe at or after
* the current playback position, if possible.
*
* @param earlyUs The time until the current buffer should be presented in microseconds. A
* negative value indicates that the buffer is late.
* @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds,
* measured at the start of the current iteration of the rendering loop.
*/
protected boolean shouldDropBuffersToKeyframe(long earlyUs, long elapsedRealtimeUs) {
return isBufferVeryLate(earlyUs);
}
/**
* Returns whether to force rendering an output buffer.
*
* @param earlyUs The time until the current buffer should be presented in microseconds. A
* negative value indicates that the buffer is late.
* @param elapsedSinceLastRenderUs The elapsed time since the last output buffer was rendered, in
* microseconds.
* @return Returns whether to force rendering an output buffer.
*/
protected boolean shouldForceRenderOutputBuffer(long earlyUs, long elapsedSinceLastRenderUs) {
return isBufferLate(earlyUs) && elapsedSinceLastRenderUs > 100000;
}
/**
* Skips the output buffer with the specified index.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to skip.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void skipOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
TraceUtil.beginSection("skipVideoBuffer");
codec.releaseOutputBuffer(index, false);
TraceUtil.endSection();
decoderCounters.skippedOutputBufferCount++;
}
/**
* Drops the output buffer with the specified index.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void dropOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
TraceUtil.beginSection("dropVideoBuffer");
codec.releaseOutputBuffer(index, false);
TraceUtil.endSection();
updateDroppedBufferCounters(1);
}
/**
* Drops frames from the current output buffer to the next keyframe at or before the playback
* position. If no such keyframe exists, as the playback position is inside the same group of
* pictures as the buffer being processed, returns {@code false}. Returns {@code true} otherwise.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
* @param positionUs The current playback position, in microseconds.
* @return Whether any buffers were dropped.
* @throws ExoPlaybackException If an error occurs flushing the codec.
*/
protected boolean maybeDropBuffersToKeyframe(MediaCodec codec, int index, long presentationTimeUs,
long positionUs) throws ExoPlaybackException {
int droppedSourceBufferCount = skipSource(positionUs);
if (droppedSourceBufferCount == 0) {
return false;
}
decoderCounters.droppedToKeyframeCount++;
// We dropped some buffers to catch up, so update the decoder counters and flush the codec,
// which releases all pending buffers buffers including the current output buffer.
updateDroppedBufferCounters(buffersInCodecCount + droppedSourceBufferCount);
flushCodec();
return true;
}
/**
* Updates decoder counters to reflect that {@code droppedBufferCount} additional buffers were
* dropped.
*
* @param droppedBufferCount The number of additional dropped buffers.
*/
protected void updateDroppedBufferCounters(int droppedBufferCount) {
decoderCounters.droppedBufferCount += droppedBufferCount;
droppedFrames += droppedBufferCount;
consecutiveDroppedFrameCount += droppedBufferCount;
decoderCounters.maxConsecutiveDroppedBufferCount = Math.max(consecutiveDroppedFrameCount,
decoderCounters.maxConsecutiveDroppedBufferCount);
if (droppedFrames >= maxDroppedFramesToNotify) {
maybeNotifyDroppedFrames();
}
}
/**
* Renders the output buffer with the specified index. This method is only called if the platform
* API version of the device is less than 21.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
*/
protected void renderOutputBuffer(MediaCodec codec, int index, long presentationTimeUs) {
maybeNotifyVideoSizeChanged();
TraceUtil.beginSection("releaseOutputBuffer");
codec.releaseOutputBuffer(index, true);
TraceUtil.endSection();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
decoderCounters.renderedOutputBufferCount++;
consecutiveDroppedFrameCount = 0;
maybeNotifyRenderedFirstFrame();
}
/**
* Renders the output buffer with the specified index. This method is only called if the platform
* API version of the device is 21 or later.
*
* @param codec The codec that owns the output buffer.
* @param index The index of the output buffer to drop.
* @param presentationTimeUs The presentation time of the output buffer, in microseconds.
* @param releaseTimeNs The wallclock time at which the frame should be displayed, in nanoseconds.
*/
@TargetApi(21)
protected void renderOutputBufferV21(
MediaCodec codec, int index, long presentationTimeUs, long releaseTimeNs) {
maybeNotifyVideoSizeChanged();
TraceUtil.beginSection("releaseOutputBuffer");
codec.releaseOutputBuffer(index, releaseTimeNs);
TraceUtil.endSection();
lastRenderTimeUs = SystemClock.elapsedRealtime() * 1000;
decoderCounters.renderedOutputBufferCount++;
consecutiveDroppedFrameCount = 0;
maybeNotifyRenderedFirstFrame();
}
private boolean shouldUseDummySurface(MediaCodecInfo codecInfo) {
return Util.SDK_INT >= 23
&& !tunneling
&& !codecNeedsSetOutputSurfaceWorkaround(codecInfo.name)
&& (!codecInfo.secure || DummySurface.isSecureSupported(context));
}
private void setJoiningDeadlineMs() {
joiningDeadlineMs = allowedJoiningTimeMs > 0
? (SystemClock.elapsedRealtime() + allowedJoiningTimeMs) : C.TIME_UNSET;
}
private void clearRenderedFirstFrame() {
renderedFirstFrame = false;
// The first frame notification is triggered by renderOutputBuffer or renderOutputBufferV21 for
// non-tunneled playback, onQueueInputBuffer for tunneled playback prior to API level 23, and
// OnFrameRenderedListenerV23.onFrameRenderedListener for tunneled playback on API level 23 and
// above.
if (Util.SDK_INT >= 23 && tunneling) {
MediaCodec codec = getCodec();
// If codec is null then the listener will be instantiated in configureCodec.
if (codec != null) {
tunnelingOnFrameRenderedListener = new OnFrameRenderedListenerV23(codec);
}
}
}
/* package */ void maybeNotifyRenderedFirstFrame() {
if (!renderedFirstFrame) {
renderedFirstFrame = true;
eventDispatcher.renderedFirstFrame(surface);
}
}
private void maybeRenotifyRenderedFirstFrame() {
if (renderedFirstFrame) {
eventDispatcher.renderedFirstFrame(surface);
}
}
private void clearReportedVideoSize() {
reportedWidth = Format.NO_VALUE;
reportedHeight = Format.NO_VALUE;
reportedPixelWidthHeightRatio = Format.NO_VALUE;
reportedUnappliedRotationDegrees = Format.NO_VALUE;
}
private void maybeNotifyVideoSizeChanged() {
if ((currentWidth != Format.NO_VALUE || currentHeight != Format.NO_VALUE)
&& (reportedWidth != currentWidth || reportedHeight != currentHeight
|| reportedUnappliedRotationDegrees != currentUnappliedRotationDegrees
|| reportedPixelWidthHeightRatio != currentPixelWidthHeightRatio)) {
eventDispatcher.videoSizeChanged(currentWidth, currentHeight, currentUnappliedRotationDegrees,
currentPixelWidthHeightRatio);
reportedWidth = currentWidth;
reportedHeight = currentHeight;
reportedUnappliedRotationDegrees = currentUnappliedRotationDegrees;
reportedPixelWidthHeightRatio = currentPixelWidthHeightRatio;
}
}
private void maybeRenotifyVideoSizeChanged() {
if (reportedWidth != Format.NO_VALUE || reportedHeight != Format.NO_VALUE) {
eventDispatcher.videoSizeChanged(reportedWidth, reportedHeight,
reportedUnappliedRotationDegrees, reportedPixelWidthHeightRatio);
}
}
private void maybeNotifyDroppedFrames() {
if (droppedFrames > 0) {
long now = SystemClock.elapsedRealtime();
long elapsedMs = now - droppedFrameAccumulationStartTimeMs;
eventDispatcher.droppedFrames(droppedFrames, elapsedMs);
droppedFrames = 0;
droppedFrameAccumulationStartTimeMs = now;
}
}
private static boolean isBufferLate(long earlyUs) {
// Class a buffer as late if it should have been presented more than 30 ms ago.
return earlyUs < -30000;
}
private static boolean isBufferVeryLate(long earlyUs) {
// Class a buffer as very late if it should have been presented more than 500 ms ago.
return earlyUs < -500000;
}
@TargetApi(23)
private static void setOutputSurfaceV23(MediaCodec codec, Surface surface) {
codec.setOutputSurface(surface);
}
@TargetApi(21)
private static void configureTunnelingV21(MediaFormat mediaFormat, int tunnelingAudioSessionId) {
mediaFormat.setFeatureEnabled(CodecCapabilities.FEATURE_TunneledPlayback, true);
mediaFormat.setInteger(MediaFormat.KEY_AUDIO_SESSION_ID, tunnelingAudioSessionId);
}
/**
* Returns the framework {@link MediaFormat} that should be used to configure the decoder.
*
* @param format The format of media.
* @param codecMaxValues Codec max values that should be used when configuring the decoder.
* @param deviceNeedsAutoFrcWorkaround Whether the device is known to enable frame-rate conversion
* logic that negatively impacts ExoPlayer.
* @param tunnelingAudioSessionId The audio session id to use for tunneling, or {@link
* C#AUDIO_SESSION_ID_UNSET} if tunneling should not be enabled.
* @return The framework {@link MediaFormat} that should be used to configure the decoder.
*/
@SuppressLint("InlinedApi")
protected MediaFormat getMediaFormat(
Format format,
CodecMaxValues codecMaxValues,
boolean deviceNeedsAutoFrcWorkaround,
int tunnelingAudioSessionId) {
MediaFormat mediaFormat = new MediaFormat();
// Set format parameters that should always be set.
mediaFormat.setString(MediaFormat.KEY_MIME, format.sampleMimeType);
mediaFormat.setInteger(MediaFormat.KEY_WIDTH, format.width);
mediaFormat.setInteger(MediaFormat.KEY_HEIGHT, format.height);
MediaFormatUtil.setCsdBuffers(mediaFormat, format.initializationData);
// Set format parameters that may be unset.
MediaFormatUtil.maybeSetFloat(mediaFormat, MediaFormat.KEY_FRAME_RATE, format.frameRate);
MediaFormatUtil.maybeSetInteger(mediaFormat, MediaFormat.KEY_ROTATION, format.rotationDegrees);
MediaFormatUtil.maybeSetColorInfo(mediaFormat, format.colorInfo);
// Set codec max values.
mediaFormat.setInteger(MediaFormat.KEY_MAX_WIDTH, codecMaxValues.width);
mediaFormat.setInteger(MediaFormat.KEY_MAX_HEIGHT, codecMaxValues.height);
MediaFormatUtil.maybeSetInteger(
mediaFormat, MediaFormat.KEY_MAX_INPUT_SIZE, codecMaxValues.inputSize);
// Set codec configuration values.
if (Util.SDK_INT >= 23) {
mediaFormat.setInteger(MediaFormat.KEY_PRIORITY, 0 /* realtime priority */);
}
if (deviceNeedsAutoFrcWorkaround) {
mediaFormat.setInteger("auto-frc", 0);
}
if (tunnelingAudioSessionId != C.AUDIO_SESSION_ID_UNSET) {
configureTunnelingV21(mediaFormat, tunnelingAudioSessionId);
}
return mediaFormat;
}
/**
* Returns {@link CodecMaxValues} suitable for configuring a codec for {@code format} in a way
* that will allow possible adaptation to other compatible formats in {@code streamFormats}.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param format The format for which the codec is being configured.
* @param streamFormats The possible stream formats.
* @return Suitable {@link CodecMaxValues}.
* @throws DecoderQueryException If an error occurs querying {@code codecInfo}.
*/
protected CodecMaxValues getCodecMaxValues(
MediaCodecInfo codecInfo, Format format, Format[] streamFormats)
throws DecoderQueryException {
int maxWidth = format.width;
int maxHeight = format.height;
int maxInputSize = getMaxInputSize(format);
if (streamFormats.length == 1) {
// The single entry in streamFormats must correspond to the format for which the codec is
// being configured.
return new CodecMaxValues(maxWidth, maxHeight, maxInputSize);
}
boolean haveUnknownDimensions = false;
for (Format streamFormat : streamFormats) {
if (areAdaptationCompatible(codecInfo.adaptive, format, streamFormat)) {
haveUnknownDimensions |=
(streamFormat.width == Format.NO_VALUE || streamFormat.height == Format.NO_VALUE);
maxWidth = Math.max(maxWidth, streamFormat.width);
maxHeight = Math.max(maxHeight, streamFormat.height);
maxInputSize = Math.max(maxInputSize, getMaxInputSize(streamFormat));
}
}
if (haveUnknownDimensions) {
Log.w(TAG, "Resolutions unknown. Codec max resolution: " + maxWidth + "x" + maxHeight);
Point codecMaxSize = getCodecMaxSize(codecInfo, format);
if (codecMaxSize != null) {
maxWidth = Math.max(maxWidth, codecMaxSize.x);
maxHeight = Math.max(maxHeight, codecMaxSize.y);
maxInputSize =
Math.max(maxInputSize, getMaxInputSize(format.sampleMimeType, maxWidth, maxHeight));
Log.w(TAG, "Codec max resolution adjusted to: " + maxWidth + "x" + maxHeight);
}
}
return new CodecMaxValues(maxWidth, maxHeight, maxInputSize);
}
/**
* Returns a maximum video size to use when configuring a codec for {@code format} in a way
* that will allow possible adaptation to other compatible formats that are expected to have the
* same aspect ratio, but whose sizes are unknown.
*
* @param codecInfo Information about the {@link MediaCodec} being configured.
* @param format The format for which the codec is being configured.
* @return The maximum video size to use, or null if the size of {@code format} should be used.
* @throws DecoderQueryException If an error occurs querying {@code codecInfo}.
*/
private static Point getCodecMaxSize(MediaCodecInfo codecInfo, Format format)
throws DecoderQueryException {
boolean isVerticalVideo = format.height > format.width;
int formatLongEdgePx = isVerticalVideo ? format.height : format.width;
int formatShortEdgePx = isVerticalVideo ? format.width : format.height;
float aspectRatio = (float) formatShortEdgePx / formatLongEdgePx;
for (int longEdgePx : STANDARD_LONG_EDGE_VIDEO_PX) {
int shortEdgePx = (int) (longEdgePx * aspectRatio);
if (longEdgePx <= formatLongEdgePx || shortEdgePx <= formatShortEdgePx) {
// Don't return a size not larger than the format for which the codec is being configured.
return null;
} else if (Util.SDK_INT >= 21) {
Point alignedSize = codecInfo.alignVideoSizeV21(isVerticalVideo ? shortEdgePx : longEdgePx,
isVerticalVideo ? longEdgePx : shortEdgePx);
float frameRate = format.frameRate;
if (codecInfo.isVideoSizeAndRateSupportedV21(alignedSize.x, alignedSize.y, frameRate)) {
return alignedSize;
}
} else {
// Conservatively assume the codec requires 16px width and height alignment.
longEdgePx = Util.ceilDivide(longEdgePx, 16) * 16;
shortEdgePx = Util.ceilDivide(shortEdgePx, 16) * 16;
if (longEdgePx * shortEdgePx <= MediaCodecUtil.maxH264DecodableFrameSize()) {
return new Point(isVerticalVideo ? shortEdgePx : longEdgePx,
isVerticalVideo ? longEdgePx : shortEdgePx);
}
}
}
return null;
}
/**
* Returns a maximum input buffer size for a given format.
*
* @param format The format.
* @return A maximum input buffer size in bytes, or {@link Format#NO_VALUE} if a maximum could not
* be determined.
*/
private static int getMaxInputSize(Format format) {
if (format.maxInputSize != Format.NO_VALUE) {
// The format defines an explicit maximum input size. Add the total size of initialization
// data buffers, as they may need to be queued in the same input buffer as the largest sample.
int totalInitializationDataSize = 0;
int initializationDataCount = format.initializationData.size();
for (int i = 0; i < initializationDataCount; i++) {
totalInitializationDataSize += format.initializationData.get(i).length;
}
return format.maxInputSize + totalInitializationDataSize;
} else {
// Calculated maximum input sizes are overestimates, so it's not necessary to add the size of
// initialization data.
return getMaxInputSize(format.sampleMimeType, format.width, format.height);
}
}
/**
* Returns a maximum input size for a given mime type, width and height.
*
* @param sampleMimeType The format mime type.
* @param width The width in pixels.
* @param height The height in pixels.
* @return A maximum input size in bytes, or {@link Format#NO_VALUE} if a maximum could not be
* determined.
*/
private static int getMaxInputSize(String sampleMimeType, int width, int height) {
if (width == Format.NO_VALUE || height == Format.NO_VALUE) {
// We can't infer a maximum input size without video dimensions.
return Format.NO_VALUE;
}
// Attempt to infer a maximum input size from the format.
int maxPixels;
int minCompressionRatio;
switch (sampleMimeType) {
case MimeTypes.VIDEO_H263:
case MimeTypes.VIDEO_MP4V:
maxPixels = width * height;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_H264:
if ("BRAVIA 4K 2015".equals(Util.MODEL)) {
// The Sony BRAVIA 4k TV has input buffers that are too small for the calculated 4k video
// maximum input size, so use the default value.
return Format.NO_VALUE;
}
// Round up width/height to an integer number of macroblocks.
maxPixels = Util.ceilDivide(width, 16) * Util.ceilDivide(height, 16) * 16 * 16;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_VP8:
// VPX does not specify a ratio so use the values from the platform's SoftVPX.cpp.
maxPixels = width * height;
minCompressionRatio = 2;
break;
case MimeTypes.VIDEO_H265:
case MimeTypes.VIDEO_VP9:
maxPixels = width * height;
minCompressionRatio = 4;
break;
default:
// Leave the default max input size.
return Format.NO_VALUE;
}
// Estimate the maximum input size assuming three channel 4:2:0 subsampled input frames.
return (maxPixels * 3) / (2 * minCompressionRatio);
}
/**
* Returns whether a codec with suitable {@link CodecMaxValues} will support adaptation between
* two {@link Format}s.
*
* @param codecIsAdaptive Whether the codec supports seamless resolution switches.
* @param first The first format.
* @param second The second format.
* @return Whether the codec will support adaptation between the two {@link Format}s.
*/
private static boolean areAdaptationCompatible(
boolean codecIsAdaptive, Format first, Format second) {
return first.sampleMimeType.equals(second.sampleMimeType)
&& first.rotationDegrees == second.rotationDegrees
&& (codecIsAdaptive || (first.width == second.width && first.height == second.height))
&& Util.areEqual(first.colorInfo, second.colorInfo);
}
/**
* Returns whether the device is known to enable frame-rate conversion logic that negatively
* impacts ExoPlayer.
* <p>
* If true is returned then we explicitly disable the feature.
*
* @return True if the device is known to enable frame-rate conversion logic that negatively
* impacts ExoPlayer. False otherwise.
*/
private static boolean deviceNeedsAutoFrcWorkaround() {
// nVidia Shield prior to M tries to adjust the playback rate to better map the frame-rate of
// content to the refresh rate of the display. For example playback of 23.976fps content is
// adjusted to play at 1.001x speed when the output display is 60Hz. Unfortunately the
// implementation causes ExoPlayer's reported playback position to drift out of sync. Captions
// also lose sync [Internal: b/26453592].
return Util.SDK_INT <= 22 && "foster".equals(Util.DEVICE) && "NVIDIA".equals(Util.MANUFACTURER);
}
/**
* Returns whether the device is known to implement {@link MediaCodec#setOutputSurface(Surface)}
* incorrectly.
* <p>
* If true is returned then we fall back to releasing and re-instantiating the codec instead.
*/
private static boolean codecNeedsSetOutputSurfaceWorkaround(String name) {
// Work around https://github.com/google/ExoPlayer/issues/3236,
// https://github.com/google/ExoPlayer/issues/3355,
// https://github.com/google/ExoPlayer/issues/3439,
// https://github.com/google/ExoPlayer/issues/3724,
// https://github.com/google/ExoPlayer/issues/3835,
// https://github.com/google/ExoPlayer/issues/4006,
// https://github.com/google/ExoPlayer/issues/4084,
// https://github.com/google/ExoPlayer/issues/4104.
// https://github.com/google/ExoPlayer/issues/4134.
return (("deb".equals(Util.DEVICE) // Nexus 7 (2013)
|| "flo".equals(Util.DEVICE) // Nexus 7 (2013)
|| "mido".equals(Util.DEVICE) // Redmi Note 4
|| "santoni".equals(Util.DEVICE)) // Redmi 4X
&& "OMX.qcom.video.decoder.avc".equals(name))
|| (("tcl_eu".equals(Util.DEVICE) // TCL Percee TV
|| "SVP-DTV15".equals(Util.DEVICE) // Sony Bravia 4K 2015
|| "BRAVIA_ATV2".equals(Util.DEVICE) // Sony Bravia 4K GB
|| Util.DEVICE.startsWith("panell_") // Motorola Moto C Plus
|| "F3311".equals(Util.DEVICE) // Sony Xperia E5
|| "M5c".equals(Util.DEVICE) // Meizu M5C
|| "QM16XE_U".equals(Util.DEVICE) // Philips QM163E
|| "A7010a48".equals(Util.DEVICE) // Lenovo K4 Note
|| "woods_f".equals(Util.MODEL)) // Moto E (4)
&& "OMX.MTK.VIDEO.DECODER.AVC".equals(name))
|| (("ALE-L21".equals(Util.MODEL) // Huawei P8 Lite
|| "CAM-L21".equals(Util.MODEL)) // Huawei Y6II
&& "OMX.k3.video.decoder.avc".equals(name))
|| (("HUAWEI VNS-L21".equals(Util.MODEL)) // Huawei P9 Lite
&& "OMX.IMG.MSVDX.Decoder.AVC".equals(name));
}
protected static final class CodecMaxValues {
public final int width;
public final int height;
public final int inputSize;
public CodecMaxValues(int width, int height, int inputSize) {
this.width = width;
this.height = height;
this.inputSize = inputSize;
}
}
@TargetApi(23)
private final class OnFrameRenderedListenerV23 implements MediaCodec.OnFrameRenderedListener {
private OnFrameRenderedListenerV23(MediaCodec codec) {
codec.setOnFrameRenderedListener(this, new Handler());
}
@Override
public void onFrameRendered(@NonNull MediaCodec codec, long presentationTimeUs, long nanoTime) {
if (this != tunnelingOnFrameRenderedListener) {
// Stale event.
return;
}
maybeNotifyRenderedFirstFrame();
}
}
}
| Blacklist Moto C from setOutputSurface
Issue: #4315
| library/core/src/main/java/com/google/android/exoplayer2/video/MediaCodecVideoRenderer.java | Blacklist Moto C from setOutputSurface | <ide><path>ibrary/core/src/main/java/com/google/android/exoplayer2/video/MediaCodecVideoRenderer.java
<ide> // https://github.com/google/ExoPlayer/issues/4084,
<ide> // https://github.com/google/ExoPlayer/issues/4104.
<ide> // https://github.com/google/ExoPlayer/issues/4134.
<add> // https://github.com/google/ExoPlayer/issues/4315
<ide> return (("deb".equals(Util.DEVICE) // Nexus 7 (2013)
<ide> || "flo".equals(Util.DEVICE) // Nexus 7 (2013)
<ide> || "mido".equals(Util.DEVICE) // Redmi Note 4
<ide> || "M5c".equals(Util.DEVICE) // Meizu M5C
<ide> || "QM16XE_U".equals(Util.DEVICE) // Philips QM163E
<ide> || "A7010a48".equals(Util.DEVICE) // Lenovo K4 Note
<del> || "woods_f".equals(Util.MODEL)) // Moto E (4)
<add> || "woods_f".equals(Util.MODEL) // Moto E (4)
<add> || "watson".equals(Util.DEVICE)) // Moto C
<ide> && "OMX.MTK.VIDEO.DECODER.AVC".equals(name))
<ide> || (("ALE-L21".equals(Util.MODEL) // Huawei P8 Lite
<ide> || "CAM-L21".equals(Util.MODEL)) // Huawei Y6II |
|
Java | bsd-3-clause | 9d1cf28e89020d58678cbf13da7f99c0badbce6a | 0 | picocontainer/NanoContainer,picocontainer/NanoContainer,picocontainer/NanoContainer,picocontainer/NanoContainer | package org.nanocontainer.script.groovy;
import org.jmock.Mock;
import org.nanocontainer.integrationkit.PicoCompositionException;
import org.nanocontainer.reflection.DefaultNanoPicoContainer;
import org.nanocontainer.script.AbstractScriptedContainerBuilderTestCase;
import org.nanocontainer.script.NanoContainerMarkupException;
import org.picocontainer.PicoContainer;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.defaults.ComponentAdapterFactory;
import org.picocontainer.defaults.InstanceComponentAdapter;
import org.picocontainer.defaults.UnsatisfiableDependenciesException;
import java.io.Reader;
import java.io.StringReader;
/**
* Test with groovy jsr parser
*
* @author Paul Hammant
* @author Mauro Talevi
* @version $Revision: 1775 $
*/
public class NanoContainerBuilderJsrTestCase extends AbstractScriptedContainerBuilderTestCase {
public void testInstantiateBasicScriptable() throws PicoCompositionException {
Reader script = new StringReader("" +
"import org.nanocontainer.script.groovy.X\n" +
"import org.nanocontainer.script.groovy.A\n" +
"X.reset()\n" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(A)\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
// LifecyleContainerBuilder starts the container
pico.dispose();
assertEquals("Should match the expression", "<A!A", X.componentRecorder);
}
public void testComponentInstances() throws PicoCompositionException {
Reader script = new StringReader("" +
"import org.nanocontainer.script.groovy.A\n" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'a', instance:'apple')\n" +
" component(key:'b', instance:'banana')\n" +
" component(instance:'noKeySpecified')\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
assertEquals("apple", pico.getComponentInstance("a"));
assertEquals("banana", pico.getComponentInstance("b"));
assertEquals("noKeySpecified", pico.getComponentInstance(String.class));
}
public void testShouldFailWhenNeitherClassNorInstanceIsSpecifiedForComponent() {
Reader script = new StringReader("" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'a')\n" +
"}");
try {
buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
fail("NanoContainerMarkupException should have been raised");
} catch (NanoContainerMarkupException e) {
// expected
}
}
public void testShouldAcceptConstantParametersForComponent() throws PicoCompositionException {
Reader script = new StringReader("" +
"import org.picocontainer.defaults.ConstantParameter\n" +
"import org.nanocontainer.script.groovy.HasParams\n" +
"" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'byClass', class:HasParams, parameters:[ 'a', 'b', new ConstantParameter('c') ])\n" +
" component(key:'byClassString', class:'org.nanocontainer.script.groovy.HasParams', parameters:[ 'c', 'a', 't' ])\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
HasParams byClass = (HasParams) pico.getComponentInstance("byClass");
assertEquals("abc", byClass.getParams());
HasParams byClassString = (HasParams) pico.getComponentInstance("byClassString");
assertEquals("cat", byClassString.getParams());
}
public void testShouldAcceptComponentParametersForComponent() throws PicoCompositionException {
Reader script = new StringReader("" +
"import org.picocontainer.defaults.ComponentParameter\n" +
"import org.nanocontainer.script.groovy.A\n" +
"import org.nanocontainer.script.groovy.B\n" +
"" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'a1', class:A)\n" +
" component(key:'a2', class:A)\n" +
" component(key:'b1', class:B, parameters:[ new ComponentParameter('a1') ])\n" +
" component(key:'b2', class:B, parameters:[ new ComponentParameter('a2') ])\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
A a1 = (A) pico.getComponentInstance("a1");
A a2 = (A) pico.getComponentInstance("a2");
B b1 = (B) pico.getComponentInstance("b1");
B b2 = (B) pico.getComponentInstance("b2");
assertNotNull(a1);
assertNotNull(a2);
assertNotNull(b1);
assertNotNull(b2);
assertSame(a1, b1.a);
assertSame(a2, b2.a);
assertNotSame(a1, a2);
assertNotSame(b1, b2);
}
public void testShouldAcceptComponentParameterWithClassNameKey() throws PicoCompositionException {
Reader script = new StringReader("" +
"import org.picocontainer.defaults.ComponentParameter\n" +
"import org.nanocontainer.script.groovy.A\n" +
"import org.nanocontainer.script.groovy.B\n" +
"" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(class:A)\n" +
" component(key:B, class:B, parameters:[ new ComponentParameter(A) ])\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
A a = (A) pico.getComponentInstance(A.class);
B b = (B) pico.getComponentInstance(B.class);
assertNotNull(a);
assertNotNull(b);
assertSame(a, b.a);
}
public void testComponentParametersScript() {
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"import org.picocontainer.defaults.ComponentParameter\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'a', class:A)\n" +
" component(key:'b', class:B, parameters:[ new ComponentParameter('a') ])\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
A a = (A) pico.getComponentInstance("a");
B b = (B) pico.getComponentInstance("b");
assertSame(a, b.a);
}
public void testShouldBeAbleToHandOffToNestedBuilder() {
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'a', class:A)\n" +
" newBuilder(class:'org.nanocontainer.script.groovy.TestingChildBuilder') {\n" +
" component(key:'b', class:B)\n" +
" }\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
Object a = pico.getComponentInstance("a");
Object b = pico.getComponentInstance("b");
assertNotNull(a);
assertNotNull(b);
}
public void testInstantiateBasicComponentInDeeperTree() {
X.reset();
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" container() {\n" +
" component(A)\n" +
" }\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
pico.dispose();
assertEquals("Should match the expression", "<A!A", X.componentRecorder);
}
public void testShouldBeAbleToSpecifyCustomCompoentAdapterFactory() {
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container(componentAdapterFactory:assemblyScope) {\n" +
" component(A)\n" +
"}");
A a = new A();
Mock cafMock = mock(ComponentAdapterFactory.class);
cafMock.expects(once()).method("createComponentAdapter").with(same(A.class), same(A.class), eq(null)).will(returnValue(new InstanceComponentAdapter(A.class, a)));
ComponentAdapterFactory componentAdapterFactory = (ComponentAdapterFactory) cafMock.proxy();
PicoContainer picoContainer = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, componentAdapterFactory);
assertSame(a, picoContainer.getComponentInstanceOfType(A.class));
}
public void testInstantiateWithImpossibleComponentDependenciesConsideringTheHierarchy() {
X.reset();
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(B)\n" +
" container() {\n" +
" component(A)\n" +
" }\n" +
" component(C)\n" +
"}");
try {
buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
fail("Should not have been able to instansiate component tree due to visibility/parent reasons.");
} catch (UnsatisfiableDependenciesException expected) {
}
}
public void testInstantiateWithChildContainerAndStartStopAndDisposeOrderIsCorrect() {
X.reset();
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(A)\n" +
" container() {\n" +
" component(B)\n" +
" }\n" +
" component(C)\n" +
"}\n");
// A and C have no no dependancies. B Depends on A.
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
//pico.start();
pico.stop();
pico.dispose();
assertEquals("Should match the expression", "<A<C<BB>C>A>!B!C!A", X.componentRecorder);
}
public void testBuildContainerWithParentAttribute() {
DefaultNanoPicoContainer parent = new DefaultNanoPicoContainer();
parent.registerComponentInstance("hello", "world");
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"nano = new NanoContainerBuilder().container(parent:parent) {\n" +
" component(A)\n" +
"}\n");
PicoContainer pico = buildContainer(
new GroovyContainerBuilder(script, getClass().getClassLoader()),
parent,
"SOME_SCOPE");
// Should be able to get instance that was registered in the parent container
assertEquals("world", pico.getComponentInstance("hello"));
}
public void testExceptionThrownWhenParentAttributeDefinedWithinChild() {
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"nano = new NanoContainerBuilder().container() {\n" +
" component(A)\n" +
" container(parent:parent) {\n" +
" component(B)\n" +
" }\n" +
"}\n");
try {
buildContainer(
new GroovyContainerBuilder(script, getClass().getClassLoader()),
new DefaultNanoPicoContainer(),
"SOME_SCOPE");
fail("NanoContainerMarkupException should have been thrown.");
} catch (NanoContainerMarkupException ignore) {
// ignore
}
}
public void testWithDynamicClassPathThatDoesNotExist() {
DefaultNanoPicoContainer parent = new DefaultNanoPicoContainer();
try {
Reader script = new StringReader("" +
" child = null\n" +
" pico = builder.container {\n" +
" classPathElement(path:'this/path/does/not/exist.jar')\n" +
" component(class:\"FooBar\") " +
" }" +
"");
buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()),
parent,
"SOME_SCOPE");
fail("should have barfed with bad path exception");
} catch (NanoContainerMarkupException e) {
// excpected
}
}
public void testWithDynamicClassPath() {
DefaultNanoPicoContainer parent = new DefaultNanoPicoContainer();
Reader script = new StringReader("" +
" File testCompJar = new File(System.getProperty(\"testcomp.jar\"))\n" +
" compJarPath = testCompJar.getCanonicalPath()\n" +
" child = null\n" +
" pico = builder.container {\n" +
" classPathElement(path:compJarPath)\n" +
" component(class:\"TestComp\")\n" +
" }" +
"");
MutablePicoContainer pico = (MutablePicoContainer) buildContainer(
new GroovyContainerBuilder(script, getClass().getClassLoader()),
parent,
"SOME_SCOPE");
assertTrue(pico.getComponentInstances().size() == 1);
assertEquals("TestComp",pico.getComponentInstances().get(0).getClass().getName());
}
public void testWithDynamicClassPathWithPermissions() {
DefaultNanoPicoContainer parent = new DefaultNanoPicoContainer();
Reader script = new StringReader("" +
" File testCompJar = new File(System.getProperty(\"testcomp.jar\"))\n" +
" compJarPath = testCompJar.getCanonicalPath()\n" +
" child = null\n" +
" pico = builder.container {\n" +
" classPathElement(path:compJarPath) {\n" +
" grant(new java.net.SocketPermission('google.com','connect'))\n" +
" }\n" +
" component(class:\"TestComp\")\n" +
" }" +
"");
MutablePicoContainer pico = (MutablePicoContainer) buildContainer(
new GroovyContainerBuilder(script, getClass().getClassLoader()),
parent,
"SOME_SCOPE");
assertTrue(pico.getComponentInstances().size() == 1);
// can't actually test the permission under JUNIT control. We're just testing the syntax here.
}
public void testGrantPermissionInWrongPlace() {
DefaultNanoPicoContainer parent = new DefaultNanoPicoContainer();
try {
Reader script = new StringReader("" +
" File testCompJar = new File(System.getProperty(\"testcomp.jar\"))\n" +
" compJarPath = testCompJar.getCanonicalPath()\n" +
" child = null\n" +
" pico = builder.container {\n" +
" grant(new java.net.SocketPermission('google.com','connect'))\n" +
" }" +
"");
buildContainer(
new GroovyContainerBuilder(script, getClass().getClassLoader()),
parent,
"SOME_SCOPE");
fail("should barf with [Don't know how to create a 'grant' child] exception");
} catch (NanoContainerMarkupException e) {
assertTrue(e.getMessage().indexOf("Don't know how to create a 'grant' child") > -1);
}
}
}
| container/src/test/org/nanocontainer/script/groovy/NanoContainerBuilderJsrTestCase.java | package org.nanocontainer.script.groovy;
import org.jmock.Mock;
import org.nanocontainer.integrationkit.PicoCompositionException;
import org.nanocontainer.reflection.DefaultNanoPicoContainer;
import org.nanocontainer.script.AbstractScriptedContainerBuilderTestCase;
import org.nanocontainer.script.NanoContainerMarkupException;
import org.picocontainer.PicoContainer;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.defaults.ComponentAdapterFactory;
import org.picocontainer.defaults.InstanceComponentAdapter;
import org.picocontainer.defaults.UnsatisfiableDependenciesException;
import java.io.Reader;
import java.io.StringReader;
/**
* Test with groovy jsr parser
*
* @author Paul Hammant
* @author Mauro Talevi
* @version $Revision: 1775 $
*/
public class NanoContainerBuilderJsrTestCase extends AbstractScriptedContainerBuilderTestCase {
public void testInstantiateBasicScriptable() throws PicoCompositionException {
Reader script = new StringReader("" +
"import org.nanocontainer.script.groovy.X\n" +
"import org.nanocontainer.script.groovy.A\n" +
"X.reset()\n" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(A)\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
// LifecyleContainerBuilder starts the container
pico.dispose();
assertEquals("Should match the expression", "<A!A", X.componentRecorder);
}
public void testComponentInstances() throws PicoCompositionException {
Reader script = new StringReader("" +
"import org.nanocontainer.script.groovy.A\n" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'a', instance:'apple')\n" +
" component(key:'b', instance:'banana')\n" +
" component(instance:'noKeySpecified')\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
assertEquals("apple", pico.getComponentInstance("a"));
assertEquals("banana", pico.getComponentInstance("b"));
assertEquals("noKeySpecified", pico.getComponentInstance(String.class));
}
public void testShouldFailWhenNeitherClassNorInstanceIsSpecifiedForComponent() {
Reader script = new StringReader("" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'a')\n" +
"}");
try {
buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
fail("NanoContainerMarkupException should have been raised");
} catch (NanoContainerMarkupException e) {
// expected
}
}
public void testShouldAcceptConstantParametersForComponent() throws PicoCompositionException {
Reader script = new StringReader("" +
"import org.picocontainer.defaults.ConstantParameter\n" +
"import org.nanocontainer.script.groovy.HasParams\n" +
"" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'byClass', class:HasParams, parameters:[ 'a', 'b', new ConstantParameter('c') ])\n" +
" component(key:'byClassString', class:'org.nanocontainer.script.groovy.HasParams', parameters:[ 'c', 'a', 't' ])\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
HasParams byClass = (HasParams) pico.getComponentInstance("byClass");
assertEquals("abc", byClass.getParams());
HasParams byClassString = (HasParams) pico.getComponentInstance("byClassString");
assertEquals("cat", byClassString.getParams());
}
public void testShouldAcceptComponentParametersForComponent() throws PicoCompositionException {
Reader script = new StringReader("" +
"import org.picocontainer.defaults.ComponentParameter\n" +
"import org.nanocontainer.script.groovy.A\n" +
"import org.nanocontainer.script.groovy.B\n" +
"" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'a1', class:A)\n" +
" component(key:'a2', class:A)\n" +
" component(key:'b1', class:B, parameters:[ new ComponentParameter('a1') ])\n" +
" component(key:'b2', class:B, parameters:[ new ComponentParameter('a2') ])\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
A a1 = (A) pico.getComponentInstance("a1");
A a2 = (A) pico.getComponentInstance("a2");
B b1 = (B) pico.getComponentInstance("b1");
B b2 = (B) pico.getComponentInstance("b2");
assertNotNull(a1);
assertNotNull(a2);
assertNotNull(b1);
assertNotNull(b2);
assertSame(a1, b1.a);
assertSame(a2, b2.a);
assertNotSame(a1, a2);
assertNotSame(b1, b2);
}
public void testShouldAcceptComponentParameterWithClassNameKey() throws PicoCompositionException {
Reader script = new StringReader("" +
"import org.picocontainer.defaults.ComponentParameter\n" +
"import org.nanocontainer.script.groovy.A\n" +
"import org.nanocontainer.script.groovy.B\n" +
"" +
"builder = new org.nanocontainer.script.groovy.NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(class:A)\n" +
" component(key:B, class:B, parameters:[ new ComponentParameter(A) ])\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
A a = (A) pico.getComponentInstance(A.class);
B b = (B) pico.getComponentInstance(B.class);
assertNotNull(a);
assertNotNull(b);
assertSame(a, b.a);
}
public void testComponentParametersScript() {
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"import org.picocontainer.defaults.ComponentParameter\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'a', class:A)\n" +
" component(key:'b', class:B, parameters:[ new ComponentParameter('a') ])\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
A a = (A) pico.getComponentInstance("a");
B b = (B) pico.getComponentInstance("b");
assertSame(a, b.a);
}
public void testShouldBeAbleToHandOffToNestedBuilder() {
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(key:'a', class:A)\n" +
" newBuilder(class:'org.nanocontainer.script.groovy.TestingChildBuilder') {\n" +
" component(key:'b', class:B)\n" +
" }\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
Object a = pico.getComponentInstance("a");
Object b = pico.getComponentInstance("b");
assertNotNull(a);
assertNotNull(b);
}
public void testInstantiateBasicComponentInDeeperTree() {
X.reset();
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" container() {\n" +
" component(A)\n" +
" }\n" +
"}");
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
pico.dispose();
assertEquals("Should match the expression", "<A!A", X.componentRecorder);
}
public void testShouldBeAbleToSpecifyCustomCompoentAdapterFactory() {
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container(componentAdapterFactory:assemblyScope) {\n" +
" component(A)\n" +
"}");
A a = new A();
Mock cafMock = mock(ComponentAdapterFactory.class);
cafMock.expects(once()).method("createComponentAdapter").with(same(A.class), same(A.class), eq(null)).will(returnValue(new InstanceComponentAdapter(A.class, a)));
ComponentAdapterFactory componentAdapterFactory = (ComponentAdapterFactory) cafMock.proxy();
PicoContainer picoContainer = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, componentAdapterFactory);
assertSame(a, picoContainer.getComponentInstanceOfType(A.class));
}
public void testInstantiateWithImpossibleComponentDependenciesConsideringTheHierarchy() {
X.reset();
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(B)\n" +
" container() {\n" +
" component(A)\n" +
" }\n" +
" component(C)\n" +
"}");
try {
buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
fail("Should not have been able to instansiate component tree due to visibility/parent reasons.");
} catch (UnsatisfiableDependenciesException expected) {
}
}
public void testInstantiateWithChildContainerAndStartStopAndDisposeOrderIsCorrect() {
X.reset();
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"builder = new NanoContainerBuilder()\n" +
"nano = builder.container {\n" +
" component(A)\n" +
" container() {\n" +
" component(B)\n" +
" }\n" +
" component(C)\n" +
"}\n");
// A and C have no no dependancies. B Depends on A.
PicoContainer pico = buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()), null, "SOME_SCOPE");
//pico.start();
pico.stop();
pico.dispose();
assertEquals("Should match the expression", "<A<C<BB>C>A>!B!C!A", X.componentRecorder);
}
public void testBuildContainerWithParentAttribute() {
DefaultNanoPicoContainer parent = new DefaultNanoPicoContainer();
parent.registerComponentInstance("hello", "world");
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"nano = new NanoContainerBuilder().container(parent:parent) {\n" +
" component(A)\n" +
"}\n");
PicoContainer pico = buildContainer(
new GroovyContainerBuilder(script, getClass().getClassLoader()),
parent,
"SOME_SCOPE");
// Should be able to get instance that was registered in the parent container
assertEquals("world", pico.getComponentInstance("hello"));
}
public void testExceptionThrownWhenParentAttributeDefinedWithinChild() {
Reader script = new StringReader("" +
"package org.nanocontainer.script.groovy\n" +
"nano = new NanoContainerBuilder().container() {\n" +
" component(A)\n" +
" container(parent:parent) {\n" +
" component(B)\n" +
" }\n" +
"}\n");
try {
buildContainer(
new GroovyContainerBuilder(script, getClass().getClassLoader()),
new DefaultNanoPicoContainer(),
"SOME_SCOPE");
fail("NanoContainerMarkupException should have been thrown.");
} catch (NanoContainerMarkupException ignore) {
// ignore
}
}
public void testWithDynamicClassPathThatDoesNotExist() {
DefaultNanoPicoContainer parent = new DefaultNanoPicoContainer();
try {
Reader script = new StringReader("" +
" child = null\n" +
" pico = builder.container {\n" +
" classPathElement(path:'this/path/does/not/exist.jar')\n" +
" component(class:\"FooBar\") " +
" }" +
"");
buildContainer(new GroovyContainerBuilder(script, getClass().getClassLoader()),
parent,
"SOME_SCOPE");
fail("should have barfed with bad path exception");
} catch (NanoContainerMarkupException e) {
// excpected
}
}
public void testWithDynamicClassPath() {
DefaultNanoPicoContainer parent = new DefaultNanoPicoContainer();
Reader script = new StringReader("" +
" File testCompJar = new File(System.getProperty(\"testcomp.jar\"))\n" +
" compJarPath = testCompJar.getCanonicalPath()\n" +
" child = null\n" +
" pico = builder.container {\n" +
" classPathElement(path:compJarPath)\n" +
" component(class:\"TestComp\")\n" +
" }" +
"");
MutablePicoContainer pico = (MutablePicoContainer) buildContainer(
new GroovyContainerBuilder(script, getClass().getClassLoader()),
parent,
"SOME_SCOPE");
assertTrue(pico.getComponentInstances().size() == 1);
assertEquals("TestComp",pico.getComponentInstances().get(0).getClass().getName());
}
public void testWithDynamicClassPathWithPermissions() {
DefaultNanoPicoContainer parent = new DefaultNanoPicoContainer();
Reader script = new StringReader("" +
" File testCompJar = new File(System.getProperty(\"testcomp.jar\"))\n" +
" compJarPath = testCompJar.getCanonicalPath()\n" +
" child = null\n" +
" pico = builder.container {\n" +
" classPathElement(path:compJarPath) {\n" +
" grant(new java.net.SocketPermission('google.com','connect'))\n" +
" }\n" +
" component(class:\"TestComp\")\n" +
" }" +
"");
MutablePicoContainer pico = (MutablePicoContainer) buildContainer(
new GroovyContainerBuilder(script, getClass().getClassLoader()),
parent,
"SOME_SCOPE");
assertTrue(pico.getComponentInstances().size() == 1);
// can;t actually test the permission under JUNIT control. We're just testing the syntax here.
}
}
| confimation that grant() in the wrong place is not allowed
git-svn-id: 12c26961da91f742cc34db10acb570e5af7eb648@2228 ac66bb80-72f5-0310-8d68-9f556cfffb23
| container/src/test/org/nanocontainer/script/groovy/NanoContainerBuilderJsrTestCase.java | confimation that grant() in the wrong place is not allowed | <ide><path>ontainer/src/test/org/nanocontainer/script/groovy/NanoContainerBuilderJsrTestCase.java
<ide>
<ide> assertTrue(pico.getComponentInstances().size() == 1);
<ide>
<del> // can;t actually test the permission under JUNIT control. We're just testing the syntax here.
<add> // can't actually test the permission under JUNIT control. We're just testing the syntax here.
<ide> }
<ide>
<add> public void testGrantPermissionInWrongPlace() {
<add> DefaultNanoPicoContainer parent = new DefaultNanoPicoContainer();
<add>
<add> try {
<add> Reader script = new StringReader("" +
<add> " File testCompJar = new File(System.getProperty(\"testcomp.jar\"))\n" +
<add> " compJarPath = testCompJar.getCanonicalPath()\n" +
<add> " child = null\n" +
<add> " pico = builder.container {\n" +
<add> " grant(new java.net.SocketPermission('google.com','connect'))\n" +
<add> " }" +
<add> "");
<add>
<add> buildContainer(
<add> new GroovyContainerBuilder(script, getClass().getClassLoader()),
<add> parent,
<add> "SOME_SCOPE");
<add> fail("should barf with [Don't know how to create a 'grant' child] exception");
<add> } catch (NanoContainerMarkupException e) {
<add> assertTrue(e.getMessage().indexOf("Don't know how to create a 'grant' child") > -1);
<add> }
<add>
<add>
<add> }
<add>
<ide>
<ide> } |
|
Java | apache-2.0 | f7df322ca597ffedaf607d7b0528bdee3b56723a | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | package org.apache.lucene.spatial.geopoint.document;
/*
* 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 java.util.Objects;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
import org.apache.lucene.util.Attribute;
import org.apache.lucene.util.AttributeFactory;
import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.AttributeReflector;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import static org.apache.lucene.spatial.geopoint.document.GeoPointField.geoCodedToPrefixCoded;
import static org.apache.lucene.spatial.geopoint.document.GeoPointField.PRECISION_STEP;
/**
* <b>Expert:</b> This class provides a {@link TokenStream} used by {@link GeoPointField}
* for encoding GeoPoint terms.
*
* This class encodes terms up to a maximum of {@link #MAX_SHIFT} using a fixed precision step defined by
* {@link GeoPointField#PRECISION_STEP}. This yields a total of 4 terms per GeoPoint
* each consisting of 5 bytes (4 prefix bytes + 1 precision byte).
*
* Here's an example usage:
*
* <pre class="prettyprint">
* // using prefix terms
* GeoPointField geoPointField = new GeoPointField(fieldName1, lat, lon, GeoPointField.TYPE_NOT_STORED);
* document.add(geoPointField);
*
* // query by bounding box
* Query q = new GeoPointInBBoxQuery(fieldName1, minLat, maxLat, minLon, maxLon);
*
* // query by distance
* q = new GeoPointDistanceQuery(fieldName2, centerLat, centerLon, radiusMeters);
* </pre>
*
* @lucene.experimental
*/
final class GeoPointTokenStream extends TokenStream {
private static final int MAX_SHIFT = PRECISION_STEP * 4;
private final GeoPointTermAttribute geoPointTermAtt = addAttribute(GeoPointTermAttribute.class);
private final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);
private boolean isInit = false;
/**
* Expert: Creates a token stream for geo point fields with the specified
* <code>precisionStep</code> using the given
* {@link org.apache.lucene.util.AttributeFactory}.
* The stream is not yet initialized,
* before using set a value using the various setGeoCode method.
*/
public GeoPointTokenStream() {
super(new GeoPointAttributeFactory(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY));
assert PRECISION_STEP > 0;
}
public GeoPointTokenStream setGeoCode(final long geoCode) {
geoPointTermAtt.init(geoCode, MAX_SHIFT-PRECISION_STEP);
isInit = true;
return this;
}
@Override
public void reset() {
if (isInit == false) {
throw new IllegalStateException("call setGeoCode() before usage");
}
}
@Override
public boolean incrementToken() {
if (isInit == false) {
throw new IllegalStateException("call setGeoCode() before usage");
}
// this will only clear all other attributes in this TokenStream
clearAttributes();
final int shift = geoPointTermAtt.incShift();
posIncrAtt.setPositionIncrement((shift == MAX_SHIFT) ? 1 : 0);
return (shift < 63);
}
/**
* Tracks shift values during encoding
*/
public interface GeoPointTermAttribute extends Attribute {
/** Returns current shift value, undefined before first token */
int getShift();
/** <em>Don't call this method!</em>
* @lucene.internal */
void init(long value, int shift);
/** <em>Don't call this method!</em>
* @lucene.internal */
int incShift();
}
// just a wrapper to prevent adding CTA
private static final class GeoPointAttributeFactory extends AttributeFactory {
private final AttributeFactory delegate;
GeoPointAttributeFactory(AttributeFactory delegate) {
this.delegate = delegate;
}
@Override
public AttributeImpl createAttributeInstance(Class<? extends Attribute> attClass) {
if (CharTermAttribute.class.isAssignableFrom(attClass)) {
throw new IllegalArgumentException("GeoPointTokenStream does not support CharTermAttribute.");
}
return delegate.createAttributeInstance(attClass);
}
}
public static final class GeoPointTermAttributeImpl extends AttributeImpl implements GeoPointTermAttribute,TermToBytesRefAttribute {
private long value = 0L;
private int shift = 0;
private BytesRefBuilder bytes = new BytesRefBuilder();
public GeoPointTermAttributeImpl() {
this.shift = MAX_SHIFT-PRECISION_STEP;
}
@Override
public BytesRef getBytesRef() {
geoCodedToPrefixCoded(value, shift, bytes);
return bytes.get();
}
@Override
public void init(long value, int shift) {
this.value = value;
this.shift = shift;
}
@Override
public int getShift() { return shift; }
@Override
public int incShift() {
return (shift += PRECISION_STEP);
}
@Override
public void clear() {
// this attribute has no contents to clear!
// we keep it untouched as it's fully controlled by outer class.
}
@Override
public void reflectWith(AttributeReflector reflector) {
reflector.reflect(TermToBytesRefAttribute.class, "bytes", getBytesRef());
reflector.reflect(GeoPointTermAttribute.class, "shift", shift);
}
@Override
public void copyTo(AttributeImpl target) {
final GeoPointTermAttribute a = (GeoPointTermAttribute) target;
a.init(value, shift);
}
@Override
public GeoPointTermAttributeImpl clone() {
GeoPointTermAttributeImpl t = (GeoPointTermAttributeImpl)super.clone();
// Do a deep clone
t.bytes = new BytesRefBuilder();
t.bytes.copyBytes(getBytesRef());
return t;
}
@Override
public int hashCode() {
return Objects.hash(shift, value);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
GeoPointTermAttributeImpl other = (GeoPointTermAttributeImpl) obj;
if (shift != other.shift) return false;
if (value != other.value) return false;
return true;
}
}
/** override toString because it can throw cryptic "illegal shift value": */
@Override
public String toString() {
return getClass().getSimpleName() + "(precisionStep=" + PRECISION_STEP + " shift=" + geoPointTermAtt.getShift() + ")";
}
}
| lucene/spatial/src/java/org/apache/lucene/spatial/geopoint/document/GeoPointTokenStream.java | package org.apache.lucene.spatial.geopoint.document;
/*
* 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 java.util.Objects;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
import org.apache.lucene.util.Attribute;
import org.apache.lucene.util.AttributeFactory;
import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.AttributeReflector;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import static org.apache.lucene.spatial.geopoint.document.GeoPointField.geoCodedToPrefixCoded;
import static org.apache.lucene.spatial.geopoint.document.GeoPointField.PRECISION_STEP;
/**
* <b>Expert:</b> This class provides a {@link TokenStream} used by {@link GeoPointField}
* for encoding GeoPoint terms.
*
* This class encodes terms up to a maximum of {@link #MAX_SHIFT} using a fixed precision step defined by
* {@link GeoPointField#PRECISION_STEP}. This yields a total of 4 terms per GeoPoint
* each consisting of 5 bytes (4 prefix bytes + 1 precision byte).
*
* Here's an example usage:
*
* <pre class="prettyprint">
* // using prefix terms
* GeoPointField geoPointField = new GeoPointField(fieldName1, lat, lon, GeoPointField.TYPE_NOT_STORED);
* document.add(geoPointField);
*
* // query by bounding box (default uses TermEncoding.PREFIX)
* Query q = new GeoPointInBBoxQuery(fieldName1, minLat, maxLat, minLon, maxLon);
*
* // using numeric terms
* geoPointField = new GeoPointField(fieldName2, lat, lon, GeoPointField.NUMERIC_TYPE_NOT_STORED);
* document.add(geoPointField);
*
* // query by distance (requires TermEncoding.NUMERIC)
* q = new GeoPointDistanceQuery(fieldName2, TermEncoding.NUMERIC, centerLat, centerLon, radiusMeters);
* </pre>
*
* @lucene.experimental
*/
final class GeoPointTokenStream extends TokenStream {
private static final int MAX_SHIFT = PRECISION_STEP * 4;
private final GeoPointTermAttribute geoPointTermAtt = addAttribute(GeoPointTermAttribute.class);
private final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);
private boolean isInit = false;
/**
* Expert: Creates a token stream for geo point fields with the specified
* <code>precisionStep</code> using the given
* {@link org.apache.lucene.util.AttributeFactory}.
* The stream is not yet initialized,
* before using set a value using the various setGeoCode method.
*/
public GeoPointTokenStream() {
super(new GeoPointAttributeFactory(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY));
assert PRECISION_STEP > 0;
}
public GeoPointTokenStream setGeoCode(final long geoCode) {
geoPointTermAtt.init(geoCode, MAX_SHIFT-PRECISION_STEP);
isInit = true;
return this;
}
@Override
public void reset() {
if (isInit == false) {
throw new IllegalStateException("call setGeoCode() before usage");
}
}
@Override
public boolean incrementToken() {
if (isInit == false) {
throw new IllegalStateException("call setGeoCode() before usage");
}
// this will only clear all other attributes in this TokenStream
clearAttributes();
final int shift = geoPointTermAtt.incShift();
posIncrAtt.setPositionIncrement((shift == MAX_SHIFT) ? 1 : 0);
return (shift < 63);
}
/**
* Tracks shift values during encoding
*/
public interface GeoPointTermAttribute extends Attribute {
/** Returns current shift value, undefined before first token */
int getShift();
/** <em>Don't call this method!</em>
* @lucene.internal */
void init(long value, int shift);
/** <em>Don't call this method!</em>
* @lucene.internal */
int incShift();
}
// just a wrapper to prevent adding CTA
private static final class GeoPointAttributeFactory extends AttributeFactory {
private final AttributeFactory delegate;
GeoPointAttributeFactory(AttributeFactory delegate) {
this.delegate = delegate;
}
@Override
public AttributeImpl createAttributeInstance(Class<? extends Attribute> attClass) {
if (CharTermAttribute.class.isAssignableFrom(attClass)) {
throw new IllegalArgumentException("GeoPointTokenStream does not support CharTermAttribute.");
}
return delegate.createAttributeInstance(attClass);
}
}
public static final class GeoPointTermAttributeImpl extends AttributeImpl implements GeoPointTermAttribute,TermToBytesRefAttribute {
private long value = 0L;
private int shift = 0;
private BytesRefBuilder bytes = new BytesRefBuilder();
public GeoPointTermAttributeImpl() {
this.shift = MAX_SHIFT-PRECISION_STEP;
}
@Override
public BytesRef getBytesRef() {
geoCodedToPrefixCoded(value, shift, bytes);
return bytes.get();
}
@Override
public void init(long value, int shift) {
this.value = value;
this.shift = shift;
}
@Override
public int getShift() { return shift; }
@Override
public int incShift() {
return (shift += PRECISION_STEP);
}
@Override
public void clear() {
// this attribute has no contents to clear!
// we keep it untouched as it's fully controlled by outer class.
}
@Override
public void reflectWith(AttributeReflector reflector) {
reflector.reflect(TermToBytesRefAttribute.class, "bytes", getBytesRef());
reflector.reflect(GeoPointTermAttribute.class, "shift", shift);
}
@Override
public void copyTo(AttributeImpl target) {
final GeoPointTermAttribute a = (GeoPointTermAttribute) target;
a.init(value, shift);
}
@Override
public GeoPointTermAttributeImpl clone() {
GeoPointTermAttributeImpl t = (GeoPointTermAttributeImpl)super.clone();
// Do a deep clone
t.bytes = new BytesRefBuilder();
t.bytes.copyBytes(getBytesRef());
return t;
}
@Override
public int hashCode() {
return Objects.hash(shift, value);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
GeoPointTermAttributeImpl other = (GeoPointTermAttributeImpl) obj;
if (shift != other.shift) return false;
if (value != other.value) return false;
return true;
}
}
/** override toString because it can throw cryptic "illegal shift value": */
@Override
public String toString() {
return getClass().getSimpleName() + "(precisionStep=" + PRECISION_STEP + " shift=" + geoPointTermAtt.getShift() + ")";
}
}
| remove numeric encoding reference from GeoPointTokenStream javadocs
| lucene/spatial/src/java/org/apache/lucene/spatial/geopoint/document/GeoPointTokenStream.java | remove numeric encoding reference from GeoPointTokenStream javadocs | <ide><path>ucene/spatial/src/java/org/apache/lucene/spatial/geopoint/document/GeoPointTokenStream.java
<ide> * GeoPointField geoPointField = new GeoPointField(fieldName1, lat, lon, GeoPointField.TYPE_NOT_STORED);
<ide> * document.add(geoPointField);
<ide> *
<del> * // query by bounding box (default uses TermEncoding.PREFIX)
<add> * // query by bounding box
<ide> * Query q = new GeoPointInBBoxQuery(fieldName1, minLat, maxLat, minLon, maxLon);
<ide> *
<del> * // using numeric terms
<del> * geoPointField = new GeoPointField(fieldName2, lat, lon, GeoPointField.NUMERIC_TYPE_NOT_STORED);
<del> * document.add(geoPointField);
<del> *
<del> * // query by distance (requires TermEncoding.NUMERIC)
<del> * q = new GeoPointDistanceQuery(fieldName2, TermEncoding.NUMERIC, centerLat, centerLon, radiusMeters);
<add> * // query by distance
<add> * q = new GeoPointDistanceQuery(fieldName2, centerLat, centerLon, radiusMeters);
<ide> * </pre>
<ide> *
<ide> * @lucene.experimental |
|
Java | mit | 1a3d59e47d804d0f15b7a7f7914c19e0af80b24c | 0 | GreenBeard/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,jimmikaelkael/GlowstonePlusPlus,GreenBeard/GlowstonePlusPlus,LukBukkit/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,LukBukkit/GlowstonePlusPlus,GreenBeard/GlowstonePlusPlus,GreenBeard/GlowstonePlusPlus,LukBukkit/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,jimmikaelkael/GlowstonePlusPlus,jimmikaelkael/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,LukBukkit/GlowstonePlusPlus,jimmikaelkael/GlowstonePlusPlus | package net.glowstone;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.blocktype.BlockTNT;
import net.glowstone.entity.GlowEntity;
import net.glowstone.entity.GlowLivingEntity;
import net.glowstone.entity.GlowPlayer;
import net.glowstone.net.message.play.game.ExplosionMessage;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.BlockVector;
import org.bukkit.util.Vector;
import java.util.*;
public final class Explosion {
public static final int POWER_TNT = 4;
public static final int POWER_BED = 5;
public static final int POWER_CREEPER = 3;
public static final int POWER_CHARGED_CREEPER = 6;
public static final int POWER_GHAST = 1;
public static final int POWER_WITHER_SKULL = 1;
public static final int POWER_WITHER_CREATION = 7;
public static final int POWER_ENDER_CRYSTAL = 6;
private float power;
private final Entity source;
private final Location location;
private final boolean incendiary;
private final boolean breakBlocks;
private final GlowWorld world;
private float yield = 0.3f;
private static final Random random = new Random();
/**
* Creates a new explosion
* @param source The entity causing this explosion
* @param world The world this explosion is in
* @param x The X location of the explosion
* @param y The Y location of the explosion
* @param z The Z location of the explosion
* @param power The power of the explosion
* @param incendiary Whether or not blocks should be set on fire
* @param breakBlocks Whether blocks should break through this explosion
*/
public Explosion(Entity source, GlowWorld world, double x, double y, double z, float power, boolean incendiary, boolean breakBlocks) {
this(source, new Location(world, x, y, z), power, incendiary, breakBlocks);
}
/**
* Creates a new explosion
* @param source The entity causing this explosion
* @param location The location this explosion is occuring at. Must contain a GlowWorld
* @param power The power of the explosion
* @param incendiary Whether or not blocks should be set on fire
* @param breakBlocks Whether blocks should break through this explosion
*/
public Explosion(Entity source, Location location, float power, boolean incendiary, boolean breakBlocks) {
if (!(location.getWorld() instanceof GlowWorld)) {
throw new IllegalArgumentException("Supplied location does not have a valid GlowWorld");
}
this.source = source;
this.location = location.clone();
this.power = power;
this.incendiary = incendiary;
this.breakBlocks = breakBlocks;
this.world = (GlowWorld) location.getWorld();
}
public boolean explodeWithEvent() {
if (power < 0.1f)
return true;
Set<BlockVector> droppedBlocks = calculateBlocks();
EntityExplodeEvent event = EventFactory.callEvent(new EntityExplodeEvent(source, location, toBlockList(droppedBlocks), yield));
if (event.isCancelled()) return false;
this.yield = event.getYield();
playOutSoundAndParticles();
List<Block> blocks = toBlockList(droppedBlocks);
for (Block block : blocks) {
handleBlockExplosion((GlowBlock) block);
}
if (incendiary) {
for (Block block : blocks) {
setBlockOnFire((GlowBlock) block);
}
}
Collection<GlowPlayer> affectedPlayers = damageEntities();
for (GlowPlayer player : affectedPlayers) {
playOutExplosion(player, droppedBlocks);
}
return true;
}
///////////////////////////////////////////////////
// Calculate all the dropping blocks
private Set<BlockVector> calculateBlocks() {
if (!breakBlocks)
return new HashSet<>();
Set<BlockVector> blocks = new HashSet<>();
final int value = 16;
for (int x = 0; x < value; x++) {
for (int y = 0; y < value; y++) {
for (int z = 0; z < value; z++) {
if (!(x == 0 || x == value - 1 || y == 0 || y == value - 1 || z == 0 || z == value - 1)) {
continue;
}
calculateRay(x, y, z, blocks);
}
}
}
return blocks;
}
private void calculateRay(int ox, int oy, int oz, Collection<BlockVector> result) {
double x = ox / 7.5 - 1;
double y = oy / 7.5 - 1;
double z = oz / 7.5 - 1;
Vector direction = new Vector(x, y, z);
direction.normalize();
direction.multiply(0.3f); // 0.3 blocks away with each step
Location current = location.clone();
float currentPower = calculateStartPower();
while (currentPower > 0) {
GlowBlock block = world.getBlockAt(current);
if (block.getType() != Material.AIR) {
double blastDurability = getBlastDurability(block) / 5d;
blastDurability += 0.3F;
blastDurability *= 0.3F;
currentPower -= blastDurability;
if (currentPower > 0) {
result.add(new BlockVector(block.getX(), block.getY(), block.getZ()));
}
}
current.add(direction);
currentPower -= 0.225f;
}
}
private void handleBlockExplosion(GlowBlock block) {
if (block.getType() == Material.AIR) {
return;
} else if (block.getType() == Material.TNT) {
BlockTNT.igniteBlock(block, true);
return;
}
block.breakNaturally(yield);
}
private float calculateStartPower() {
float rand = random.nextFloat();
rand *= 0.6F; // (max - 0.7)
rand += 0.7; // min
return rand * power;
}
private double getBlastDurability(GlowBlock block) {
return block.getMaterialValues().getBlastResistance();
}
private List<Block> toBlockList(Collection<BlockVector> locs) {
List<Block> blocks = new ArrayList<>(locs.size());
for (BlockVector location : locs)
blocks.add(world.getBlockAt(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
return blocks;
}
private void setBlockOnFire(GlowBlock block) {
if (random.nextInt(3) != 0) {
return;
}
Block below = block.getRelative(BlockFace.DOWN);
Material belowType = below.getType();
if (belowType == Material.AIR || belowType == Material.FIRE || !belowType.isFlammable()) {
return;
}
BlockIgniteEvent event = EventFactory.callEvent(new BlockIgniteEvent(block, BlockIgniteEvent.IgniteCause.EXPLOSION, source));
if (event.isCancelled()) {
return;
}
block.setType(Material.FIRE);
}
/////////////////////////////////////////
// Damage entities
private Collection<GlowPlayer> damageEntities() {
float power = this.power;
this.power *= 2f;
Collection<GlowPlayer> affectedPlayers = new ArrayList<>();
Collection<GlowLivingEntity> entities = getNearbyEntities();
for (GlowLivingEntity entity : entities) {
if (entity instanceof GlowPlayer) {
affectedPlayers.add((GlowPlayer) entity);
}
double disDivPower = distanceTo(entity) / (double) this.power;
if (disDivPower > 1.0D) continue;
Vector vecDistance = distanceToHead(entity);
if (vecDistance.length() == 0.0) continue;
vecDistance.normalize();
double basicDamage = calculateDamage(entity, disDivPower);
double explosionDamage = calculateEnchantedDamage((int) ((basicDamage * basicDamage + basicDamage) * 4 * (double) power + 1.0D), entity);
DamageCause damageCause;
if (source == null || source.getType() == EntityType.PRIMED_TNT) {
damageCause = DamageCause.BLOCK_EXPLOSION;
} else {
damageCause = DamageCause.ENTITY_EXPLOSION;
}
entity.damage(explosionDamage, source, damageCause);
vecDistance.multiply(explosionDamage).multiply(0.25);
Vector currentVelocity = entity.getVelocity();
currentVelocity.add(vecDistance);
entity.setVelocity(currentVelocity);
}
return affectedPlayers;
}
private double calculateEnchantedDamage(double explosionDamage, GlowLivingEntity entity) {
int level = 0;
if (entity.getEquipment() != null) {
for (ItemStack stack : entity.getEquipment().getArmorContents()) {
if (stack != null) {
level += stack.getEnchantmentLevel(Enchantment.PROTECTION_EXPLOSIONS);
}
}
}
if (level > 0) {
float sub = level * 0.15f;
double damage = explosionDamage * sub;
damage = Math.floor(damage);
return explosionDamage - damage;
}
return explosionDamage;
}
private double calculateDamage(GlowEntity entity, double disDivPower) {
double damage = world.rayTrace(location, entity);
return (damage * (1D - disDivPower));
}
private Collection<GlowLivingEntity> getNearbyEntities() {
ArrayList<Chunk> chunks = new ArrayList<>();
chunks.add(location.getChunk());
int relX = location.getBlockX() - 16 * (int) Math.floor(location.getBlockX() / 16);
int relZ = location.getBlockZ() - 16 * (int) Math.floor(location.getBlockZ() / 16);
if (relX < power || relZ < power) {
if (relX < power) {
chunks.add(location.getWorld().getChunkAt(location.getBlockX() - 1 >> 4, location.getBlockZ() >> 4));
}
if (relZ < power) {
chunks.add(location.getWorld().getChunkAt(location.getBlockX() >> 4, location.getBlockZ() - 1 >> 4));
}
} else {
int invRelX = Math.abs(location.getBlockX() - 16 * (int) Math.floor(location.getBlockX() / 16));
int invRelZ = Math.abs(location.getBlockZ() - 16 * (int) Math.floor(location.getBlockZ() / 16));
if (invRelX < power) {
chunks.add(location.getWorld().getChunkAt(location.getBlockX() + 1 >> 4, location.getBlockZ() >> 4));
}
if (invRelZ < power) {
chunks.add(location.getWorld().getChunkAt(location.getBlockX() >> 4, location.getBlockZ() + 1 >> 4));
}
}
ArrayList<Entity> entities = new ArrayList<>();
for (Chunk chunk : chunks) {
entities.addAll(Arrays.asList(chunk.getEntities()));
}
List<GlowLivingEntity> nearbyEntities = new ArrayList<>();
for (Entity entity : entities) {
if (entity instanceof LivingEntity && distanceTo((LivingEntity) entity) / power < 1) {
nearbyEntities.add((GlowLivingEntity) entity);
}
}
return nearbyEntities;
}
private double distanceTo(LivingEntity entity) {
return location.clone().subtract(entity.getLocation()).length();
}
private Vector distanceToHead(LivingEntity entity) {
return entity.getLocation().clone().subtract(location.clone().subtract(0, entity.getEyeHeight(), 0)).toVector();
}
///////////////////////////////////////
// Visualize
private void playOutSoundAndParticles() {
world.playSound(location, Sound.EXPLODE, 4, (1.0F + (random.nextFloat() - random.nextFloat()) * 0.2F) * 0.7F);
if (this.power >= 2.0F && this.breakBlocks) {
// send huge explosion
world.spigot().playEffect(location, Effect.EXPLOSION_HUGE);
} else {
// send large explosion
world.spigot().playEffect(location, Effect.EXPLOSION_LARGE);
}
}
private void playOutExplosion(GlowPlayer player, Iterable<BlockVector> blocks) {
Collection<ExplosionMessage.Record> records = new ArrayList<>();
Location clientLoc = location.clone();
clientLoc.setX((int) clientLoc.getX());
clientLoc.setY((int) clientLoc.getY());
clientLoc.setZ((int) clientLoc.getZ());
for (BlockVector block : blocks) {
byte x = (byte) (block.getBlockX() - clientLoc.getBlockX());
byte y = (byte) (block.getBlockY() - clientLoc.getBlockY());
byte z = (byte) (block.getBlockZ() - clientLoc.getBlockZ());
records.add(new ExplosionMessage.Record(x, y, z));
}
Vector velocity = player.getVelocity();
ExplosionMessage message = new ExplosionMessage((float) location.getX(), (float) location.getY(), (float) location.getZ(),
power,
(float) velocity.getX(), (float) velocity.getY(), (float) velocity.getZ(),
records);
player.getSession().send(message);
}
}
| src/main/java/net/glowstone/Explosion.java | package net.glowstone;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.blocktype.BlockTNT;
import net.glowstone.entity.GlowEntity;
import net.glowstone.entity.GlowLivingEntity;
import net.glowstone.entity.GlowPlayer;
import net.glowstone.net.message.play.game.ExplosionMessage;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.BlockVector;
import org.bukkit.util.Vector;
import java.util.*;
public final class Explosion {
public static final int POWER_TNT = 4;
public static final int POWER_BED = 5;
public static final int POWER_CREEPER = 3;
public static final int POWER_CHARGED_CREEPER = 6;
public static final int POWER_GHAST = 1;
public static final int POWER_WITHER_SKULL = 1;
public static final int POWER_WITHER_CREATION = 7;
public static final int POWER_ENDER_CRYSTAL = 6;
private float power;
private final Entity source;
private final Location location;
private final boolean incendiary;
private final boolean breakBlocks;
private final GlowWorld world;
private float yield = 0.3f;
private static final Random random = new Random();
/**
* Creates a new explosion
* @param source The entity causing this explosion
* @param world The world this explosion is in
* @param x The X location of the explosion
* @param y The Y location of the explosion
* @param z The Z location of the explosion
* @param power The power of the explosion
* @param incendiary Whether or not blocks should be set on fire
* @param breakBlocks Whether blocks should break through this explosion
*/
public Explosion(Entity source, GlowWorld world, double x, double y, double z, float power, boolean incendiary, boolean breakBlocks) {
this(source, new Location(world, x, y, z), power, incendiary, breakBlocks);
}
/**
* Creates a new explosion
* @param source The entity causing this explosion
* @param location The location this explosion is occuring at. Must contain a GlowWorld
* @param power The power of the explosion
* @param incendiary Whether or not blocks should be set on fire
* @param breakBlocks Whether blocks should break through this explosion
*/
public Explosion(Entity source, Location location, float power, boolean incendiary, boolean breakBlocks) {
if (!(location.getWorld() instanceof GlowWorld)) {
throw new IllegalArgumentException("Supplied location does not have a valid GlowWorld");
}
this.source = source;
this.location = location.clone();
this.power = power;
this.incendiary = incendiary;
this.breakBlocks = breakBlocks;
this.world = (GlowWorld) location.getWorld();
}
public boolean explodeWithEvent() {
if (power < 0.1f)
return true;
Set<BlockVector> droppedBlocks = calculateBlocks();
EntityExplodeEvent event = EventFactory.callEvent(new EntityExplodeEvent(source, location, toBlockList(droppedBlocks), yield));
if (event.isCancelled()) return false;
this.yield = event.getYield();
playOutSoundAndParticles();
List<Block> blocks = toBlockList(droppedBlocks);
for (Block block : blocks) {
handleBlockExplosion((GlowBlock) block);
}
if (incendiary) {
for (Block block : blocks) {
setBlockOnFire((GlowBlock) block);
}
}
Collection<GlowPlayer> affectedPlayers = damageEntities();
for (GlowPlayer player : affectedPlayers) {
playOutExplosion(player, droppedBlocks);
}
return true;
}
///////////////////////////////////////////////////
// Calculate all the dropping blocks
private Set<BlockVector> calculateBlocks() {
if (!breakBlocks)
return new HashSet<>();
Set<BlockVector> blocks = new HashSet<>();
final int value = 16;
for (int x = 0; x < value; x++) {
for (int y = 0; y < value; y++) {
for (int z = 0; z < value; z++) {
if (!(x == 0 || x == value - 1 || y == 0 || y == value - 1 || z == 0 || z == value - 1)) {
continue;
}
calculateRay(x, y, z, blocks);
}
}
}
return blocks;
}
private void calculateRay(int ox, int oy, int oz, Collection<BlockVector> result) {
double x = ox / 7.5 - 1;
double y = oy / 7.5 - 1;
double z = oz / 7.5 - 1;
Vector direction = new Vector(x, y, z);
direction.normalize();
direction.multiply(0.3f); // 0.3 blocks away with each step
Location current = location.clone();
float currentPower = calculateStartPower();
while (currentPower > 0) {
GlowBlock block = world.getBlockAt(current);
if (block.getType() != Material.AIR) {
double blastDurability = getBlastDurability(block) / 5d;
blastDurability += 0.3F;
blastDurability *= 0.3F;
currentPower -= blastDurability;
if (currentPower > 0) {
result.add(new BlockVector(block.getX(), block.getY(), block.getZ()));
}
}
current.add(direction);
currentPower -= 0.225f;
}
}
private void handleBlockExplosion(GlowBlock block) {
if (block.getType() == Material.AIR) {
return;
} else if (block.getType() == Material.TNT) {
BlockTNT.igniteBlock(block, true);
return;
}
block.breakNaturally(yield);
}
private float calculateStartPower() {
float rand = random.nextFloat();
rand *= 0.6F; // (max - 0.7)
rand += 0.7; // min
return rand * power;
}
private double getBlastDurability(GlowBlock block) {
return block.getMaterialValues().getBlastResistance();
}
private List<Block> toBlockList(Collection<BlockVector> locs) {
List<Block> blocks = new ArrayList<>(locs.size());
for (BlockVector location : locs)
blocks.add(world.getBlockAt(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
return blocks;
}
private void setBlockOnFire(GlowBlock block) {
if (random.nextInt(3) != 0) {
return;
}
Block below = block.getRelative(BlockFace.DOWN);
Material belowType = below.getType();
if (belowType == Material.AIR || belowType == Material.FIRE || !belowType.isFlammable()) {
return;
}
BlockIgniteEvent event = EventFactory.callEvent(new BlockIgniteEvent(block, BlockIgniteEvent.IgniteCause.EXPLOSION, source));
if (event.isCancelled()) {
return;
}
block.setType(Material.FIRE);
}
/////////////////////////////////////////
// Damage entities
private Collection<GlowPlayer> damageEntities() {
float power = this.power;
this.power *= 2f;
Collection<GlowPlayer> affectedPlayers = new ArrayList<>();
Collection<GlowLivingEntity> entities = getNearbyEntities();
for (GlowLivingEntity entity : entities) {
if (entity instanceof GlowPlayer) {
affectedPlayers.add((GlowPlayer) entity);
} else {
double disDivPower = distanceTo(entity) / (double) this.power;
if (disDivPower > 1.0D) continue;
Vector vecDistance = distanceToHead(entity);
if (vecDistance.length() == 0.0) continue;
vecDistance.normalize();
double basicDamage = calculateDamage(entity, disDivPower);
double explosionDamage = calculateEnchantedDamage((int) ((basicDamage * basicDamage + basicDamage) * 4 * (double) power + 1.0D), entity);
DamageCause damageCause;
if (source == null || source.getType() == EntityType.PRIMED_TNT) {
damageCause = DamageCause.BLOCK_EXPLOSION;
} else {
damageCause = DamageCause.ENTITY_EXPLOSION;
}
entity.damage(explosionDamage, source, damageCause);
vecDistance.multiply(explosionDamage).multiply(0.25);
Vector currentVelocity = entity.getVelocity();
currentVelocity.add(vecDistance);
entity.setVelocity(currentVelocity);
}
}
return affectedPlayers;
}
private double calculateEnchantedDamage(double explosionDamage, GlowLivingEntity entity) {
int level = 0;
if (entity.getEquipment() != null) {
for (ItemStack stack : entity.getEquipment().getArmorContents()) {
if (stack != null) {
level += stack.getEnchantmentLevel(Enchantment.PROTECTION_EXPLOSIONS);
}
}
}
if (level > 0) {
float sub = level * 0.15f;
double damage = explosionDamage * sub;
damage = Math.floor(damage);
return explosionDamage - damage;
}
return explosionDamage;
}
private double calculateDamage(GlowEntity entity, double disDivPower) {
double damage = world.rayTrace(location, entity);
return (damage * (1D - disDivPower));
}
private Collection<GlowLivingEntity> getNearbyEntities() {
ArrayList<Chunk> chunks = new ArrayList<>();
chunks.add(location.getChunk());
int relX = location.getBlockX() - 16 * (int) Math.floor(location.getBlockX() / 16);
int relZ = location.getBlockZ() - 16 * (int) Math.floor(location.getBlockZ() / 16);
if (relX < power || relZ < power) {
if (relX < power) {
chunks.add(location.getWorld().getChunkAt(location.getBlockX() - 1 >> 4, location.getBlockZ() >> 4));
}
if (relZ < power) {
chunks.add(location.getWorld().getChunkAt(location.getBlockX() >> 4, location.getBlockZ() - 1 >> 4));
}
} else {
int invRelX = Math.abs(location.getBlockX() - 16 * (int) Math.floor(location.getBlockX() / 16));
int invRelZ = Math.abs(location.getBlockZ() - 16 * (int) Math.floor(location.getBlockZ() / 16));
if (invRelX < power) {
chunks.add(location.getWorld().getChunkAt(location.getBlockX() + 1 >> 4, location.getBlockZ() >> 4));
}
if (invRelZ < power) {
chunks.add(location.getWorld().getChunkAt(location.getBlockX() >> 4, location.getBlockZ() + 1 >> 4));
}
}
ArrayList<Entity> entities = new ArrayList<>();
for (Chunk chunk : chunks) {
entities.addAll(Arrays.asList(chunk.getEntities()));
}
List<GlowLivingEntity> nearbyEntities = new ArrayList<>();
for (Entity entity : entities) {
if (entity instanceof LivingEntity && distanceTo((LivingEntity) entity) / power < 1) {
nearbyEntities.add((GlowLivingEntity) entity);
}
}
return nearbyEntities;
}
private double distanceTo(LivingEntity entity) {
return location.clone().subtract(entity.getLocation()).length();
}
private Vector distanceToHead(LivingEntity entity) {
return entity.getLocation().clone().subtract(location.clone().subtract(0, entity.getEyeHeight(), 0)).toVector();
}
///////////////////////////////////////
// Visualize
private void playOutSoundAndParticles() {
world.playSound(location, Sound.EXPLODE, 4, (1.0F + (random.nextFloat() - random.nextFloat()) * 0.2F) * 0.7F);
if (this.power >= 2.0F && this.breakBlocks) {
// send huge explosion
world.spigot().playEffect(location, Effect.EXPLOSION_HUGE);
} else {
// send large explosion
world.spigot().playEffect(location, Effect.EXPLOSION_LARGE);
}
}
private void playOutExplosion(GlowPlayer player, Iterable<BlockVector> blocks) {
Collection<ExplosionMessage.Record> records = new ArrayList<>();
Location clientLoc = location.clone();
clientLoc.setX((int) clientLoc.getX());
clientLoc.setY((int) clientLoc.getY());
clientLoc.setZ((int) clientLoc.getZ());
for (BlockVector block : blocks) {
byte x = (byte) (block.getBlockX() - clientLoc.getBlockX());
byte y = (byte) (block.getBlockY() - clientLoc.getBlockY());
byte z = (byte) (block.getBlockZ() - clientLoc.getBlockZ());
records.add(new ExplosionMessage.Record(x, y, z));
}
Vector velocity = player.getVelocity();
ExplosionMessage message = new ExplosionMessage((float) location.getX(), (float) location.getY(), (float) location.getZ(),
power,
(float) velocity.getX(), (float) velocity.getY(), (float) velocity.getZ(),
records);
player.getSession().send(message);
}
}
| Affect players with explosion
| src/main/java/net/glowstone/Explosion.java | Affect players with explosion | <ide><path>rc/main/java/net/glowstone/Explosion.java
<ide> for (GlowLivingEntity entity : entities) {
<ide> if (entity instanceof GlowPlayer) {
<ide> affectedPlayers.add((GlowPlayer) entity);
<add> }
<add> double disDivPower = distanceTo(entity) / (double) this.power;
<add> if (disDivPower > 1.0D) continue;
<add>
<add> Vector vecDistance = distanceToHead(entity);
<add> if (vecDistance.length() == 0.0) continue;
<add>
<add> vecDistance.normalize();
<add>
<add> double basicDamage = calculateDamage(entity, disDivPower);
<add> double explosionDamage = calculateEnchantedDamage((int) ((basicDamage * basicDamage + basicDamage) * 4 * (double) power + 1.0D), entity);
<add>
<add> DamageCause damageCause;
<add> if (source == null || source.getType() == EntityType.PRIMED_TNT) {
<add> damageCause = DamageCause.BLOCK_EXPLOSION;
<ide> } else {
<del> double disDivPower = distanceTo(entity) / (double) this.power;
<del> if (disDivPower > 1.0D) continue;
<del>
<del> Vector vecDistance = distanceToHead(entity);
<del> if (vecDistance.length() == 0.0) continue;
<del>
<del> vecDistance.normalize();
<del>
<del> double basicDamage = calculateDamage(entity, disDivPower);
<del> double explosionDamage = calculateEnchantedDamage((int) ((basicDamage * basicDamage + basicDamage) * 4 * (double) power + 1.0D), entity);
<del>
<del> DamageCause damageCause;
<del> if (source == null || source.getType() == EntityType.PRIMED_TNT) {
<del> damageCause = DamageCause.BLOCK_EXPLOSION;
<del> } else {
<del> damageCause = DamageCause.ENTITY_EXPLOSION;
<del> }
<del> entity.damage(explosionDamage, source, damageCause);
<del>
<del> vecDistance.multiply(explosionDamage).multiply(0.25);
<del>
<del> Vector currentVelocity = entity.getVelocity();
<del> currentVelocity.add(vecDistance);
<del> entity.setVelocity(currentVelocity);
<del> }
<add> damageCause = DamageCause.ENTITY_EXPLOSION;
<add> }
<add> entity.damage(explosionDamage, source, damageCause);
<add>
<add> vecDistance.multiply(explosionDamage).multiply(0.25);
<add>
<add> Vector currentVelocity = entity.getVelocity();
<add> currentVelocity.add(vecDistance);
<add> entity.setVelocity(currentVelocity);
<ide> }
<ide>
<ide> return affectedPlayers; |
|
Java | apache-2.0 | ab65bf47eebff8d244401141ffa25cd4f78e6383 | 0 | cloud-software-foundation/c5,cloud-software-foundation/c5,cloud-software-foundation/c5,cloud-software-foundation/c5,cloud-software-foundation/c5 | /*
* Copyright (C) 2014 Ohm Data
*
* 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 c5db.client;
import c5db.MiniClusterBase;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import static c5db.testing.BytesMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class TestTooBigForASingleWebSocketTest extends MiniClusterBase {
private static final byte[] randomBytes = new byte[65535 * 4];
private static final Random random = new Random();
static {
random.nextBytes(randomBytes);
}
private final byte[] cf = Bytes.toBytes("cf");
private final byte[] cq = Bytes.toBytes("cq");
@Test
public void shouldSuccessfullyAcceptSmallPut() throws InterruptedException, ExecutionException, TimeoutException, IOException, MutationFailedException {
DataHelper.putRowInDB(table, row);
}
@Test
public void shouldSuccessfullyAcceptSmallPutAndReadSameValue()
throws InterruptedException, ExecutionException, TimeoutException, MutationFailedException, IOException {
byte[] valuePutIntoDatabase = row;
putRowAndValueIntoDatabase(row, valuePutIntoDatabase);
assertThat(DataHelper.valueReadFromDB(table, row), is(equalTo(valuePutIntoDatabase)));
}
@Test
public void testSendBigOne()
throws InterruptedException, ExecutionException, TimeoutException, IOException, MutationFailedException {
byte[] valuePutIntoDatabase = randomBytes;
putRowAndValueIntoDatabase(row, valuePutIntoDatabase);
}
@Test
public void shouldSuccessfullyAcceptLargePutAndReadSameValue() throws IOException {
byte[] valuePutIntoDatabase = randomBytes;
putRowAndValueIntoDatabase(row, valuePutIntoDatabase);
assertThat(DataHelper.valueReadFromDB(table, row), is(equalTo(valuePutIntoDatabase)));
}
private void putRowAndValueIntoDatabase(byte[] row,
byte[] valuePutIntoDatabase) throws IOException {
Put put = new Put(row);
put.add(cf, cq, valuePutIntoDatabase);
table.put(put);
}
}
| c5-end-to-end-tests/src/test/java/c5db/client/TestTooBigForASingleWebSocketTest.java | /*
* Copyright (C) 2014 Ohm Data
*
* 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 c5db.client;
import c5db.ManyClusterBase;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import static c5db.testing.BytesMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class TestTooBigForASingleWebSocketTest extends ManyClusterBase {
private static final byte[] randomBytes = new byte[65535 * 4];
private static final Random random = new Random();
static {
random.nextBytes(randomBytes);
}
private final byte[] cf = Bytes.toBytes("cf");
private final byte[] cq = Bytes.toBytes("cq");
@Test
public void shouldSuccessfullyAcceptSmallPut() throws InterruptedException, ExecutionException, TimeoutException, IOException, MutationFailedException {
DataHelper.putRowInDB(table, row);
}
@Test
public void shouldSuccessfullyAcceptSmallPutAndReadSameValue()
throws InterruptedException, ExecutionException, TimeoutException, MutationFailedException, IOException {
byte[] valuePutIntoDatabase = row;
putRowAndValueIntoDatabase(row, valuePutIntoDatabase);
assertThat(DataHelper.valueReadFromDB(table, row), is(equalTo(valuePutIntoDatabase)));
}
@Test
public void testSendBigOne()
throws InterruptedException, ExecutionException, TimeoutException, IOException, MutationFailedException {
byte[] valuePutIntoDatabase = randomBytes;
putRowAndValueIntoDatabase(row, valuePutIntoDatabase);
}
@Test
public void shouldSuccessfullyAcceptLargePutAndReadSameValue() throws IOException {
byte[] valuePutIntoDatabase = randomBytes;
putRowAndValueIntoDatabase(row, valuePutIntoDatabase);
assertThat(DataHelper.valueReadFromDB(table, row), is(equalTo(valuePutIntoDatabase)));
}
private void putRowAndValueIntoDatabase(byte[] row,
byte[] valuePutIntoDatabase) throws IOException {
Put put = new Put(row);
put.add(cf, cq, valuePutIntoDatabase);
table.put(put);
}
}
| Moved tests to minicluster
| c5-end-to-end-tests/src/test/java/c5db/client/TestTooBigForASingleWebSocketTest.java | Moved tests to minicluster | <ide><path>5-end-to-end-tests/src/test/java/c5db/client/TestTooBigForASingleWebSocketTest.java
<ide> */
<ide> package c5db.client;
<ide>
<del>import c5db.ManyClusterBase;
<add>import c5db.MiniClusterBase;
<ide> import org.apache.hadoop.hbase.client.Put;
<ide> import org.apache.hadoop.hbase.util.Bytes;
<ide> import org.junit.Test;
<ide> import static org.hamcrest.CoreMatchers.is;
<ide> import static org.hamcrest.MatcherAssert.assertThat;
<ide>
<del>public class TestTooBigForASingleWebSocketTest extends ManyClusterBase {
<add>public class TestTooBigForASingleWebSocketTest extends MiniClusterBase {
<ide> private static final byte[] randomBytes = new byte[65535 * 4];
<ide> private static final Random random = new Random();
<ide> |
|
JavaScript | mit | 5ae77bd9c00f347d43e9c44bf702305a3d155125 | 0 | aminmarashi/binary-bot,binary-com/binary-bot,binary-com/binary-bot,aminmarashi/binary-bot | import { Map } from 'immutable'
import Proposal from './Proposal'
import Broadcast from './Broadcast'
import Total from './Total'
import Balance from './Balance'
import FollowTicks from './FollowTicks'
import OpenContract from './OpenContract'
const scopeToWatchResolve = {
before: ['before', true],
purchase: ['before', false],
during: ['during', true],
after: ['during', false],
}
export default class TradeEngine extends Balance(
OpenContract(Proposal(FollowTicks(Broadcast(Total(class {})))))) {
constructor($scope) {
super()
this.api = $scope.api
this.observer = $scope.observer
this.$scope = $scope
this.observe()
this.data = new Map()
this.watches = new Map()
this.signals = new Map()
}
start(token, tradeOption) {
this.makeProposals(tradeOption)
this.followTicks(tradeOption.symbol)
if (token === this.token) {
return
}
this.api.authorize(token).then(() => {
this.token = token
this.subscribeToBalance()
})
}
purchase(contractType) {
const toBuy = this.selectProposal(contractType)
this.isPurchaseStarted = true
this.api.buyContract(toBuy.id, toBuy.ask_price).then(r => {
this.broadcastPurchase(r.buy, contractType)
this.subscribeToOpenContract(r.buy.contract_id)
this.signal('purchase')
})
}
observe() {
this.observeOpenContract()
this.observeBalance()
this.observeProposals()
}
signal(scope) {
const [watchName, arg] = scopeToWatchResolve[scope]
if (this.watches.has(watchName)) {
const watch = this.watches.get(watchName)
this.watches = this.watches.delete(watchName)
watch(arg)
} else {
this.signals = this.signals.set(watchName, arg)
}
this.scope = scope
}
watch(watchName) {
if (this.signals.has(watchName)) {
const signal = this.signals.get(watchName)
this.signals = this.signals.delete(watchName)
return Promise.resolve(signal)
}
return new Promise(resolve => {
this.watches = this.watches.set(watchName, resolve)
})
}
getData() {
return this.data
}
isInside(scope) {
return this.scope === scope
}
listen(n, f) {
this.api.events.on(n, f)
}
}
| src/botPage/bot/TradeEngine/index.js | import { Map } from 'immutable'
import Proposal from './Proposal'
import Broadcast from './Broadcast'
import Total from './Total'
import Balance from './Balance'
import FollowTicks from './FollowTicks'
import OpenContract from './OpenContract'
const scopeToWatchResolve = {
before: ['before', true],
purchase: ['before', false],
during: ['during', true],
after: ['during', false],
}
export default class TradeEngine extends Balance(
OpenContract(Proposal(FollowTicks(Broadcast(Total(class {})))))) {
constructor($scope) {
super()
this.api = $scope.api
this.observer = $scope.observer
this.$scope = $scope
this.observe()
this.data = new Map()
this.promises = new Map()
this.signals = new Map()
}
start(token, tradeOption) {
this.makeProposals(tradeOption)
this.followTicks(tradeOption.symbol)
if (token === this.token) {
return
}
this.api.authorize(token).then(() => {
this.token = token
this.subscribeToBalance()
})
}
purchase(contractType) {
const toBuy = this.selectProposal(contractType)
this.isPurchaseStarted = true
this.api.buyContract(toBuy.id, toBuy.ask_price).then(r => {
this.broadcastPurchase(r.buy, contractType)
this.subscribeToOpenContract(r.buy.contract_id)
this.signal('purchase')
})
}
observe() {
this.observeOpenContract()
this.observeBalance()
this.observeProposals()
}
signal(scope) {
const [watchName, arg] = scopeToWatchResolve[scope]
if (this.promises.has(watchName)) {
this.signals = this.signals.delete(watchName)
this.promises.get(watchName)(arg)
} else {
this.signals = this.signals.set(watchName, arg)
}
this.scope = scope
}
watch(watchName) {
if (this.signals.has(watchName)) {
const signal = this.signals.get(watchName)
this.signals = this.signals.delete(watchName)
return Promise.resolve(signal)
}
return new Promise(resolve => {
this.promises = this.promises.set(watchName, resolve)
})
}
getData() {
return this.data
}
isInside(scope) {
return this.scope === scope
}
listen(n, f) {
this.api.events.on(n, f)
}
}
| Add watches for unresolved watch calls and signals unwatched signals
| src/botPage/bot/TradeEngine/index.js | Add watches for unresolved watch calls and signals unwatched signals | <ide><path>rc/botPage/bot/TradeEngine/index.js
<ide> this.$scope = $scope
<ide> this.observe()
<ide> this.data = new Map()
<del> this.promises = new Map()
<add> this.watches = new Map()
<ide> this.signals = new Map()
<ide> }
<ide> start(token, tradeOption) {
<ide> signal(scope) {
<ide> const [watchName, arg] = scopeToWatchResolve[scope]
<ide>
<del> if (this.promises.has(watchName)) {
<del> this.signals = this.signals.delete(watchName)
<del> this.promises.get(watchName)(arg)
<add> if (this.watches.has(watchName)) {
<add> const watch = this.watches.get(watchName)
<add>
<add> this.watches = this.watches.delete(watchName)
<add>
<add> watch(arg)
<ide> } else {
<ide> this.signals = this.signals.set(watchName, arg)
<ide> }
<ide> this.signals = this.signals.delete(watchName)
<ide> return Promise.resolve(signal)
<ide> }
<add>
<ide> return new Promise(resolve => {
<del> this.promises = this.promises.set(watchName, resolve)
<add> this.watches = this.watches.set(watchName, resolve)
<ide> })
<ide> }
<ide> getData() { |
|
JavaScript | mit | c691eebbae2851e88f2cdbc81a64661c973d3955 | 0 | BizzoTech/kunafa-client | import uuid from 'uuid';
import R from 'ramda';
import kunafaSelectors from '../selectors';
const {
eventsByRelevantDocSelector
} = kunafaSelectors;
export default(store, config) => {
const {
localOnlyActions,
needLocalProcessing,
getActionPreProcessors,
getActionPostProcessors,
getRelevantDocsIds,
deviceInfo
} = config;
const createClientAction = (action, state) => {
const eventsList = R.values(state.events);
const events_size = eventsList.length;
const localOnlyEvents = eventsList.filter(R.prop('localOnly'));
const localProcessingDocumentsIds = R.flatten(localOnlyEvents.map(event => event.relevantDocsIds));
const relevantDocsIds = getRelevantDocsIds(action);
const shouldWaitForOtherAction = relevantDocsIds.some(docId => localProcessingDocumentsIds.includes(docId));
const localOnly = needLocalProcessing.includes(action) || shouldWaitForOtherAction;
const _id = state.currentProfile._id ?
`${state.currentProfile._id}-${Date.now()}-${action.type}` :
`anonymous-${deviceInfo.device_unique_id}-${Date.now()}-${action.type}`;
return {
_id,
type: "EVENT",
draft: "true",
localOnly: localOnly ?
"true" : undefined,
action,
relevantDocsIds: getRelevantDocsIds(action),
preProcessors: getActionPreProcessors(action),
postProcessors: getActionPostProcessors(action),
status: "draft",
info: deviceInfo,
createdAt: Date.now(),
createdBy: (state.currentProfile._id || "anonymous")
}
}
return next => action => {
if(!localOnlyActions.includes(action.type) && action.type !== 'ADD_PROFILE') {
setTimeout(() => {
next({
type: 'ADD_EVENT',
doc: createClientAction(action, store.getState())
});
}, 0);
}
let result = next(action);
if(action.type === 'LOAD_DOCS' || action.type === 'LOAD_DOCS_FROM_CACHE') {
setTimeout(() => {
const eventsByRelevantDoc = eventsByRelevantDocSelector(store.getState());
action.docs.forEach(doc => {
const docEvents = eventsByRelevantDoc[doc._id] || [];
docEvents.forEach(event => {
const isAppliedOn = event.appliedOn && event.appliedOn[doc._id];
if(isAppliedOn && event.appliedOn[doc._id] <= doc._rev) {
event.appliedOnClient = event.appliedOnClient || {};
if(!event.appliedOnClient[doc._id]) {
next({
type: 'UPDATE_EVENT',
doc: {
...event,
draft: true,
appliedOnClient: {
...(event.appliedOnClient),
[doc._id]: doc._rev
}
}
});
}
} else {
next(event.action);
}
});
});
}, 0);
}
return result;
}
}
| middlewares/event_sourcing_middleware.js | import uuid from 'uuid';
import R from 'ramda';
import kunafaSelectors from '../selectors';
const {
eventsByRelevantDocSelector
} = kunafaSelectors;
export default(store, config) => {
const {
localOnlyActions,
needLocalProcessing,
getActionPreProcessors,
getActionPostProcessors,
getRelevantDocsIds,
deviceInfo
} = config;
const createClientAction = (action, state) => {
const eventsList = R.values(state.events);
const events_size = eventsList.length;
const localOnlyEvents = eventsList.filter(R.prop('localOnly'));
const localProcessingDocumentsIds = R.flatten(localOnlyEvents.map(event => event.relevantDocsIds));
const relevantDocsIds = getRelevantDocsIds(action);
const shouldWaitForOtherAction = relevantDocsIds.some(docId => localProcessingDocumentsIds.includes(docId));
const localOnly = needLocalProcessing.includes(action) || shouldWaitForOtherAction;
const _id = state.currentProfile._id ?
`${state.currentProfile._id}-${Date.now()}-${action.type}` :
`anonymous-${info.device_unique_id}-${Date.now()}-${action.type}`;
return {
_id,
type: "EVENT",
draft: "true",
localOnly: localOnly ?
"true" : undefined,
action,
relevantDocsIds: getRelevantDocsIds(action),
preProcessors: getActionPreProcessors(action),
postProcessors: getActionPostProcessors(action),
status: "draft",
info: deviceInfo,
createdAt: Date.now(),
createdBy: (state.currentProfile._id || "anonymous")
}
}
return next => action => {
if(!localOnlyActions.includes(action.type) && action.type !== 'ADD_PROFILE') {
setTimeout(() => {
next({
type: 'ADD_EVENT',
doc: createClientAction(action, store.getState())
});
}, 0);
}
let result = next(action);
if(action.type === 'LOAD_DOCS' || action.type === 'LOAD_DOCS_FROM_CACHE') {
setTimeout(() => {
const eventsByRelevantDoc = eventsByRelevantDocSelector(store.getState());
action.docs.forEach(doc => {
const docEvents = eventsByRelevantDoc[doc._id] || [];
docEvents.forEach(event => {
const isAppliedOn = event.appliedOn && event.appliedOn[doc._id];
if(isAppliedOn && event.appliedOn[doc._id] <= doc._rev) {
event.appliedOnClient = event.appliedOnClient || {};
if(!event.appliedOnClient[doc._id]) {
next({
type: 'UPDATE_EVENT',
doc: {
...event,
draft: true,
appliedOnClient: {
...(event.appliedOnClient),
[doc._id]: doc._rev
}
}
});
}
} else {
next(event.action);
}
});
});
}, 0);
}
return result;
}
}
| fix typo
| middlewares/event_sourcing_middleware.js | fix typo | <ide><path>iddlewares/event_sourcing_middleware.js
<ide> const localOnly = needLocalProcessing.includes(action) || shouldWaitForOtherAction;
<ide> const _id = state.currentProfile._id ?
<ide> `${state.currentProfile._id}-${Date.now()}-${action.type}` :
<del> `anonymous-${info.device_unique_id}-${Date.now()}-${action.type}`;
<add> `anonymous-${deviceInfo.device_unique_id}-${Date.now()}-${action.type}`;
<ide> return {
<ide> _id,
<ide> type: "EVENT", |
|
Java | mit | b4797580691ed012c1a6ae51f7f68fac78b389b8 | 0 | Sh4rK/szoftlab4 | package szoftlab4;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A játék grafikus felületének fő osztálya, a kirajzoláshoz szükséges grafikus elemeket és a kirajzolandó
* játékobjektumokat tartalmazza. Kezeli a modelben történő változásokat.
*/
@SuppressWarnings("serial")
public class View {
private final List<Drawable> drawables;
private final JPanel panel;
private final JPanel mapPanel;
private final JPanel magicPanel;
private Drawable placing;
/**
* Konstruktor. Létrehozza az összes a képernyőn megjelenő gombot, panelt.
* Beállítja ezeknek az eseménykezelőit.
*/
public View(Game game, Map map) {
Controller c = new Controller(game, this);
JButton buildTower = new JButton();
JButton buildObstacle = new JButton();
JButton pause = new JButton(" P ");
GemButton redGem = new GemButton(TowerGem.red);
GemButton greenGem = new GemButton(TowerGem.green);
GemButton blueGem = new GemButton(TowerGem.blue);
GemButton yellowGem = new GemButton(ObstacleGem.yellow);
GemButton orangeGem = new GemButton(ObstacleGem.orange);
JLabel magic = new JLabel("Magic: ");
drawables = new ArrayList<Drawable>();
drawables.add(new GraphicMap(map));
JPanel menuPanel = new JPanel();
JPanel mainPanel = new JPanel();
magicPanel = new JPanel();
/* wow such anonymous class */
mapPanel = new JPanel() {
/**
* Kirajzolja az összes játékban lévő objektumot
*/
public void paintComponent(Graphics g) {
/* very thread-safe */
synchronized (drawables) {
for (Drawable dr : drawables)
dr.draw(g);
if (placing != null) {
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
placing.draw(g);
}
}
}
};
mapPanel.setPreferredSize(new Dimension(800, 600));
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(mainPanel, BorderLayout.PAGE_START);
panel.add(mapPanel, BorderLayout.CENTER);
mainPanel.setLayout(new BorderLayout());
mainPanel.add(menuPanel);
mainPanel.add(magicPanel, BorderLayout.EAST);
menuPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
menuPanel.setPreferredSize(new Dimension(0, 55));
menuPanel.add(buildTower);
menuPanel.add(redGem);
menuPanel.add(greenGem);
menuPanel.add(blueGem);
menuPanel.add(buildObstacle);
menuPanel.add(yellowGem);
menuPanel.add(orangeGem);
menuPanel.add(pause);
magicPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
Font magicFont = new Font("Consolas", Font.PLAIN, 26);
magic.setFont(magicFont);
magicPanel.add(magic);
redGem.setToolTipText("<html><center>Piros varázskő<br>Több sebezés<br>" + TowerGem.red.getCost() + " VE</center></html>");
greenGem.setToolTipText("<html><center>Zöld varázskő<br>Nagyobb hatókör<br>" + TowerGem.green.getCost() + " VE</center></html>");
blueGem.setToolTipText("<html><center>Kék varázskő<br>Gyorsabb tüzelés<br>" + TowerGem.blue.getCost() + " VE</center></html>");
yellowGem.setToolTipText("<html><center>Sárga varázskő<br>Nagyobb hatókör<br>" + ObstacleGem.yellow.getCost() + " VE</center></html>");
orangeGem.setToolTipText("<html><center>Narancssárga varázskő<br>Jobb lassítás<br>" + ObstacleGem.orange.getCost() + " VE</center></html>");
buildTower.setToolTipText("<html><center>Torony építése<br>" + Tower.cost + " VE</center></html>");
buildObstacle.setToolTipText("<html><center>Akadály építése<br>" + Obstacle.cost + " VE</center></html>");
buildTower.addMouseListener(c.new BuildTowerMouseEvent());
redGem.addMouseListener(c.new EnchantMouseEvent());
greenGem.addMouseListener(c.new EnchantMouseEvent());
blueGem.addMouseListener(c.new EnchantMouseEvent());
buildObstacle.addMouseListener(c.new BuildObstacleMouseEvent());
yellowGem.addMouseListener(c.new EnchantMouseEvent());
orangeGem.addMouseListener(c.new EnchantMouseEvent());
mapPanel.addMouseListener(c.new MapMouseEvent());
mapPanel.addMouseMotionListener(c.new MapMouseEvent());
/* comeatmebro cheat */
mapPanel.addKeyListener(new KeyAdapter() {
String typed = "";
public void keyPressed(KeyEvent e) {
typed += e.getKeyChar();
if (typed.contains("comeatmebro")) {
Tower.comeatmebro = !Tower.comeatmebro;
typed = "";
}
}
});
menuPanel.addMouseListener(c.new MenuPanelMouseEvent());
pause.addMouseListener(c.new pauseMouseEvent());
pause.setFont(magicFont);
setButtonLook(pause, null);
buildTower.setBackground(menuPanel.getBackground());
setButtonLook(buildTower, new ImageIcon(Resources.TowerImage));
buildObstacle.setBackground(menuPanel.getBackground());
setButtonLook(buildObstacle, new ImageIcon(Resources.ObstacleImage));
redGem.setBackground(menuPanel.getBackground());
setButtonLook(redGem, new ImageIcon(Resources.RedGemImage));
greenGem.setBackground(menuPanel.getBackground());
setButtonLook(greenGem, new ImageIcon(Resources.GreenGemImage));
blueGem.setBackground(menuPanel.getBackground());
setButtonLook(blueGem, new ImageIcon(Resources.BlueGemImage));
yellowGem.setBackground(menuPanel.getBackground());
setButtonLook(yellowGem, new ImageIcon(Resources.YellowGemImage));
orangeGem.setBackground(menuPanel.getBackground());
setButtonLook(orangeGem, new ImageIcon(Resources.OrangeGemImage));
mapPanel.requestFocusInWindow();
}
/**
* Beállítja egy JButton kinézetét
*/
private void setButtonLook(JButton b, ImageIcon img) {
b.setFocusPainted(false);
b.setMargin(new Insets(1, 1, 1, 1));
b.setContentAreaFilled(false);
b.setIcon(img);
b.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
}
/**
* Bármilyen drawable hozzáadásához.
* Anonymous class-okkal lehet használni.
* FPS számlálóhoz kell.
*/
public void addDrawable(Drawable d) {
synchronized (drawables) {
drawables.add(d);
Collections.sort(drawables, Collections.reverseOrder());
}
}
public JPanel getPanel() {
return panel;
}
/**
* Hozzáad egy ellenséget a kirajzolandó objektumokhoz.
*/
public void enemyAdded(Enemy en) {
synchronized (drawables) {
drawables.add(new GraphicEnemy(en));
Collections.sort(drawables, Collections.reverseOrder());
}
}
/**
* Kitöröl egy már célba ért lövedéket a kirajzolandó objektumok közül.
*/
public void projectileExploded(Projectile p) {
synchronized (drawables) {
drawables.remove(new GraphicProjectile(p));
}
}
/**
* Hozzáad egy lövedéket a kirajzolandó objektumokhoz.
*/
public void projectileAdded(Projectile p) {
synchronized (drawables) {
drawables.add(new GraphicProjectile(p));
Collections.sort(drawables, Collections.reverseOrder());
}
}
/**
* Kitöröl egy ellenséget a kirajzolandó objektumok közül.
*/
public void enemyDied(Enemy en) {
synchronized (drawables) {
drawables.remove(new GraphicEnemy(en));
}
}
/**
* Hozzáad egy tornyot a kirajzolandó objektumokhoz.
*/
public void towerAdded(Tower t) {
synchronized (drawables) {
drawables.add(new GraphicTower(t));
Collections.sort(drawables, Collections.reverseOrder());
}
}
/**
* Hozzáad egy akadályt a kirajzolandó objektumokhoz.
*/
public void obstacleAdded(Obstacle o) {
synchronized (drawables) {
drawables.add(new GraphicObstacle(o));
Collections.sort(drawables, Collections.reverseOrder());
}
}
/**
* Hozzáad egy gem-et egy már a kirajzolandó listában lévő toronyhoz.
*/
public void towerEnchanted(Tower t) {
synchronized (drawables) {
GraphicTower gt = (GraphicTower) drawables.get(drawables.indexOf(new GraphicTower(t)));
gt.setGem();
}
}
/**
* Hozzáad egy gem-et egy már a kirajzolandó listában lévő akadályhoz.
*/
public void obstacleEnchanted(Obstacle o) {
synchronized (drawables) {
GraphicObstacle go = (GraphicObstacle) drawables.get(drawables.indexOf(new GraphicObstacle(o)));
go.setGem();
}
}
/**
* Beállítja az éppen lerakásra váró kirajzolható objektumot.
*/
public void setPlacing(Drawable d) {
placing = d;
}
/**
* Kirajzolja a kirajzolandó objektumokat.
*/
public void drawAll() {
mapPanel.repaint();
}
/**
* Frissíti a kiírt varázserő mennyiségét.
*
* @param magic Az új érték.
*/
public void magicChange(int magic) {
JLabel magicLabel = (JLabel) magicPanel.getComponent(0);
magicLabel.setText("Magic: " + magic);
}
/**
* Kiír a képernyőre egy szöveget és kirak egy képet
* A mapPanel-re való kattintás után visszatér a metódus
*/
private void winLoseScreen(final String msg, final Image image) {
synchronized (drawables) {
drawables.add(new Drawable() {
{
this.img = image;
z_index = 10;
}
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.white);
g2.setFont(new Font("Consolas", Font.BOLD, 36));
g2.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D r = fm.getStringBounds(msg, g2);
int x = (800 - (int) r.getWidth()) / 2;
int y = ((600 - (int) r.getHeight()) / 3 + fm.getAscent());
g2.drawString(msg, x, y);
if (img != null)
g2.drawImage(img, 800 / 2, 600 / 2, null);
g2.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
});
}
drawAll();
final Object lock = new Object(); // szinkronizációs objektum
mapPanel.addMouseListener(new MouseAdapter() {
/**
* Gombnyomásra értesíti a lock objektumot
*/
public void mousePressed(MouseEvent e) {
synchronized (lock) {
lock.notify();
}
}
});
/* vár amíg meg nem nyomunk egy egérgombot */
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Kirajzolja a vesztes képernyőt
*/
public void gameLost() {
winLoseScreen("Sajnálom kollega, vesztett", null);
}
/**
* Kirajzolja a nyertes képernyőt
*/
public void gameWon() {
winLoseScreen("Kíváló munka, kollega!", Resources.LZImage);
}
}
| src/szoftlab4/View.java | package szoftlab4;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A játék grafikus felületének fő osztálya, a kirajzoláshoz szükséges grafikus elemeket és a kirajzolandó
* játékobjektumokat tartalmazza. Kezeli a modelben történő változásokat.
*/
@SuppressWarnings("serial")
public class View {
private final List<Drawable> drawables;
private final JPanel panel;
private final JPanel mapPanel;
private final JPanel magicPanel;
private Drawable placing;
/**
* Konstruktor. Létrehozza az összes a képernyőn megjelenő gombot, panelt.
* Beállítja ezeknek az eseménykezelőit.
*/
public View(Game game, Map map) {
Controller c = new Controller(game, this);
JButton buildTower = new JButton();
JButton buildObstacle = new JButton();
JButton pause = new JButton(" P ");
GemButton redGem = new GemButton(TowerGem.red);
GemButton greenGem = new GemButton(TowerGem.green);
GemButton blueGem = new GemButton(TowerGem.blue);
GemButton yellowGem = new GemButton(ObstacleGem.yellow);
GemButton orangeGem = new GemButton(ObstacleGem.orange);
JLabel magic = new JLabel("Magic: ");
drawables = new ArrayList<Drawable>();
drawables.add(new GraphicMap(map));
JPanel menuPanel = new JPanel();
JPanel mainPanel = new JPanel();
magicPanel = new JPanel();
/* wow such anonymous class */
mapPanel = new JPanel() {
/**
* Kirajzolja az összes játékban lévő objektumot
*/
public void paintComponent(Graphics g) {
/* very thread-safe */
synchronized (drawables) {
for (Drawable dr : drawables)
dr.draw(g);
if (placing != null) {
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
placing.draw(g);
}
}
}
};
mapPanel.setPreferredSize(new Dimension(800, 600));
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(mainPanel, BorderLayout.PAGE_START);
panel.add(mapPanel, BorderLayout.CENTER);
mainPanel.setLayout(new BorderLayout());
mainPanel.add(menuPanel);
mainPanel.add(magicPanel, BorderLayout.EAST);
menuPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
menuPanel.setPreferredSize(new Dimension(0, 55));
menuPanel.add(buildTower);
menuPanel.add(redGem);
menuPanel.add(greenGem);
menuPanel.add(blueGem);
menuPanel.add(buildObstacle);
menuPanel.add(yellowGem);
menuPanel.add(orangeGem);
menuPanel.add(pause);
magicPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
Font magicFont = new Font("Consolas", Font.PLAIN, 26);
magic.setFont(magicFont);
magicPanel.add(magic);
redGem.setToolTipText("<html><center>Piros varázskő<br>Több sebezés<br>" + TowerGem.red.getCost() + " VE</center></html>");
greenGem.setToolTipText("<html><center>Zöld varázskő<br>Nagyobb hatókör<br>" + TowerGem.green.getCost() + " VE</center></html>");
blueGem.setToolTipText("<html><center>Kék varázskő<br>Gyorsabb tüzelés<br>" + TowerGem.blue.getCost() + " VE</center></html>");
yellowGem.setToolTipText("<html><center>Sárga varázskő<br>Nagyobb hatókör<br>" + ObstacleGem.yellow.getCost() + " VE</center></html>");
orangeGem.setToolTipText("<html><center>Narancssárga varázskő<br>Jobb lassítás<br>" + ObstacleGem.orange.getCost() + " VE</center></html>");
buildTower.setToolTipText("<html><center>Torony építése<br>" + Tower.cost + " VE</center></html>");
buildObstacle.setToolTipText("<html><center>Akadály építése<br>" + Obstacle.cost + " VE</center></html>");
buildTower.addMouseListener(c.new BuildTowerMouseEvent());
redGem.addMouseListener(c.new EnchantMouseEvent());
greenGem.addMouseListener(c.new EnchantMouseEvent());
blueGem.addMouseListener(c.new EnchantMouseEvent());
buildObstacle.addMouseListener(c.new BuildObstacleMouseEvent());
yellowGem.addMouseListener(c.new EnchantMouseEvent());
orangeGem.addMouseListener(c.new EnchantMouseEvent());
mapPanel.addMouseListener(c.new MapMouseEvent());
mapPanel.addMouseMotionListener(c.new MapMouseEvent());
/* comeatmebro cheat */
mapPanel.addKeyListener(new KeyAdapter() {
String typed = "";
public void keyPressed(KeyEvent e) {
typed += e.getKeyChar();
if (typed.contains("comeatmebro")) {
Tower.comeatmebro = !Tower.comeatmebro;
typed = "";
}
}
});
menuPanel.addMouseListener(c.new MenuPanelMouseEvent());
pause.addMouseListener(c.new pauseMouseEvent());
pause.setFont(magicFont);
setButtonLook(pause, null);
buildTower.setBackground(menuPanel.getBackground());
setButtonLook(buildTower, new ImageIcon(Resources.TowerImage));
buildObstacle.setBackground(menuPanel.getBackground());
setButtonLook(buildObstacle, new ImageIcon(Resources.ObstacleImage));
redGem.setBackground(menuPanel.getBackground());
setButtonLook(redGem, new ImageIcon(Resources.RedGemImage));
greenGem.setBackground(menuPanel.getBackground());
setButtonLook(greenGem, new ImageIcon(Resources.GreenGemImage));
blueGem.setBackground(menuPanel.getBackground());
setButtonLook(blueGem, new ImageIcon(Resources.BlueGemImage));
yellowGem.setBackground(menuPanel.getBackground());
setButtonLook(yellowGem, new ImageIcon(Resources.YellowGemImage));
orangeGem.setBackground(menuPanel.getBackground());
setButtonLook(orangeGem, new ImageIcon(Resources.OrangeGemImage));
mapPanel.requestFocusInWindow();
}
/**
* Beállítja egy JButton kinézetét
*/
private void setButtonLook(JButton b, ImageIcon img) {
b.setFocusPainted(false);
b.setMargin(new Insets(1, 1, 1, 1));
b.setContentAreaFilled(false);
b.setIcon(img);
b.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
}
/**
* Bármilyen drawable hozzáadásához.
* Anonymous class-okkal lehet használni.
* FPS számlálóhoz kell.
*/
public void addDrawable(Drawable d) {
synchronized (drawables) {
drawables.add(d);
Collections.sort(drawables, Collections.reverseOrder());
}
}
public JPanel getPanel() {
return panel;
}
/**
* Hozzáad egy ellenséget a kirajzolandó objektumokhoz.
*/
public void enemyAdded(Enemy en) {
synchronized (drawables) {
drawables.add(new GraphicEnemy(en));
Collections.sort(drawables, Collections.reverseOrder());
}
}
/**
* Kitöröl egy már célba ért lövedéket a kirajzolandó objektumok közül.
*/
public void projectileExploded(Projectile p) {
synchronized (drawables) {
drawables.remove(new GraphicProjectile(p));
}
}
/**
* Hozzáad egy lövedéket a kirajzolandó objektumokhoz.
*/
public void projectileAdded(Projectile p) {
synchronized (drawables) {
drawables.add(new GraphicProjectile(p));
Collections.sort(drawables, Collections.reverseOrder());
}
}
/**
* Kitöröl egy ellenséget a kirajzolandó objektumok közül.
*/
public void enemyDied(Enemy en) {
synchronized (drawables) {
drawables.remove(new GraphicEnemy(en));
}
}
/**
* Hozzáad egy tornyot a kirajzolandó objektumokhoz.
*/
public void towerAdded(Tower t) {
synchronized (drawables) {
drawables.add(new GraphicTower(t));
Collections.sort(drawables, Collections.reverseOrder());
}
}
/**
* Hozzáad egy akadályt a kirajzolandó objektumokhoz.
*/
public void obstacleAdded(Obstacle o) {
synchronized (drawables) {
drawables.add(new GraphicObstacle(o));
Collections.sort(drawables, Collections.reverseOrder());
}
}
/**
* Hozzáad egy gem-et egy már a kirajzolandó listában lévő toronyhoz.
*/
public void towerEnchanted(Tower t) {
synchronized (drawables) {
GraphicTower gt = (GraphicTower) drawables.get(drawables.indexOf(new GraphicTower(t)));
gt.setGem();
}
}
/**
* Hozzáad egy gem-et egy már a kirajzolandó listában lévő akadályhoz.
*/
public void obstacleEnchanted(Obstacle o) {
synchronized (drawables) {
GraphicObstacle go = (GraphicObstacle) drawables.get(drawables.indexOf(new GraphicObstacle(o)));
go.setGem();
}
}
/**
* Beállítja az éppen lerakásra váró kirajzolható objektumot.
*/
public void setPlacing(Drawable d) {
placing = d;
}
/**
* Kirajzolja a kirajzolandó objektumokat.
*/
public void drawAll() {
mapPanel.repaint();
}
/**
* Frissíti a kiírt varázserő mennyiségét.
*
* @param magic Az új érték.
*/
public void magicChange(int magic) {
JLabel magicLabel = (JLabel) magicPanel.getComponent(0);
magicLabel.setText("Magic: " + magic);
}
/**
* Kiír a képernyőre egy szöveget és kirak egy képet
* A mapPanel-re való kattintás után visszatér a metódus
*/
private void winLoseScreen(String message, Image img) {
synchronized (drawables) {
drawables.add(new Drawable() {
String msg;
public Drawable init(String st, Image i) {
msg = st;
img = i;
z_index = 10;
return this;
}
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.white);
g2.setFont(new Font("Consolas", Font.BOLD, 36));
g2.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D r = fm.getStringBounds(msg, g2);
int x = (800 - (int) r.getWidth()) / 2;
int y = ((600 - (int) r.getHeight()) / 3 + fm.getAscent());
g2.drawString(msg, x, y);
if (img != null)
g2.drawImage(img, 800 / 2, 600 / 2, null);
g2.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
}.init(message, img));
}
drawAll();
final Object lock = new Object(); // szinkronizációs objektum
mapPanel.addMouseListener(new MouseAdapter() {
/**
* Gombnyomásra értesíti a lock objektumot
*/
public void mousePressed(MouseEvent e) {
synchronized (lock) {
lock.notify();
}
}
});
/* vár amíg meg nem nyomunk egy egérgombot */
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Kirajzolja a vesztes képernyőt
*/
public void gameLost() {
winLoseScreen("Sajnálom kollega, vesztett", null);
}
/**
* Kirajzolja a nyertes képernyőt
*/
public void gameWon() {
winLoseScreen("Kíváló munka, kollega!", Resources.LZImage);
}
}
| More refactor
| src/szoftlab4/View.java | More refactor | <ide><path>rc/szoftlab4/View.java
<ide> * Kiír a képernyőre egy szöveget és kirak egy képet
<ide> * A mapPanel-re való kattintás után visszatér a metódus
<ide> */
<del> private void winLoseScreen(String message, Image img) {
<add> private void winLoseScreen(final String msg, final Image image) {
<ide> synchronized (drawables) {
<ide> drawables.add(new Drawable() {
<del> String msg;
<del>
<del> public Drawable init(String st, Image i) {
<del> msg = st;
<del> img = i;
<add> {
<add> this.img = image;
<ide> z_index = 10;
<del>
<del> return this;
<ide> }
<ide>
<ide> public void draw(Graphics g) {
<ide> RenderingHints.KEY_TEXT_ANTIALIASING,
<ide> RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
<ide> }
<del> }.init(message, img));
<add> });
<ide> }
<ide>
<ide> drawAll(); |
|
Java | apache-2.0 | 4c5f926cbdd5870e8a8804da9e759da64f02dc3f | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | package org.apache.lucene.store;
/**
* Copyright 2004 The Apache Software 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.
*/
import java.io.IOException;
/** A Directory is a flat list of files. Files may be written once, when they
* are created. Once a file is created it may only be opened for read, or
* deleted. Random access is permitted both when reading and writing.
*
* <p> Java's i/o APIs not used directly, but rather all i/o is
* through this API. This permits things such as: <ul>
* <li> implementation of RAM-based indices;
* <li> implementation indices stored in a database, via JDBC;
* <li> implementation of an index as a single file;
* </ul>
*
* @author Doug Cutting
*/
public abstract class Directory {
/** Returns an array of strings, one for each file in the directory. */
public abstract String[] list()
throws IOException;
/** Returns true iff a file with the given name exists. */
public abstract boolean fileExists(String name)
throws IOException;
/** Returns the time the named file was last modified. */
public abstract long fileModified(String name)
throws IOException;
/** Set the modified time of an existing file to now. */
public abstract void touchFile(String name)
throws IOException;
/** Removes an existing file in the directory. */
public abstract void deleteFile(String name)
throws IOException;
/** Renames an existing file in the directory.
If a file already exists with the new name, then it is replaced.
This replacement should be atomic. */
public abstract void renameFile(String from, String to)
throws IOException;
/** Returns the length of a file in the directory. */
public abstract long fileLength(String name)
throws IOException;
/** Creates a new, empty file in the directory with the given name.
Returns a stream writing this file. */
public abstract OutputStream createFile(String name)
throws IOException;
/** @deprecated use {@link #openInput(String)} */
public InputStream openFile(String name) throws IOException {
return (InputStream)openInput(name);
}
/** Returns a stream reading an existing file. */
public IndexInput openInput(String name)
throws IOException {
// default implementation for back compatibility
// this method should be abstract
return (IndexInput)openFile(name);
}
/** Construct a {@link Lock}.
* @param name the name of the lock file
*/
public abstract Lock makeLock(String name);
/** Closes the store. */
public abstract void close()
throws IOException;
}
| src/java/org/apache/lucene/store/Directory.java | package org.apache.lucene.store;
/**
* Copyright 2004 The Apache Software 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.
*/
import java.io.IOException;
/** A Directory is a flat list of files. Files may be written once, when they
* are created. Once a file is created it may only be opened for read, or
* deleted. Random access is permitted both when reading and writing.
*
* <p> Java's i/o APIs not used directly, but rather all i/o is
* through this API. This permits things such as: <ul>
* <li> implementation of RAM-based indices;
* <li> implementation indices stored in a database, via JDBC;
* <li> implementation of an index as a single file;
* </ul>
*
* @author Doug Cutting
*/
public abstract class Directory {
/** Returns an array of strings, one for each file in the directory. */
public abstract String[] list()
throws IOException;
/** Returns true iff a file with the given name exists. */
public abstract boolean fileExists(String name)
throws IOException;
/** Returns the time the named file was last modified. */
public abstract long fileModified(String name)
throws IOException;
/** Set the modified time of an existing file to now. */
public abstract void touchFile(String name)
throws IOException;
/** Removes an existing file in the directory. */
public abstract void deleteFile(String name)
throws IOException;
/** Renames an existing file in the directory.
If a file already exists with the new name, then it is replaced.
This replacement should be atomic. */
public abstract void renameFile(String from, String to)
throws IOException;
/** Returns the length of a file in the directory. */
public abstract long fileLength(String name)
throws IOException;
/** Creates a new, empty file in the directory with the given name.
Returns a stream writing this file. */
public abstract OutputStream createFile(String name)
throws IOException;
/** @deprecated use {@link openInput(String)}. */
public InputStream openFile(String name) throws IOException {
return (InputStream)openInput(name);
}
/** Returns a stream reading an existing file. */
public IndexInput openInput(String name)
throws IOException {
// default implementation for back compatibility
// this method should be abstract
return (IndexInput)openFile(name);
}
/** Construct a {@link Lock}.
* @param name the name of the lock file
*/
public abstract Lock makeLock(String name);
/** Closes the store. */
public abstract void close()
throws IOException;
}
| fix link in doc
git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@150519 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/lucene/store/Directory.java | fix link in doc | <ide><path>rc/java/org/apache/lucene/store/Directory.java
<ide> public abstract OutputStream createFile(String name)
<ide> throws IOException;
<ide>
<del> /** @deprecated use {@link openInput(String)}. */
<add> /** @deprecated use {@link #openInput(String)} */
<ide> public InputStream openFile(String name) throws IOException {
<ide> return (InputStream)openInput(name);
<ide> } |
|
Java | apache-2.0 | c4b57c2f272f1798ab46cea737d6c696c96c93e4 | 0 | ppavlidis/baseCode,ppavlidis/baseCode | package baseCode.gui.table;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
import baseCode.gui.JMatrixDisplay;
/**
* TableSorter is a decorator for TableModels; adding sorting
* functionality to a supplied TableModel. TableSorter does
* not store or copy the data in its TableModel; instead it maintains
* a map from the row indexes of the view to the row indexes of the
* model. As requests are made of the sorter (like getValueAt(row, col))
* they are passed to the underlying model after the row numbers
* have been translated via the internal mapping array. This way,
* the TableSorter appears to hold another copy of the table
* with the rows in a different order.
* <p/>
* TableSorter registers itself as a listener to the underlying model,
* just as the JTable itself would. Events recieved from the model
* are examined, sometimes manipulated (typically widened), and then
* passed on to the TableSorter's listeners (typically the JTable).
* If a change to the model has invalidated the order of TableSorter's
* rows, a note of this is made and the sorter will resort the
* rows the next time a value is requested.
* <p/>
* When the tableHeader property is set, either by using the
* setTableHeader() method or the two argument constructor, the
* table header may be used as a complete UI for TableSorter.
* The default renderer of the tableHeader is decorated with a renderer
* that indicates the sorting status of each column. In addition,
* a mouse listener is installed with the following behavior:
* <ul>
* <li>
* Mouse-click: Clears the sorting status of all other columns
* and advances the sorting status of that column through three
* values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
* NOT_SORTED again).
* <li>
* SHIFT-mouse-click: Clears the sorting status of all other columns
* and cycles the sorting status of the column through the same
* three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
* <li>
* CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
* that the changes to the column do not cancel the statuses of columns
* that are already sorting - giving a way to initiate a compound
* sort.
* </ul>
* <p/>
* This is a long overdue rewrite of a class of the same name that
* first appeared in the swing table demos in 1997.
*
* @author Philip Milne
* @author Brendon McLean
* @author Dan van Enckevort
* @author Parwinder Sekhon
* @version 2.0 02/27/04
*/
public class TableSorter extends AbstractTableModel {
protected TableModel tableModel;
private JMatrixDisplay m_matrixDisplay;
public static final int DESCENDING = -1;
public static final int NOT_SORTED = 0;
public static final int ASCENDING = 1;
private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) o1).compareTo(o2);
}
};
public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
};
private Row[] viewToModel;
private int[] modelToView;
private JTableHeader tableHeader;
private MouseListener mouseListener;
private TableModelListener tableModelListener;
private Map columnComparators = new HashMap();
private List sortingColumns = new ArrayList();
public TableSorter() {
this.mouseListener = new MouseHandler();
this.tableModelListener = new TableModelHandler();
}
public TableSorter(TableModel tableModel) {
this();
setTableModel(tableModel);
}
public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
this();
setTableHeader(tableHeader);
setTableModel(tableModel);
}
public TableSorter( TableModel tableModel, JMatrixDisplay matrixDisplay ) {
this( tableModel );
m_matrixDisplay = matrixDisplay;
}
private void clearSortingState() {
viewToModel = null;
modelToView = null;
}
public TableModel getTableModel() {
return tableModel;
}
public void setTableModel(TableModel tableModel) {
if (this.tableModel != null) {
this.tableModel.removeTableModelListener(tableModelListener);
}
this.tableModel = tableModel;
if (this.tableModel != null) {
this.tableModel.addTableModelListener(tableModelListener);
}
clearSortingState();
fireTableStructureChanged();
}
public JTableHeader getTableHeader() {
return tableHeader;
}
public void setTableHeader(JTableHeader tableHeader) {
if (this.tableHeader != null) {
this.tableHeader.removeMouseListener(mouseListener);
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
if (defaultRenderer instanceof SortableHeaderRenderer) {
this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
}
}
this.tableHeader = tableHeader;
if (this.tableHeader != null) {
this.tableHeader.addMouseListener(mouseListener);
this.tableHeader.setDefaultRenderer(
new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
}
}
public boolean isSorting() {
return sortingColumns.size() != 0;
}
private Directive getDirective(int column) {
for (int i = 0; i < sortingColumns.size(); i++) {
Directive directive = (Directive)sortingColumns.get(i);
if (directive.column == column) {
return directive;
}
}
return EMPTY_DIRECTIVE;
}
public int getSortingStatus(int column) {
return getDirective(column).direction;
}
private void sortingStatusChanged() {
clearSortingState();
fireTableDataChanged();
if (tableHeader != null) {
tableHeader.repaint();
}
}
public void setSortingStatus(int column, int status) {
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE) {
sortingColumns.remove(directive);
}
if (status != NOT_SORTED) {
sortingColumns.add(new Directive(column, status));
}
sortingStatusChanged();
}
protected Icon getHeaderRendererIcon(int column, int size) {
Directive directive = getDirective(column);
if (directive == EMPTY_DIRECTIVE) {
return null;
}
return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
}
public void cancelSorting() {
sortingColumns.clear();
sortingStatusChanged();
}
public void setColumnComparator(Class type, Comparator comparator) {
if (comparator == null) {
columnComparators.remove(type);
} else {
columnComparators.put(type, comparator);
}
}
protected Comparator getComparator(int column) {
Class columnType = tableModel.getColumnClass(column);
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null) {
return comparator;
}
if (Comparable.class.isAssignableFrom(columnType)) {
return COMPARABLE_COMAPRATOR;
}
return LEXICAL_COMPARATOR;
}
protected Comparator getComparator(Class columnClass) {
Class columnType = columnClass;
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null) {
return comparator;
}
if (Comparable.class.isAssignableFrom(columnType)) {
return COMPARABLE_COMAPRATOR;
}
return LEXICAL_COMPARATOR;
}
private Row[] getViewToModel() {
if (viewToModel == null) {
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++) {
viewToModel[row] = new Row(row);
}
if (isSorting()) {
Arrays.sort(viewToModel);
}
}
return viewToModel;
}
public int modelIndex(int viewIndex) {
return getViewToModel()[viewIndex].modelIndex;
}
private int[] getModelToView() {
if (modelToView == null) {
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++) {
modelToView[modelIndex(i)] = i;
}
}
return modelToView;
}
// TableModel interface methods
public int getRowCount() {
return (tableModel == null) ? 0 : tableModel.getRowCount();
}
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
}
public String getColumnName(int column) {
return tableModel.getColumnName(column);
}
public Class getColumnClass(int column) {
return tableModel.getColumnClass(column);
}
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(modelIndex(row), column);
}
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(modelIndex(row), column);
}
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, modelIndex(row), column);
}
// Helper classes
private class Row implements Comparable {
private int modelIndex;
public Row(int index) {
this.modelIndex = index;
}
public int compareTo(Object o) {
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
Directive directive = (Directive) it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
Comparator comparator;
int comparison = 0;
if ( o1 == null && o2 == null ) {
comparison = 0;
}
else if ( o1 == null ) {
if ( directive.direction == DESCENDING) // Define null less than everything, except null.
comparison = -1;
else // Define null greater than everything, except null.
comparison = 1;
}
else if ( o2 == null) {
if ( directive.direction == DESCENDING)
comparison = 1;
else
comparison = -1;
}
else if ( o1 != null && o2 != null ) {
if(o1.getClass().equals(Double.class)) {
comparator = getComparator( Double.class );
}
else if(o1.getClass().equals(Integer.class)) {
comparator = getComparator( Integer.class );
}
else if(o1.getClass().equals(Point.class)) {
comparator = getComparator( Double.class );
// If sortColumn is in the matrix display, then model.getValueAt()
// returns a Point object that represents a coordinate into the
// display matrix. This is done so that the display matrix object
// can be asked for both the color and the value. We are here only
// interested in the value.
if (m_matrixDisplay != null) {
Point p1 = ( Point ) o1;
Point p2 = ( Point ) o2;
o1 = new Double( m_matrixDisplay.getValue( p1.x, p1.y ) );
o2 = new Double( m_matrixDisplay.getValue( p2.x, p2.y ) );
}
}
else if(o1.getClass().equals(ArrayList.class)) {
comparator = getComparator( Double.class );
if (m_matrixDisplay != null) {
// Because of the bar graph cell renderer, getValueAt
// in our table model returns an array of two values:
// the first is the actual p value, and the second is
// the expected p value. Here, we want to sort by
// the actual p value, which should be the first item
// in the array list.
Double a = ( Double ) ( ( ArrayList ) o1 ).get( 0 );
Double b = ( Double ) ( ( ArrayList ) o2 ).get( 0 );
// yes, we did get an array list, but we want to
// compare the Double values the array lists contain,
// not the array lists themselves.
o1 = a;
o2 = b;
}
}
else {
comparator=getComparator( column );
}
comparison = comparator.compare( o1, o2 );
}
if (comparison != 0) {
return directive.direction == DESCENDING ? -comparison : comparison;
}
}
return 0;
}
}
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not sorting by anything, just pass the event along.
if (!isSorting()) {
clearSortingState();
fireTableChanged(e);
return;
}
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
cancelSorting();
fireTableChanged(e);
return;
}
// We can map a cell event through to the view without widening
// when the following conditions apply:
//
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
//
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
//
// The last check, for (modelToView != null) is to see if modelToView
// is already allocated. If we don't do this check; sorting can become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow()
&& column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED
&& modelToView != null) {
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this,
viewIndex, viewIndex,
column, e.getType()));
return;
}
// Something has happened to the data that may have invalidated the row order.
clearSortingState();
fireTableDataChanged();
return;
}
}
private class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if(e.getButton()==MouseEvent.BUTTON1)
{
JTableHeader h = ( JTableHeader ) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX( e.getX() );
if ( viewColumn == -1) return;
int column = columnModel.getColumn( viewColumn ).getModelIndex();
if ( column != -1 ) {
int status = getSortingStatus( column );
if ( !e.isControlDown() ) {
cancelSorting();
}
// Cycle the sorting states through {ASCENDING, DESCENDING} ignoring NOT_SORTED
status = ( status == ASCENDING ) ? DESCENDING : ASCENDING;
setSortingStatus( column, status );
}
}
}
}
private static class Arrow implements Icon {
private boolean descending;
private int size;
private int priority;
public Arrow(boolean descending, int size, int priority) {
this.descending = descending;
this.size = size;
this.priority = priority;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Color color = c == null ? Color.GRAY : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
}
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
}
public int getIconWidth() {
return size;
}
public int getIconHeight() {
return size;
}
}
private class SortableHeaderRenderer implements TableCellRenderer {
private TableCellRenderer tableCellRenderer;
public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
this.tableCellRenderer = tableCellRenderer;
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = tableCellRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
l.setHorizontalTextPosition( JLabel.LEFT );
l.setVerticalAlignment( JLabel.BOTTOM );
int modelColumn = table.convertColumnIndexToModel(column);
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
}
return c;
}
}
private static class Directive {
private int column;
private int direction;
public Directive(int column, int direction) {
this.column = column;
this.direction = direction;
}
}
}
| src/baseCode/gui/table/TableSorter.java | package baseCode.gui.table;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
import baseCode.gui.JMatrixDisplay;
/**
* TableSorter is a decorator for TableModels; adding sorting
* functionality to a supplied TableModel. TableSorter does
* not store or copy the data in its TableModel; instead it maintains
* a map from the row indexes of the view to the row indexes of the
* model. As requests are made of the sorter (like getValueAt(row, col))
* they are passed to the underlying model after the row numbers
* have been translated via the internal mapping array. This way,
* the TableSorter appears to hold another copy of the table
* with the rows in a different order.
* <p/>
* TableSorter registers itself as a listener to the underlying model,
* just as the JTable itself would. Events recieved from the model
* are examined, sometimes manipulated (typically widened), and then
* passed on to the TableSorter's listeners (typically the JTable).
* If a change to the model has invalidated the order of TableSorter's
* rows, a note of this is made and the sorter will resort the
* rows the next time a value is requested.
* <p/>
* When the tableHeader property is set, either by using the
* setTableHeader() method or the two argument constructor, the
* table header may be used as a complete UI for TableSorter.
* The default renderer of the tableHeader is decorated with a renderer
* that indicates the sorting status of each column. In addition,
* a mouse listener is installed with the following behavior:
* <ul>
* <li>
* Mouse-click: Clears the sorting status of all other columns
* and advances the sorting status of that column through three
* values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
* NOT_SORTED again).
* <li>
* SHIFT-mouse-click: Clears the sorting status of all other columns
* and cycles the sorting status of the column through the same
* three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
* <li>
* CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
* that the changes to the column do not cancel the statuses of columns
* that are already sorting - giving a way to initiate a compound
* sort.
* </ul>
* <p/>
* This is a long overdue rewrite of a class of the same name that
* first appeared in the swing table demos in 1997.
*
* @author Philip Milne
* @author Brendon McLean
* @author Dan van Enckevort
* @author Parwinder Sekhon
* @version 2.0 02/27/04
*/
public class TableSorter extends AbstractTableModel {
protected TableModel tableModel;
private JMatrixDisplay m_matrixDisplay;
public static final int DESCENDING = -1;
public static final int NOT_SORTED = 0;
public static final int ASCENDING = 1;
private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) o1).compareTo(o2);
}
};
public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
};
private Row[] viewToModel;
private int[] modelToView;
private JTableHeader tableHeader;
private MouseListener mouseListener;
private TableModelListener tableModelListener;
private Map columnComparators = new HashMap();
private List sortingColumns = new ArrayList();
public TableSorter() {
this.mouseListener = new MouseHandler();
this.tableModelListener = new TableModelHandler();
}
public TableSorter(TableModel tableModel) {
this();
setTableModel(tableModel);
}
public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
this();
setTableHeader(tableHeader);
setTableModel(tableModel);
}
public TableSorter( TableModel tableModel, JMatrixDisplay matrixDisplay ) {
this( tableModel );
m_matrixDisplay = matrixDisplay;
}
private void clearSortingState() {
viewToModel = null;
modelToView = null;
}
public TableModel getTableModel() {
return tableModel;
}
public void setTableModel(TableModel tableModel) {
if (this.tableModel != null) {
this.tableModel.removeTableModelListener(tableModelListener);
}
this.tableModel = tableModel;
if (this.tableModel != null) {
this.tableModel.addTableModelListener(tableModelListener);
}
clearSortingState();
fireTableStructureChanged();
}
public JTableHeader getTableHeader() {
return tableHeader;
}
public void setTableHeader(JTableHeader tableHeader) {
if (this.tableHeader != null) {
this.tableHeader.removeMouseListener(mouseListener);
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
if (defaultRenderer instanceof SortableHeaderRenderer) {
this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
}
}
this.tableHeader = tableHeader;
if (this.tableHeader != null) {
this.tableHeader.addMouseListener(mouseListener);
this.tableHeader.setDefaultRenderer(
new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
}
}
public boolean isSorting() {
return sortingColumns.size() != 0;
}
private Directive getDirective(int column) {
for (int i = 0; i < sortingColumns.size(); i++) {
Directive directive = (Directive)sortingColumns.get(i);
if (directive.column == column) {
return directive;
}
}
return EMPTY_DIRECTIVE;
}
public int getSortingStatus(int column) {
return getDirective(column).direction;
}
private void sortingStatusChanged() {
clearSortingState();
fireTableDataChanged();
if (tableHeader != null) {
tableHeader.repaint();
}
}
public void setSortingStatus(int column, int status) {
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE) {
sortingColumns.remove(directive);
}
if (status != NOT_SORTED) {
sortingColumns.add(new Directive(column, status));
}
sortingStatusChanged();
}
protected Icon getHeaderRendererIcon(int column, int size) {
Directive directive = getDirective(column);
if (directive == EMPTY_DIRECTIVE) {
return null;
}
return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
}
public void cancelSorting() {
sortingColumns.clear();
sortingStatusChanged();
}
public void setColumnComparator(Class type, Comparator comparator) {
if (comparator == null) {
columnComparators.remove(type);
} else {
columnComparators.put(type, comparator);
}
}
protected Comparator getComparator(int column) {
Class columnType = tableModel.getColumnClass(column);
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null) {
return comparator;
}
if (Comparable.class.isAssignableFrom(columnType)) {
return COMPARABLE_COMAPRATOR;
}
return LEXICAL_COMPARATOR;
}
protected Comparator getComparator(Class columnClass) {
Class columnType = columnClass;
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null) {
return comparator;
}
if (Comparable.class.isAssignableFrom(columnType)) {
return COMPARABLE_COMAPRATOR;
}
return LEXICAL_COMPARATOR;
}
private Row[] getViewToModel() {
if (viewToModel == null) {
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++) {
viewToModel[row] = new Row(row);
}
if (isSorting()) {
Arrays.sort(viewToModel);
}
}
return viewToModel;
}
public int modelIndex(int viewIndex) {
return getViewToModel()[viewIndex].modelIndex;
}
private int[] getModelToView() {
if (modelToView == null) {
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++) {
modelToView[modelIndex(i)] = i;
}
}
return modelToView;
}
// TableModel interface methods
public int getRowCount() {
return (tableModel == null) ? 0 : tableModel.getRowCount();
}
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
}
public String getColumnName(int column) {
return tableModel.getColumnName(column);
}
public Class getColumnClass(int column) {
return tableModel.getColumnClass(column);
}
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(modelIndex(row), column);
}
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(modelIndex(row), column);
}
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, modelIndex(row), column);
}
// Helper classes
private class Row implements Comparable {
private int modelIndex;
public Row(int index) {
this.modelIndex = index;
}
public int compareTo(Object o) {
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
Directive directive = (Directive) it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
Comparator comparator;
int comparison = 0;
if ( o1 == null && o2 == null ) {
comparison = 0;
}
else if ( o1 == null ) {
if ( directive.direction == DESCENDING) // Define null less than everything, except null.
comparison = -1;
else // Define null greater than everything, except null.
comparison = 1;
}
else if ( o2 == null) {
if ( directive.direction == DESCENDING)
comparison = 1;
else
comparison = -1;
}
else if ( o1 != null && o2 != null ) {
if(o1.getClass().equals(Double.class)) {
comparator = getComparator( Double.class );
}
else if(o1.getClass().equals(Integer.class)) {
comparator = getComparator( Integer.class );
}
else if(o1.getClass().equals(Point.class)) {
comparator = getComparator( Double.class );
// If sortColumn is in the matrix display, then model.getValueAt()
// returns a Point object that represents a coordinate into the
// display matrix. This is done so that the display matrix object
// can be asked for both the color and the value. We are here only
// interested in the value.
if (m_matrixDisplay != null) {
Point p1 = ( Point ) o1;
Point p2 = ( Point ) o2;
o1 = new Double( m_matrixDisplay.getValue( p1.x, p1.y ) );
o2 = new Double( m_matrixDisplay.getValue( p2.x, p2.y ) );
}
}
else if(o1.getClass().equals(ArrayList.class)) {
comparator = getComparator( Double.class );
if (m_matrixDisplay != null) {
// Because of the bar graph cell renderer, getValueAt
// in our table model returns an array of two values:
// the first is the actual p value, and the second is
// the expected p value. Here, we want to sort by
// the actual p value, which should be the first item
// in the array list.
Double a = ( Double ) ( ( ArrayList ) o1 ).get( 0 );
Double b = ( Double ) ( ( ArrayList ) o2 ).get( 0 );
// yes, we did get an array list, but we want to
// compare the Double values the array lists contain,
// not the array lists themselves.
o1 = a;
o2 = b;
}
}
else {
comparator=getComparator( column );
}
comparison = comparator.compare( o1, o2 );
}
if (comparison != 0) {
return directive.direction == DESCENDING ? -comparison : comparison;
}
}
return 0;
}
}
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not sorting by anything, just pass the event along.
if (!isSorting()) {
clearSortingState();
fireTableChanged(e);
return;
}
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
cancelSorting();
fireTableChanged(e);
return;
}
// We can map a cell event through to the view without widening
// when the following conditions apply:
//
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
//
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
//
// The last check, for (modelToView != null) is to see if modelToView
// is already allocated. If we don't do this check; sorting can become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow()
&& column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED
&& modelToView != null) {
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this,
viewIndex, viewIndex,
column, e.getType()));
return;
}
// Something has happened to the data that may have invalidated the row order.
clearSortingState();
fireTableDataChanged();
return;
}
}
private class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if(e.getButton()==MouseEvent.BUTTON1)
{
JTableHeader h = ( JTableHeader ) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX( e.getX() );
int column = columnModel.getColumn( viewColumn ).getModelIndex();
if ( column != -1 ) {
int status = getSortingStatus( column );
if ( !e.isControlDown() ) {
cancelSorting();
}
// Cycle the sorting states through {ASCENDING, DESCENDING} ignoring NOT_SORTED
status = ( status == ASCENDING ) ? DESCENDING : ASCENDING;
setSortingStatus( column, status );
}
}
}
}
private static class Arrow implements Icon {
private boolean descending;
private int size;
private int priority;
public Arrow(boolean descending, int size, int priority) {
this.descending = descending;
this.size = size;
this.priority = priority;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Color color = c == null ? Color.GRAY : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
}
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
}
public int getIconWidth() {
return size;
}
public int getIconHeight() {
return size;
}
}
private class SortableHeaderRenderer implements TableCellRenderer {
private TableCellRenderer tableCellRenderer;
public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
this.tableCellRenderer = tableCellRenderer;
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = tableCellRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
l.setHorizontalTextPosition( JLabel.LEFT );
l.setVerticalAlignment( JLabel.BOTTOM );
int modelColumn = table.convertColumnIndexToModel(column);
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
}
return c;
}
}
private static class Directive {
private int column;
private int direction;
public Directive(int column, int direction) {
this.column = column;
this.direction = direction;
}
}
}
| No NullPointerException will result if a user mouse-clicks to the right of the table header (outside the table but within the view port -- the table has to be smaller than the viewport for this).
| src/baseCode/gui/table/TableSorter.java | No NullPointerException will result if a user mouse-clicks to the right of the table header (outside the table but within the view port -- the table has to be smaller than the viewport for this). | <ide><path>rc/baseCode/gui/table/TableSorter.java
<ide> this( tableModel );
<ide> m_matrixDisplay = matrixDisplay;
<ide> }
<del>
<add>
<ide> private void clearSortingState() {
<ide> viewToModel = null;
<ide> modelToView = null;
<ide> }
<ide> else if(o1.getClass().equals(Point.class)) {
<ide> comparator = getComparator( Double.class );
<del>
<add>
<ide> // If sortColumn is in the matrix display, then model.getValueAt()
<ide> // returns a Point object that represents a coordinate into the
<ide> // display matrix. This is done so that the display matrix object
<ide> }
<ide> else if(o1.getClass().equals(ArrayList.class)) {
<ide> comparator = getComparator( Double.class );
<del>
<add>
<ide> if (m_matrixDisplay != null) {
<ide>
<ide> // Because of the bar graph cell renderer, getValueAt
<ide> // in our table model returns an array of two values:
<ide> // the first is the actual p value, and the second is
<del> // the expected p value. Here, we want to sort by
<add> // the expected p value. Here, we want to sort by
<ide> // the actual p value, which should be the first item
<ide> // in the array list.
<del>
<add>
<ide> Double a = ( Double ) ( ( ArrayList ) o1 ).get( 0 );
<ide> Double b = ( Double ) ( ( ArrayList ) o2 ).get( 0 );
<ide>
<ide> JTableHeader h = ( JTableHeader ) e.getSource();
<ide> TableColumnModel columnModel = h.getColumnModel();
<ide> int viewColumn = columnModel.getColumnIndexAtX( e.getX() );
<add> if ( viewColumn == -1) return;
<add>
<ide> int column = columnModel.getColumn( viewColumn ).getModelIndex();
<ide> if ( column != -1 ) {
<ide> int status = getSortingStatus( column ); |
|
JavaScript | mit | fd684bc94f15bb03d61b5879dea7d3e67aca9a78 | 0 | letsroundup/landing-page | import React from 'react';
import favicon from 'images/favicon.png';
import appleTouchIcon from 'images/apple-touch-icon.png';
import logoImg from 'images/square512.png';
const KEYWORDS = [
'planning', 'calendar', 'dynamic pricing', 'chat',
'group', 'app', 'iphone', 'startup',
'together', 'deals', 'specials', 'bar',
'restaurant', 'restaurants', 'bars', 'happy hour',
'happy hours', 'social', 'voo', 'rdvoo', 'rendez-voo',
'rendez-vous', 'tryvoo', 'events', 'plans',
].join(',');
const commentIE = '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><![endif]-->';
const commentIE9 = '<!--[if lt IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script><![endif]-->';
const DESCRIPTION = 'Know what the places you love are offering. Solidify plans with your friends.';
const SOCIAL_DESCRIPTION = 'Voo helps you and your friends go to the places you love, for less.';
const NAME = 'Voo';
export default React.createClass({
displayName: 'Head',
propTypes: {
title: React.PropTypes.string.isRequired,
},
getDefaultProps() {
return { title: 'Try Voo' };
},
render() {
return (
<head>
<meta charSet="UTF-8"/>
<title>{this.props.title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="description" content={DESCRIPTION}/>
<meta name="keywords" content={KEYWORDS}/>
<meta name="author" content="RoundUp Social, Inc."/>
<meta name="react-comment-ie" dangerouslySetInnerHTML={{__html: commentIE}}/>
<meta name="react-comment-ie9" dangerouslySetInnerHTML={{__html: commentIE9}}/>
{/* Social Media metatags */}
{/* Schema.org markup for Google+ */}
<meta itemProp="name" content={NAME}/>
<meta itemProp="description" content={SOCIAL_DESCRIPTION}/>
<meta itemProp="image" content={logoImg}/>
{/* Twitter Card data */}
<meta name="twitter:card" content="app"/>
<meta name="twitter:site" content="@RdVoo"/>
<meta name="twitter:description" content={SOCIAL_DESCRIPTION}/>
<meta name="twitter:app:name:iphone" content={NAME}/>
<meta name="twitter:app:id:iphone" content="1035084963"/>
<meta name="twitter:app:id:ipad" content=""/>
<meta name="twitter:app:id:googleplay" content=""/>
<meta name="twitter:title" content={NAME}/>
<meta name="twitter:image" content={logoImg}/>
{/* Open Graph data */}
<meta property="og:title" content={NAME}/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="http://www.tryvoo.com"/>
<meta property="og:image" content={logoImg}/>
<meta property="og:description" content={SOCIAL_DESCRIPTION}/>
<meta property="og:site_name" content={NAME}/>
{/* Favicons And Touch Icons */}
<link rel="shortcut icon" type="image/png" href={favicon}/>
<link rel="apple-touch-icon" href={appleTouchIcon}/>
{/* Stylesheets */}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400" rel="stylesheet" type="text/css"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.css" rel="stylesheet"/>
<link href="css/jssocials.css" rel="stylesheet" type="text/css"/>
<link href="css/jssocials-theme-custom.css" rel="stylesheet" type="text/css"/>
<link href="css/style.css" rel="stylesheet"/>
<link href="/main.css" rel="stylesheet" type="text/css"/>
{/* Scripts */}
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"/>
<script src="/analytics.js"/>
</head>
);
},
});
| src/components/Head/Head.js | import React from 'react';
import favicon from 'images/favicon.png';
import appleTouchIcon from 'images/apple-touch-icon.png';
import logoImg from 'images/square512.png';
const KEYWORDS = [
'planning', 'calendar', 'dynamic pricing', 'chat',
'group', 'app', 'iphone', 'startup',
'together', 'deals', 'specials', 'bar',
'restaurant', 'restaurants', 'bars', 'happy hour',
'happy hours', 'social', 'voo', 'rdvoo', 'rendez-voo',
'rendez-vous', 'tryvoo', 'events', 'plans',
].join(',');
const commentIE = '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><![endif]-->';
const commentIE9 = '<!--[if lt IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script><![endif]-->';
const DESCRIPTION = 'Know what the places you love are offering. Solidify plans with your friends.';
const SOCIAL_DESCRIPTION = 'Voo helps you and your friends to go to the places you love, for less.';
const NAME = 'Voo';
export default React.createClass({
displayName: 'Head',
propTypes: {
title: React.PropTypes.string.isRequired,
},
getDefaultProps() {
return { title: 'Try Voo' };
},
render() {
return (
<head>
<meta charSet="UTF-8"/>
<title>{this.props.title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="description" content={DESCRIPTION}/>
<meta name="keywords" content={KEYWORDS}/>
<meta name="author" content="RoundUp Social, Inc."/>
<meta name="react-comment-ie" dangerouslySetInnerHTML={{__html: commentIE}}/>
<meta name="react-comment-ie9" dangerouslySetInnerHTML={{__html: commentIE9}}/>
{/* Social Media metatags */}
{/* Schema.org markup for Google+ */}
<meta itemProp="name" content={NAME}/>
<meta itemProp="description" content={SOCIAL_DESCRIPTION}/>
<meta itemProp="image" content={logoImg}/>
{/* Twitter Card data */}
<meta name="twitter:card" content="app"/>
<meta name="twitter:site" content="@RdVoo"/>
<meta name="twitter:description" content={SOCIAL_DESCRIPTION}/>
<meta name="twitter:app:name:iphone" content={NAME}/>
<meta name="twitter:app:id:iphone" content="1035084963"/>
<meta name="twitter:app:id:ipad" content=""/>
<meta name="twitter:app:id:googleplay" content=""/>
<meta name="twitter:title" content={NAME}/>
<meta name="twitter:image" content={logoImg}/>
{/* Open Graph data */}
<meta property="og:title" content={NAME}/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="http://www.tryvoo.com"/>
<meta property="og:image" content={logoImg}/>
<meta property="og:description" content={SOCIAL_DESCRIPTION}/>
<meta property="og:site_name" content={NAME}/>
{/* Favicons And Touch Icons */}
<link rel="shortcut icon" type="image/png" href={favicon}/>
<link rel="apple-touch-icon" href={appleTouchIcon}/>
{/* Stylesheets */}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<link href="http://fonts.googleapis.com/css?family=Roboto:100,300,400" rel="stylesheet" type="text/css"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.css" rel="stylesheet"/>
<link href="css/jssocials.css" rel="stylesheet" type="text/css"/>
<link href="css/jssocials-theme-custom.css" rel="stylesheet" type="text/css"/>
<link href="css/style.css" rel="stylesheet"/>
<link href="/main.css" rel="stylesheet" type="text/css"/>
{/* Scripts */}
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"/>
<script src="/analytics.js"/>
</head>
);
},
});
| [fixed] https for google fonts
| src/components/Head/Head.js | [fixed] https for google fonts | <ide><path>rc/components/Head/Head.js
<ide> const commentIE9 = '<!--[if lt IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script><![endif]-->';
<ide>
<ide> const DESCRIPTION = 'Know what the places you love are offering. Solidify plans with your friends.';
<del>const SOCIAL_DESCRIPTION = 'Voo helps you and your friends to go to the places you love, for less.';
<add>const SOCIAL_DESCRIPTION = 'Voo helps you and your friends go to the places you love, for less.';
<ide> const NAME = 'Voo';
<ide>
<ide> export default React.createClass({
<ide>
<ide> {/* Stylesheets */}
<ide> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<del> <link href="http://fonts.googleapis.com/css?family=Roboto:100,300,400" rel="stylesheet" type="text/css"/>
<del> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<add> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400" rel="stylesheet" type="text/css"/>
<add> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<ide> <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.css" rel="stylesheet"/>
<ide> <link href="css/jssocials.css" rel="stylesheet" type="text/css"/>
<ide> <link href="css/jssocials-theme-custom.css" rel="stylesheet" type="text/css"/> |
|
Java | bsd-2-clause | 8e1252ba5d6149c8a3ba70717446d42f5d36293f | 0 | l2-/runelite,runelite/runelite,runelite/runelite,Sethtroll/runelite,l2-/runelite,runelite/runelite,Sethtroll/runelite | /*
* Copyright (c) 2017. l2-
* Copyright (c) 2017, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 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 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 net.runelite.client.plugins.chatcommands;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.inject.Provides;
import java.io.IOException;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.Constants;
import net.runelite.api.Experience;
import net.runelite.api.IconID;
import net.runelite.api.ItemComposition;
import net.runelite.api.MessageNode;
import net.runelite.api.Player;
import net.runelite.api.VarPlayer;
import net.runelite.api.Varbits;
import net.runelite.api.WorldType;
import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick;
import net.runelite.api.events.VarbitChanged;
import net.runelite.api.events.WidgetLoaded;
import net.runelite.api.vars.AccountType;
import net.runelite.api.widgets.Widget;
import static net.runelite.api.widgets.WidgetID.ADVENTURE_LOG_ID;
import static net.runelite.api.widgets.WidgetID.GENERIC_SCROLL_GROUP_ID;
import static net.runelite.api.widgets.WidgetID.KILL_LOGS_GROUP_ID;
import net.runelite.api.widgets.WidgetInfo;
import net.runelite.client.chat.ChatColorType;
import net.runelite.client.chat.ChatCommandManager;
import net.runelite.client.chat.ChatMessageBuilder;
import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.events.ChatInput;
import net.runelite.client.game.ItemManager;
import net.runelite.client.input.KeyManager;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.util.QuantityFormatter;
import net.runelite.client.util.Text;
import net.runelite.http.api.chat.ChatClient;
import net.runelite.http.api.chat.Duels;
import net.runelite.http.api.hiscore.HiscoreClient;
import net.runelite.http.api.hiscore.HiscoreEndpoint;
import net.runelite.http.api.hiscore.HiscoreResult;
import net.runelite.http.api.hiscore.HiscoreSkill;
import net.runelite.http.api.hiscore.SingleHiscoreSkillResult;
import net.runelite.http.api.hiscore.Skill;
import net.runelite.http.api.item.ItemPrice;
import org.apache.commons.text.WordUtils;
@PluginDescriptor(
name = "Chat Commands",
description = "Enable chat commands",
tags = {"grand", "exchange", "level", "prices"}
)
@Slf4j
public class ChatCommandsPlugin extends Plugin
{
private static final Pattern KILLCOUNT_PATTERN = Pattern.compile("Your (.+) (?:kill|harvest|lap|completion) count is: <col=ff0000>(\\d+)</col>");
private static final Pattern RAIDS_PATTERN = Pattern.compile("Your completed (.+) count is: <col=ff0000>(\\d+)</col>");
private static final Pattern RAIDS_PB_PATTERN = Pattern.compile("<col=ef20ff>Congratulations - your raid is complete!</col><br>Team size: <col=ff0000>(?:[0-9]+ players|Solo)</col> Duration:</col> <col=ff0000>(?<pb>[0-9:]+)</col> \\(new personal best\\)</col>");
private static final Pattern TOB_WAVE_PB_PATTERN = Pattern.compile("^.*Theatre of Blood wave completion time: <col=ff0000>(?<pb>[0-9:]+)</col> \\(Personal best!\\)");
private static final Pattern TOB_WAVE_DURATION_PATTERN = Pattern.compile("^.*Theatre of Blood wave completion time: <col=ff0000>[0-9:]+</col><br></col>Personal best: (?<pb>[0-9:]+)");
private static final Pattern WINTERTODT_PATTERN = Pattern.compile("Your subdued Wintertodt count is: <col=ff0000>(\\d+)</col>");
private static final Pattern BARROWS_PATTERN = Pattern.compile("Your Barrows chest count is: <col=ff0000>(\\d+)</col>");
private static final Pattern KILL_DURATION_PATTERN = Pattern.compile("(?i)^(?:Fight |Lap |Challenge |Corrupted challenge )?duration: <col=ff0000>[0-9:]+</col>\\. Personal best: (?<pb>[0-9:]+)");
private static final Pattern NEW_PB_PATTERN = Pattern.compile("(?i)^(?:Fight |Lap |Challenge |Corrupted challenge )?duration: <col=ff0000>(?<pb>[0-9:]+)</col> \\(new personal best\\)");
private static final Pattern DUEL_ARENA_WINS_PATTERN = Pattern.compile("You (were defeated|won)! You have(?: now)? won (\\d+) duels?");
private static final Pattern DUEL_ARENA_LOSSES_PATTERN = Pattern.compile("You have(?: now)? lost (\\d+) duels?");
private static final Pattern ADVENTURE_LOG_TITLE_PATTERN = Pattern.compile("The Exploits of (.+)");
private static final Pattern ADVENTURE_LOG_COX_PB_PATTERN = Pattern.compile("Fastest (?:kill|run)(?: - \\(Team size: (?:[0-9]+ players|Solo)\\))?: ([0-9:]+)");
private static final Pattern ADVENTURE_LOG_BOSS_PB_PATTERN = Pattern.compile("[a-zA-Z]+(?: [a-zA-Z]+)*");
private static final Pattern ADVENTURE_LOG_PB_PATTERN = Pattern.compile("(" + ADVENTURE_LOG_BOSS_PB_PATTERN + "(?: - " + ADVENTURE_LOG_BOSS_PB_PATTERN + ")*) (?:" + ADVENTURE_LOG_COX_PB_PATTERN + "( )*)+");
private static final Pattern HS_PB_PATTERN = Pattern.compile("Floor (?<floor>\\d) time: <col=ff0000>(?<floortime>[0-9:]+)</col>(?: \\(new personal best\\)|. Personal best: (?<floorpb>[0-9:]+))" +
"(?:<br>Overall time: <col=ff0000>(?<otime>[0-9:]+)</col>(?: \\(new personal best\\)|. Personal best: (?<opb>[0-9:]+)))?");
private static final Pattern HS_KC_FLOOR_PATTERN = Pattern.compile("You have completed Floor (\\d) of the Hallowed Sepulchre! Total completions: <col=ff0000>(\\d+)</col>\\.");
private static final Pattern HS_KC_GHC_PATTERN = Pattern.compile("You have opened the Grand Hallowed Coffin <col=ff0000>(\\d+)</col> times?!");
private static final String TOTAL_LEVEL_COMMAND_STRING = "!total";
private static final String PRICE_COMMAND_STRING = "!price";
private static final String LEVEL_COMMAND_STRING = "!lvl";
private static final String BOUNTY_HUNTER_HUNTER_COMMAND = "!bh";
private static final String BOUNTY_HUNTER_ROGUE_COMMAND = "!bhrogue";
private static final String CLUES_COMMAND_STRING = "!clues";
private static final String LAST_MAN_STANDING_COMMAND = "!lms";
private static final String KILLCOUNT_COMMAND_STRING = "!kc";
private static final String CMB_COMMAND_STRING = "!cmb";
private static final String QP_COMMAND_STRING = "!qp";
private static final String PB_COMMAND = "!pb";
private static final String GC_COMMAND_STRING = "!gc";
private static final String DUEL_ARENA_COMMAND = "!duels";
@VisibleForTesting
static final int ADV_LOG_EXPLOITS_TEXT_INDEX = 1;
private final ChatClient chatClient = new ChatClient();
private boolean bossLogLoaded;
private boolean advLogLoaded;
private boolean scrollInterfaceLoaded;
private String pohOwner;
private HiscoreEndpoint hiscoreEndpoint; // hiscore endpoint for current player
private String lastBossKill;
private int lastPb = -1;
@Inject
private Client client;
@Inject
private ChatCommandsConfig config;
@Inject
private ConfigManager configManager;
@Inject
private ItemManager itemManager;
@Inject
private ChatMessageManager chatMessageManager;
@Inject
private ChatCommandManager chatCommandManager;
@Inject
private ScheduledExecutorService executor;
@Inject
private KeyManager keyManager;
@Inject
private ChatKeyboardListener chatKeyboardListener;
@Inject
private HiscoreClient hiscoreClient;
@Override
public void startUp()
{
keyManager.registerKeyListener(chatKeyboardListener);
chatCommandManager.registerCommandAsync(TOTAL_LEVEL_COMMAND_STRING, this::playerSkillLookup);
chatCommandManager.registerCommandAsync(CMB_COMMAND_STRING, this::combatLevelLookup);
chatCommandManager.registerCommand(PRICE_COMMAND_STRING, this::itemPriceLookup);
chatCommandManager.registerCommandAsync(LEVEL_COMMAND_STRING, this::playerSkillLookup);
chatCommandManager.registerCommandAsync(BOUNTY_HUNTER_HUNTER_COMMAND, this::bountyHunterHunterLookup);
chatCommandManager.registerCommandAsync(BOUNTY_HUNTER_ROGUE_COMMAND, this::bountyHunterRogueLookup);
chatCommandManager.registerCommandAsync(CLUES_COMMAND_STRING, this::clueLookup);
chatCommandManager.registerCommandAsync(LAST_MAN_STANDING_COMMAND, this::lastManStandingLookup);
chatCommandManager.registerCommandAsync(KILLCOUNT_COMMAND_STRING, this::killCountLookup, this::killCountSubmit);
chatCommandManager.registerCommandAsync(QP_COMMAND_STRING, this::questPointsLookup, this::questPointsSubmit);
chatCommandManager.registerCommandAsync(PB_COMMAND, this::personalBestLookup, this::personalBestSubmit);
chatCommandManager.registerCommandAsync(GC_COMMAND_STRING, this::gambleCountLookup, this::gambleCountSubmit);
chatCommandManager.registerCommandAsync(DUEL_ARENA_COMMAND, this::duelArenaLookup, this::duelArenaSubmit);
}
@Override
public void shutDown()
{
lastBossKill = null;
keyManager.unregisterKeyListener(chatKeyboardListener);
chatCommandManager.unregisterCommand(TOTAL_LEVEL_COMMAND_STRING);
chatCommandManager.unregisterCommand(CMB_COMMAND_STRING);
chatCommandManager.unregisterCommand(PRICE_COMMAND_STRING);
chatCommandManager.unregisterCommand(LEVEL_COMMAND_STRING);
chatCommandManager.unregisterCommand(CLUES_COMMAND_STRING);
chatCommandManager.unregisterCommand(KILLCOUNT_COMMAND_STRING);
chatCommandManager.unregisterCommand(QP_COMMAND_STRING);
chatCommandManager.unregisterCommand(PB_COMMAND);
chatCommandManager.unregisterCommand(GC_COMMAND_STRING);
chatCommandManager.unregisterCommand(DUEL_ARENA_COMMAND);
}
@Provides
ChatCommandsConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(ChatCommandsConfig.class);
}
private void setKc(String boss, int killcount)
{
configManager.setConfiguration("killcount." + client.getUsername().toLowerCase(),
boss.toLowerCase(), killcount);
}
private int getKc(String boss)
{
Integer killCount = configManager.getConfiguration("killcount." + client.getUsername().toLowerCase(),
boss.toLowerCase(), int.class);
return killCount == null ? 0 : killCount;
}
private void setPb(String boss, int seconds)
{
configManager.setConfiguration("personalbest." + client.getUsername().toLowerCase(),
boss.toLowerCase(), seconds);
}
private int getPb(String boss)
{
Integer personalBest = configManager.getConfiguration("personalbest." + client.getUsername().toLowerCase(),
boss.toLowerCase(), int.class);
return personalBest == null ? 0 : personalBest;
}
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}
String message = chatMessage.getMessage();
Matcher matcher = KILLCOUNT_PATTERN.matcher(message);
if (matcher.find())
{
String boss = matcher.group(1);
int kc = Integer.parseInt(matcher.group(2));
setKc(boss, kc);
// We either already have the pb, or need to remember the boss for the upcoming pb
if (lastPb > -1)
{
log.debug("Got out-of-order personal best for {}: {}", boss, lastPb);
setPb(boss, lastPb);
lastPb = -1;
}
else
{
lastBossKill = boss;
}
return;
}
matcher = WINTERTODT_PATTERN.matcher(message);
if (matcher.find())
{
int kc = Integer.parseInt(matcher.group(1));
setKc("Wintertodt", kc);
}
matcher = RAIDS_PATTERN.matcher(message);
if (matcher.find())
{
String boss = matcher.group(1);
int kc = Integer.parseInt(matcher.group(2));
setKc(boss, kc);
if (lastPb > -1)
{
// lastPb contains the last raid duration and not the personal best, because the raid
// complete message does not include the pb. We have to check if it is a new pb:
int currentPb = getPb(boss);
if (currentPb <= 0 || lastPb < currentPb)
{
setPb(boss, lastPb);
}
lastPb = -1;
}
lastBossKill = boss;
return;
}
matcher = DUEL_ARENA_WINS_PATTERN.matcher(message);
if (matcher.find())
{
final int oldWins = getKc("Duel Arena Wins");
final int wins = Integer.parseInt(matcher.group(2));
final String result = matcher.group(1);
int winningStreak = getKc("Duel Arena Win Streak");
int losingStreak = getKc("Duel Arena Lose Streak");
if (result.equals("won") && wins > oldWins)
{
losingStreak = 0;
winningStreak += 1;
}
else if (result.equals("were defeated"))
{
losingStreak += 1;
winningStreak = 0;
}
else
{
log.warn("unrecognized duel streak chat message: {}", message);
}
setKc("Duel Arena Wins", wins);
setKc("Duel Arena Win Streak", winningStreak);
setKc("Duel Arena Lose Streak", losingStreak);
}
matcher = DUEL_ARENA_LOSSES_PATTERN.matcher(message);
if (matcher.find())
{
int losses = Integer.parseInt(matcher.group(1));
setKc("Duel Arena Losses", losses);
}
matcher = BARROWS_PATTERN.matcher(message);
if (matcher.find())
{
int kc = Integer.parseInt(matcher.group(1));
setKc("Barrows Chests", kc);
}
matcher = KILL_DURATION_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = NEW_PB_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = RAIDS_PB_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = TOB_WAVE_PB_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = TOB_WAVE_DURATION_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = HS_PB_PATTERN.matcher(message);
if (matcher.find())
{
int floor = Integer.parseInt(matcher.group("floor"));
String floortime = matcher.group("floortime");
String floorpb = matcher.group("floorpb");
String otime = matcher.group("otime");
String opb = matcher.group("opb");
String pb = MoreObjects.firstNonNull(floorpb, floortime);
setPb("Hallowed Sepulchre Floor " + floor, timeStringToSeconds(pb));
if (otime != null)
{
pb = MoreObjects.firstNonNull(opb, otime);
setPb("Hallowed Sepulchre", timeStringToSeconds(pb));
}
}
matcher = HS_KC_FLOOR_PATTERN.matcher(message);
if (matcher.find())
{
int floor = Integer.parseInt(matcher.group(1));
int kc = Integer.parseInt(matcher.group(2));
setKc("Hallowed Sepulchre Floor " + floor, kc);
}
matcher = HS_KC_GHC_PATTERN.matcher(message);
if (matcher.find())
{
int kc = Integer.parseInt(matcher.group(1));
setKc("Hallowed Sepulchre", kc);
}
lastBossKill = null;
}
private static int timeStringToSeconds(String timeString)
{
String[] s = timeString.split(":");
if (s.length == 2) // mm:ss
{
return Integer.parseInt(s[0]) * 60 + Integer.parseInt(s[1]);
}
else if (s.length == 3) // h:mm:ss
{
return Integer.parseInt(s[0]) * 60 * 60 + Integer.parseInt(s[1]) * 60 + Integer.parseInt(s[2]);
}
return Integer.parseInt(timeString);
}
private void matchPb(Matcher matcher)
{
int seconds = timeStringToSeconds(matcher.group("pb"));
if (lastBossKill != null)
{
// Most bosses sent boss kill message, and then pb message, so we
// use the remembered lastBossKill
log.debug("Got personal best for {}: {}", lastBossKill, seconds);
setPb(lastBossKill, seconds);
lastPb = -1;
}
else
{
// Some bosses send the pb message, and then the kill message!
lastPb = seconds;
}
}
@Subscribe
public void onGameTick(GameTick event)
{
if (client.getLocalPlayer() == null)
{
return;
}
if (advLogLoaded)
{
advLogLoaded = false;
Widget adventureLog = client.getWidget(WidgetInfo.ADVENTURE_LOG);
Matcher advLogExploitsText = ADVENTURE_LOG_TITLE_PATTERN.matcher(adventureLog.getChild(ADV_LOG_EXPLOITS_TEXT_INDEX).getText());
if (advLogExploitsText.find())
{
pohOwner = advLogExploitsText.group(1);
}
}
if (bossLogLoaded && (pohOwner == null || pohOwner.equals(client.getLocalPlayer().getName())))
{
bossLogLoaded = false;
Widget title = client.getWidget(WidgetInfo.KILL_LOG_TITLE);
Widget bossMonster = client.getWidget(WidgetInfo.KILL_LOG_MONSTER);
Widget bossKills = client.getWidget(WidgetInfo.KILL_LOG_KILLS);
if (title == null || bossMonster == null || bossKills == null
|| !"Boss Kill Log".equals(title.getText()))
{
return;
}
Widget[] bossChildren = bossMonster.getChildren();
Widget[] killsChildren = bossKills.getChildren();
for (int i = 0; i < bossChildren.length; ++i)
{
Widget boss = bossChildren[i];
Widget kill = killsChildren[i];
String bossName = boss.getText().replace(":", "");
int kc = Integer.parseInt(kill.getText().replace(",", ""));
if (kc != getKc(longBossName(bossName)))
{
setKc(longBossName(bossName), kc);
}
}
}
if (scrollInterfaceLoaded)
{
scrollInterfaceLoaded = false;
if (client.getLocalPlayer().getName().equals(pohOwner))
{
String counterText = Text.sanitizeMultilineText(client.getWidget(WidgetInfo.GENERIC_SCROLL_TEXT).getText());
Matcher mCounterText = ADVENTURE_LOG_PB_PATTERN.matcher(counterText);
while (mCounterText.find())
{
String bossName = longBossName(mCounterText.group(1));
if (bossName.equalsIgnoreCase("chambers of xeric") ||
bossName.equalsIgnoreCase("chambers of xeric challenge mode"))
{
Matcher mCoxRuns = ADVENTURE_LOG_COX_PB_PATTERN.matcher(mCounterText.group());
int bestPbTime = Integer.MAX_VALUE;
while (mCoxRuns.find())
{
bestPbTime = Math.min(timeStringToSeconds(mCoxRuns.group(1)), bestPbTime);
}
// So we don't reset people's already saved PB's if they had one before the update
int currentPb = getPb(bossName);
if (currentPb == 0 || currentPb > bestPbTime)
{
setPb(bossName, bestPbTime);
}
}
else
{
String pbTime = mCounterText.group(2);
setPb(bossName, timeStringToSeconds(pbTime));
}
}
}
}
}
@Subscribe
public void onWidgetLoaded(WidgetLoaded widget)
{
switch (widget.getGroupId())
{
case ADVENTURE_LOG_ID:
advLogLoaded = true;
break;
case KILL_LOGS_GROUP_ID:
bossLogLoaded = true;
break;
case GENERIC_SCROLL_GROUP_ID:
scrollInterfaceLoaded = true;
break;
}
}
@Subscribe
public void onGameStateChanged(GameStateChanged event)
{
switch (event.getGameState())
{
case LOADING:
case HOPPING:
pohOwner = null;
}
}
@Subscribe
public void onVarbitChanged(VarbitChanged varbitChanged)
{
hiscoreEndpoint = getLocalHiscoreEndpointType();
}
private boolean killCountSubmit(ChatInput chatInput, String value)
{
int idx = value.indexOf(' ');
final String boss = longBossName(value.substring(idx + 1));
final int kc = getKc(boss);
if (kc <= 0)
{
return false;
}
final String playerName = client.getLocalPlayer().getName();
executor.execute(() ->
{
try
{
chatClient.submitKc(playerName, boss, kc);
}
catch (Exception ex)
{
log.warn("unable to submit killcount", ex);
}
finally
{
chatInput.resume();
}
});
return true;
}
private void killCountLookup(ChatMessage chatMessage, String message)
{
if (!config.killcount())
{
return;
}
if (message.length() <= KILLCOUNT_COMMAND_STRING.length())
{
return;
}
ChatMessageType type = chatMessage.getType();
String search = message.substring(KILLCOUNT_COMMAND_STRING.length() + 1);
final String player;
if (type.equals(ChatMessageType.PRIVATECHATOUT))
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
search = longBossName(search);
final int kc;
try
{
kc = chatClient.getKc(player, search);
}
catch (IOException ex)
{
log.debug("unable to lookup killcount", ex);
return;
}
String response = new ChatMessageBuilder()
.append(ChatColorType.HIGHLIGHT)
.append(search)
.append(ChatColorType.NORMAL)
.append(" kill count: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(kc))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
private boolean duelArenaSubmit(ChatInput chatInput, String value)
{
final int wins = getKc("Duel Arena Wins");
final int losses = getKc("Duel Arena Losses");
final int winningStreak = getKc("Duel Arena Win Streak");
final int losingStreak = getKc("Duel Arena Lose Streak");
if (wins <= 0 && losses <= 0 && winningStreak <= 0 && losingStreak <= 0)
{
return false;
}
final String playerName = client.getLocalPlayer().getName();
executor.execute(() ->
{
try
{
chatClient.submitDuels(playerName, wins, losses, winningStreak, losingStreak);
}
catch (Exception ex)
{
log.warn("unable to submit duels", ex);
}
finally
{
chatInput.resume();
}
});
return true;
}
private void duelArenaLookup(ChatMessage chatMessage, String message)
{
if (!config.duels())
{
return;
}
ChatMessageType type = chatMessage.getType();
final String player;
if (type == ChatMessageType.PRIVATECHATOUT)
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
Duels duels;
try
{
duels = chatClient.getDuels(player);
}
catch (IOException ex)
{
log.debug("unable to lookup duels", ex);
return;
}
final int wins = duels.getWins();
final int losses = duels.getLosses();
final int winningStreak = duels.getWinningStreak();
final int losingStreak = duels.getLosingStreak();
String response = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Duel Arena wins: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(wins))
.append(ChatColorType.NORMAL)
.append(" losses: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(losses))
.append(ChatColorType.NORMAL)
.append(" streak: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString((winningStreak != 0 ? winningStreak : -losingStreak)))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
private void questPointsLookup(ChatMessage chatMessage, String message)
{
if (!config.qp())
{
return;
}
ChatMessageType type = chatMessage.getType();
final String player;
if (type.equals(ChatMessageType.PRIVATECHATOUT))
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
int qp;
try
{
qp = chatClient.getQp(player);
}
catch (IOException ex)
{
log.debug("unable to lookup quest points", ex);
return;
}
String response = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Quest points: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(qp))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
private boolean questPointsSubmit(ChatInput chatInput, String value)
{
final int qp = client.getVar(VarPlayer.QUEST_POINTS);
final String playerName = client.getLocalPlayer().getName();
executor.execute(() ->
{
try
{
chatClient.submitQp(playerName, qp);
}
catch (Exception ex)
{
log.warn("unable to submit quest points", ex);
}
finally
{
chatInput.resume();
}
});
return true;
}
private void personalBestLookup(ChatMessage chatMessage, String message)
{
if (!config.pb())
{
return;
}
if (message.length() <= PB_COMMAND.length())
{
return;
}
ChatMessageType type = chatMessage.getType();
String search = message.substring(PB_COMMAND.length() + 1);
final String player;
if (type.equals(ChatMessageType.PRIVATECHATOUT))
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
search = longBossName(search);
final int pb;
try
{
pb = chatClient.getPb(player, search);
}
catch (IOException ex)
{
log.debug("unable to lookup personal best", ex);
return;
}
int minutes = pb / 60;
int seconds = pb % 60;
String response = new ChatMessageBuilder()
.append(ChatColorType.HIGHLIGHT)
.append(search)
.append(ChatColorType.NORMAL)
.append(" personal best: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%d:%02d", minutes, seconds))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
private boolean personalBestSubmit(ChatInput chatInput, String value)
{
int idx = value.indexOf(' ');
final String boss = longBossName(value.substring(idx + 1));
final int pb = getPb(boss);
if (pb <= 0)
{
return false;
}
final String playerName = client.getLocalPlayer().getName();
executor.execute(() ->
{
try
{
chatClient.submitPb(playerName, boss, pb);
}
catch (Exception ex)
{
log.warn("unable to submit personal best", ex);
}
finally
{
chatInput.resume();
}
});
return true;
}
private void gambleCountLookup(ChatMessage chatMessage, String message)
{
if (!config.gc())
{
return;
}
ChatMessageType type = chatMessage.getType();
final String player;
if (type == ChatMessageType.PRIVATECHATOUT)
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
int gc;
try
{
gc = chatClient.getGc(player);
}
catch (IOException ex)
{
log.debug("unable to lookup gamble count", ex);
return;
}
String response = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Barbarian Assault High-level gambles: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(gc))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
private boolean gambleCountSubmit(ChatInput chatInput, String value)
{
final int gc = client.getVar(Varbits.BA_GC);
final String playerName = client.getLocalPlayer().getName();
executor.execute(() ->
{
try
{
chatClient.submitGc(playerName, gc);
}
catch (Exception ex)
{
log.warn("unable to submit gamble count", ex);
}
finally
{
chatInput.resume();
}
});
return true;
}
/**
* Looks up the item price and changes the original message to the
* response.
*
* @param chatMessage The chat message containing the command.
* @param message The chat message
*/
private void itemPriceLookup(ChatMessage chatMessage, String message)
{
if (!config.price())
{
return;
}
if (message.length() <= PRICE_COMMAND_STRING.length())
{
return;
}
MessageNode messageNode = chatMessage.getMessageNode();
String search = message.substring(PRICE_COMMAND_STRING.length() + 1);
List<ItemPrice> results = itemManager.search(search);
if (!results.isEmpty())
{
ItemPrice item = retrieveFromList(results, search);
int itemId = item.getId();
int itemPrice = item.getPrice();
final ChatMessageBuilder builder = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Price of ")
.append(ChatColorType.HIGHLIGHT)
.append(item.getName())
.append(ChatColorType.NORMAL)
.append(": GE average ")
.append(ChatColorType.HIGHLIGHT)
.append(QuantityFormatter.formatNumber(itemPrice));
ItemComposition itemComposition = itemManager.getItemComposition(itemId);
if (itemComposition != null)
{
int alchPrice = Math.round(itemComposition.getPrice() * Constants.HIGH_ALCHEMY_MULTIPLIER);
builder
.append(ChatColorType.NORMAL)
.append(" HA value ")
.append(ChatColorType.HIGHLIGHT)
.append(QuantityFormatter.formatNumber(alchPrice));
}
String response = builder.build();
log.debug("Setting response {}", response);
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
}
/**
* Looks up the player skill and changes the original message to the
* response.
*
* @param chatMessage The chat message containing the command.
* @param message The chat message
*/
private void playerSkillLookup(ChatMessage chatMessage, String message)
{
if (!config.lvl())
{
return;
}
String search;
if (message.equalsIgnoreCase(TOTAL_LEVEL_COMMAND_STRING))
{
search = "total";
}
else
{
if (message.length() <= LEVEL_COMMAND_STRING.length())
{
return;
}
search = message.substring(LEVEL_COMMAND_STRING.length() + 1);
}
search = SkillAbbreviations.getFullName(search);
final HiscoreSkill skill;
try
{
skill = HiscoreSkill.valueOf(search.toUpperCase());
}
catch (IllegalArgumentException i)
{
return;
}
final HiscoreLookup lookup = getCorrectLookupFor(chatMessage);
try
{
final SingleHiscoreSkillResult result = hiscoreClient.lookup(lookup.getName(), skill, lookup.getEndpoint());
if (result == null)
{
log.warn("unable to look up skill {} for {}: not found", skill, search);
return;
}
final Skill hiscoreSkill = result.getSkill();
ChatMessageBuilder chatMessageBuilder = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Level ")
.append(ChatColorType.HIGHLIGHT)
.append(skill.getName()).append(": ").append(String.valueOf(hiscoreSkill.getLevel()))
.append(ChatColorType.NORMAL);
if (hiscoreSkill.getExperience() != -1)
{
chatMessageBuilder.append(" Experience: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", hiscoreSkill.getExperience()))
.append(ChatColorType.NORMAL);
}
if (hiscoreSkill.getRank() != -1)
{
chatMessageBuilder.append(" Rank: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", hiscoreSkill.getRank()));
}
final String response = chatMessageBuilder.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("unable to look up skill {} for {}", skill, search, ex);
}
}
private void combatLevelLookup(ChatMessage chatMessage, String message)
{
if (!config.lvl())
{
return;
}
ChatMessageType type = chatMessage.getType();
String player;
if (type == ChatMessageType.PRIVATECHATOUT)
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
try
{
HiscoreResult playerStats = hiscoreClient.lookup(player);
if (playerStats == null)
{
log.warn("Error fetching hiscore data: not found");
return;
}
int attack = playerStats.getAttack().getLevel();
int strength = playerStats.getStrength().getLevel();
int defence = playerStats.getDefence().getLevel();
int hitpoints = playerStats.getHitpoints().getLevel();
int ranged = playerStats.getRanged().getLevel();
int prayer = playerStats.getPrayer().getLevel();
int magic = playerStats.getMagic().getLevel();
int combatLevel = Experience.getCombatLevel(attack, strength, defence, hitpoints, magic, ranged, prayer);
String response = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Combat Level: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(combatLevel))
.append(ChatColorType.NORMAL)
.append(" A: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(attack))
.append(ChatColorType.NORMAL)
.append(" S: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(strength))
.append(ChatColorType.NORMAL)
.append(" D: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(defence))
.append(ChatColorType.NORMAL)
.append(" H: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(hitpoints))
.append(ChatColorType.NORMAL)
.append(" R: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(ranged))
.append(ChatColorType.NORMAL)
.append(" P: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(prayer))
.append(ChatColorType.NORMAL)
.append(" M: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(magic))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("Error fetching hiscore data", ex);
}
}
private void bountyHunterHunterLookup(ChatMessage chatMessage, String message)
{
if (!config.bh())
{
return;
}
minigameLookup(chatMessage, HiscoreSkill.BOUNTY_HUNTER_HUNTER);
}
private void bountyHunterRogueLookup(ChatMessage chatMessage, String message)
{
if (!config.bhRogue())
{
return;
}
minigameLookup(chatMessage, HiscoreSkill.BOUNTY_HUNTER_ROGUE);
}
private void lastManStandingLookup(ChatMessage chatMessage, String message)
{
if (!config.lms())
{
return;
}
minigameLookup(chatMessage, HiscoreSkill.LAST_MAN_STANDING);
}
private void minigameLookup(ChatMessage chatMessage, HiscoreSkill minigame)
{
try
{
final Skill hiscoreSkill;
final HiscoreLookup lookup = getCorrectLookupFor(chatMessage);
final HiscoreResult result = hiscoreClient.lookup(lookup.getName(), lookup.getEndpoint());
if (result == null)
{
log.warn("error looking up {} score: not found", minigame.getName().toLowerCase());
return;
}
switch (minigame)
{
case BOUNTY_HUNTER_HUNTER:
hiscoreSkill = result.getBountyHunterHunter();
break;
case BOUNTY_HUNTER_ROGUE:
hiscoreSkill = result.getBountyHunterRogue();
break;
case LAST_MAN_STANDING:
hiscoreSkill = result.getLastManStanding();
break;
default:
log.warn("error looking up {} score: not implemented", minigame.getName().toLowerCase());
return;
}
int score = hiscoreSkill.getLevel();
if (score == -1)
{
return;
}
ChatMessageBuilder chatMessageBuilder = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append(minigame.getName())
.append(" Score: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(score));
int rank = hiscoreSkill.getRank();
if (rank != -1)
{
chatMessageBuilder.append(ChatColorType.NORMAL)
.append(" Rank: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", rank));
}
String response = chatMessageBuilder.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("error looking up {}", minigame.getName().toLowerCase(), ex);
}
}
private void clueLookup(ChatMessage chatMessage, String message)
{
if (!config.clue())
{
return;
}
String search;
if (message.equalsIgnoreCase(CLUES_COMMAND_STRING))
{
search = "total";
}
else
{
search = message.substring(CLUES_COMMAND_STRING.length() + 1);
}
try
{
final Skill hiscoreSkill;
final HiscoreLookup lookup = getCorrectLookupFor(chatMessage);
final HiscoreResult result = hiscoreClient.lookup(lookup.getName(), lookup.getEndpoint());
if (result == null)
{
log.warn("error looking up clues: not found");
return;
}
String level = search.toLowerCase();
switch (level)
{
case "beginner":
hiscoreSkill = result.getClueScrollBeginner();
break;
case "easy":
hiscoreSkill = result.getClueScrollEasy();
break;
case "medium":
hiscoreSkill = result.getClueScrollMedium();
break;
case "hard":
hiscoreSkill = result.getClueScrollHard();
break;
case "elite":
hiscoreSkill = result.getClueScrollElite();
break;
case "master":
hiscoreSkill = result.getClueScrollMaster();
break;
case "total":
hiscoreSkill = result.getClueScrollAll();
break;
default:
return;
}
int quantity = hiscoreSkill.getLevel();
int rank = hiscoreSkill.getRank();
if (quantity == -1)
{
return;
}
ChatMessageBuilder chatMessageBuilder = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Clue scroll (" + level + ")").append(": ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(quantity));
if (rank != -1)
{
chatMessageBuilder.append(ChatColorType.NORMAL)
.append(" Rank: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", rank));
}
String response = chatMessageBuilder.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("error looking up clues", ex);
}
}
/**
* Gets correct lookup data for message
*
* @param chatMessage chat message
* @return hiscore lookup data
*/
private HiscoreLookup getCorrectLookupFor(final ChatMessage chatMessage)
{
Player localPlayer = client.getLocalPlayer();
final String player = Text.sanitize(chatMessage.getName());
// If we are sending the message then just use the local hiscore endpoint for the world
if (chatMessage.getType().equals(ChatMessageType.PRIVATECHATOUT)
|| player.equals(localPlayer.getName()))
{
return new HiscoreLookup(localPlayer.getName(), hiscoreEndpoint);
}
// Public chat on a leagues world is always league hiscores, regardless of icon
if (chatMessage.getType() == ChatMessageType.PUBLICCHAT || chatMessage.getType() == ChatMessageType.MODCHAT)
{
if (client.getWorldType().contains(WorldType.LEAGUE))
{
return new HiscoreLookup(player, HiscoreEndpoint.LEAGUE);
}
}
// Get ironman status from their icon in chat
HiscoreEndpoint endpoint = getHiscoreEndpointByName(chatMessage.getName());
return new HiscoreLookup(player, endpoint);
}
/**
* Compares the names of the items in the list with the original input.
* Returns the item if its name is equal to the original input or the
* shortest match if no exact match is found.
*
* @param items List of items.
* @param originalInput String with the original input.
* @return Item which has a name equal to the original input.
*/
private ItemPrice retrieveFromList(List<ItemPrice> items, String originalInput)
{
ItemPrice shortest = null;
for (ItemPrice item : items)
{
if (item.getName().toLowerCase().equals(originalInput.toLowerCase()))
{
return item;
}
if (shortest == null || item.getName().length() < shortest.getName().length())
{
shortest = item;
}
}
// Take a guess
return shortest;
}
/**
* Looks up the ironman status of the local player. Does NOT work on other players.
*
* @return hiscore endpoint
*/
private HiscoreEndpoint getLocalHiscoreEndpointType()
{
EnumSet<WorldType> worldType = client.getWorldType();
if (worldType.contains(WorldType.LEAGUE))
{
return HiscoreEndpoint.LEAGUE;
}
return toEndPoint(client.getAccountType());
}
/**
* Returns the ironman status based on the symbol in the name of the player.
*
* @param name player name
* @return hiscore endpoint
*/
private static HiscoreEndpoint getHiscoreEndpointByName(final String name)
{
if (name.contains(IconID.IRONMAN.toString()))
{
return toEndPoint(AccountType.IRONMAN);
}
else if (name.contains(IconID.ULTIMATE_IRONMAN.toString()))
{
return toEndPoint(AccountType.ULTIMATE_IRONMAN);
}
else if (name.contains(IconID.HARDCORE_IRONMAN.toString()))
{
return toEndPoint(AccountType.HARDCORE_IRONMAN);
}
else
{
return toEndPoint(AccountType.NORMAL);
}
}
/**
* Converts account type to hiscore endpoint
*
* @param accountType account type
* @return hiscore endpoint
*/
private static HiscoreEndpoint toEndPoint(final AccountType accountType)
{
switch (accountType)
{
case IRONMAN:
return HiscoreEndpoint.IRONMAN;
case ULTIMATE_IRONMAN:
return HiscoreEndpoint.ULTIMATE_IRONMAN;
case HARDCORE_IRONMAN:
return HiscoreEndpoint.HARDCORE_IRONMAN;
default:
return HiscoreEndpoint.NORMAL;
}
}
@Value
private static class HiscoreLookup
{
private final String name;
private final HiscoreEndpoint endpoint;
}
private static String longBossName(String boss)
{
switch (boss.toLowerCase())
{
case "corp":
return "Corporeal Beast";
case "jad":
case "tzhaar fight cave":
return "TzTok-Jad";
case "kq":
return "Kalphite Queen";
case "chaos ele":
return "Chaos Elemental";
case "dusk":
case "dawn":
case "gargs":
return "Grotesque Guardians";
case "crazy arch":
return "Crazy Archaeologist";
case "deranged arch":
return "Deranged Archaeologist";
case "mole":
return "Giant Mole";
case "vetion":
return "Vet'ion";
case "vene":
return "Venenatis";
case "kbd":
return "King Black Dragon";
case "vork":
return "Vorkath";
case "sire":
return "Abyssal Sire";
case "smoke devil":
case "thermy":
return "Thermonuclear Smoke Devil";
case "cerb":
return "Cerberus";
case "zuk":
case "inferno":
return "TzKal-Zuk";
case "hydra":
return "Alchemical Hydra";
// gwd
case "sara":
case "saradomin":
case "zilyana":
case "zily":
return "Commander Zilyana";
case "zammy":
case "zamorak":
case "kril":
case "kril trutsaroth":
return "K'ril Tsutsaroth";
case "arma":
case "kree":
case "kreearra":
case "armadyl":
return "Kree'arra";
case "bando":
case "bandos":
case "graardor":
return "General Graardor";
// dks
case "supreme":
return "Dagannoth Supreme";
case "rex":
return "Dagannoth Rex";
case "prime":
return "Dagannoth Prime";
case "wt":
return "Wintertodt";
case "barrows":
return "Barrows Chests";
case "herbi":
return "Herbiboar";
// cox
case "cox":
case "xeric":
case "chambers":
case "olm":
case "raids":
return "Chambers of Xeric";
// cox cm
case "cox cm":
case "xeric cm":
case "chambers cm":
case "olm cm":
case "raids cm":
case "chambers of xeric - challenge mode":
return "Chambers of Xeric Challenge Mode";
// tob
case "tob":
case "theatre":
case "verzik":
case "verzik vitur":
case "raids 2":
return "Theatre of Blood";
// agility course
case "prif":
case "prifddinas":
return "Prifddinas Agility Course";
// The Gauntlet
case "gaunt":
case "gauntlet":
case "the gauntlet":
return "Gauntlet";
// Corrupted Gauntlet
case "cgaunt":
case "cgauntlet":
case "the corrupted gauntlet":
return "Corrupted Gauntlet";
case "the nightmare":
return "Nightmare";
// Hallowed Sepulchre
case "hs":
case "sepulchre":
case "ghc":
return "Hallowed Sepulchre";
case "hs1":
case "hs 1":
return "Hallowed Sepulchre Floor 1";
case "hs2":
case "hs 2":
return "Hallowed Sepulchre Floor 2";
case "hs3":
case "hs 3":
return "Hallowed Sepulchre Floor 3";
case "hs4":
case "hs 4":
return "Hallowed Sepulchre Floor 4";
case "hs5":
case "hs 5":
return "Hallowed Sepulchre Floor 5";
default:
return WordUtils.capitalize(boss);
}
}
}
| runelite-client/src/main/java/net/runelite/client/plugins/chatcommands/ChatCommandsPlugin.java | /*
* Copyright (c) 2017. l2-
* Copyright (c) 2017, Adam <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 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 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 net.runelite.client.plugins.chatcommands;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.inject.Provides;
import java.io.IOException;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.Constants;
import net.runelite.api.Experience;
import net.runelite.api.IconID;
import net.runelite.api.ItemComposition;
import net.runelite.api.MessageNode;
import net.runelite.api.Player;
import net.runelite.api.VarPlayer;
import net.runelite.api.Varbits;
import net.runelite.api.WorldType;
import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick;
import net.runelite.api.events.VarbitChanged;
import net.runelite.api.events.WidgetLoaded;
import net.runelite.api.vars.AccountType;
import net.runelite.api.widgets.Widget;
import static net.runelite.api.widgets.WidgetID.ADVENTURE_LOG_ID;
import static net.runelite.api.widgets.WidgetID.GENERIC_SCROLL_GROUP_ID;
import static net.runelite.api.widgets.WidgetID.KILL_LOGS_GROUP_ID;
import net.runelite.api.widgets.WidgetInfo;
import net.runelite.client.chat.ChatColorType;
import net.runelite.client.chat.ChatCommandManager;
import net.runelite.client.chat.ChatMessageBuilder;
import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.events.ChatInput;
import net.runelite.client.game.ItemManager;
import net.runelite.client.input.KeyManager;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.util.QuantityFormatter;
import net.runelite.client.util.Text;
import net.runelite.http.api.chat.ChatClient;
import net.runelite.http.api.chat.Duels;
import net.runelite.http.api.hiscore.HiscoreClient;
import net.runelite.http.api.hiscore.HiscoreEndpoint;
import net.runelite.http.api.hiscore.HiscoreResult;
import net.runelite.http.api.hiscore.HiscoreSkill;
import net.runelite.http.api.hiscore.SingleHiscoreSkillResult;
import net.runelite.http.api.hiscore.Skill;
import net.runelite.http.api.item.ItemPrice;
import org.apache.commons.text.WordUtils;
@PluginDescriptor(
name = "Chat Commands",
description = "Enable chat commands",
tags = {"grand", "exchange", "level", "prices"}
)
@Slf4j
public class ChatCommandsPlugin extends Plugin
{
private static final Pattern KILLCOUNT_PATTERN = Pattern.compile("Your (.+) (?:kill|harvest|lap|completion) count is: <col=ff0000>(\\d+)</col>");
private static final Pattern RAIDS_PATTERN = Pattern.compile("Your completed (.+) count is: <col=ff0000>(\\d+)</col>");
private static final Pattern RAIDS_PB_PATTERN = Pattern.compile("<col=ef20ff>Congratulations - your raid is complete!</col><br>Team size: <col=ff0000>(?:[0-9]+ players|Solo)</col> Duration:</col> <col=ff0000>([0-9:]+)</col> \\(new personal best\\)</col>");
private static final Pattern TOB_WAVE_PB_PATTERN = Pattern.compile("^.*Theatre of Blood wave completion time: <col=ff0000>([0-9:]+)</col> \\(Personal best!\\)");
private static final Pattern TOB_WAVE_DURATION_PATTERN = Pattern.compile("^.*Theatre of Blood wave completion time: <col=ff0000>[0-9:]+</col><br></col>Personal best: ([0-9:]+)");
private static final Pattern WINTERTODT_PATTERN = Pattern.compile("Your subdued Wintertodt count is: <col=ff0000>(\\d+)</col>");
private static final Pattern BARROWS_PATTERN = Pattern.compile("Your Barrows chest count is: <col=ff0000>(\\d+)</col>");
private static final Pattern KILL_DURATION_PATTERN = Pattern.compile("(?i)^(?:Fight |Lap |Challenge |Corrupted challenge )?duration: <col=ff0000>[0-9:]+</col>\\. Personal best: ([0-9:]+)");
private static final Pattern NEW_PB_PATTERN = Pattern.compile("(?i)^(?:Fight |Lap |Challenge |Corrupted challenge )?duration: <col=ff0000>([0-9:]+)</col> \\(new personal best\\)");
private static final Pattern DUEL_ARENA_WINS_PATTERN = Pattern.compile("You (were defeated|won)! You have(?: now)? won (\\d+) duels?");
private static final Pattern DUEL_ARENA_LOSSES_PATTERN = Pattern.compile("You have(?: now)? lost (\\d+) duels?");
private static final Pattern ADVENTURE_LOG_TITLE_PATTERN = Pattern.compile("The Exploits of (.+)");
private static final Pattern ADVENTURE_LOG_COX_PB_PATTERN = Pattern.compile("Fastest (?:kill|run)(?: - \\(Team size: (?:[0-9]+ players|Solo)\\))?: ([0-9:]+)");
private static final Pattern ADVENTURE_LOG_BOSS_PB_PATTERN = Pattern.compile("[a-zA-Z]+(?: [a-zA-Z]+)*");
private static final Pattern ADVENTURE_LOG_PB_PATTERN = Pattern.compile("(" + ADVENTURE_LOG_BOSS_PB_PATTERN + "(?: - " + ADVENTURE_LOG_BOSS_PB_PATTERN + ")*) (?:" + ADVENTURE_LOG_COX_PB_PATTERN + "( )*)+");
private static final Pattern HS_PB_PATTERN = Pattern.compile("Floor (?<floor>\\d) time: <col=ff0000>(?<floortime>[0-9:]+)</col>(?: \\(new personal best\\)|. Personal best: (?<floorpb>[0-9:]+))" +
"(?:<br>Overall time: <col=ff0000>(?<otime>[0-9:]+)</col>(?: \\(new personal best\\)|. Personal best: (?<opb>[0-9:]+)))?");
private static final Pattern HS_KC_FLOOR_PATTERN = Pattern.compile("You have completed Floor (\\d) of the Hallowed Sepulchre! Total completions: <col=ff0000>(\\d+)</col>\\.");
private static final Pattern HS_KC_GHC_PATTERN = Pattern.compile("You have opened the Grand Hallowed Coffin <col=ff0000>(\\d+)</col> times?!");
private static final String TOTAL_LEVEL_COMMAND_STRING = "!total";
private static final String PRICE_COMMAND_STRING = "!price";
private static final String LEVEL_COMMAND_STRING = "!lvl";
private static final String BOUNTY_HUNTER_HUNTER_COMMAND = "!bh";
private static final String BOUNTY_HUNTER_ROGUE_COMMAND = "!bhrogue";
private static final String CLUES_COMMAND_STRING = "!clues";
private static final String LAST_MAN_STANDING_COMMAND = "!lms";
private static final String KILLCOUNT_COMMAND_STRING = "!kc";
private static final String CMB_COMMAND_STRING = "!cmb";
private static final String QP_COMMAND_STRING = "!qp";
private static final String PB_COMMAND = "!pb";
private static final String GC_COMMAND_STRING = "!gc";
private static final String DUEL_ARENA_COMMAND = "!duels";
@VisibleForTesting
static final int ADV_LOG_EXPLOITS_TEXT_INDEX = 1;
private final ChatClient chatClient = new ChatClient();
private boolean bossLogLoaded;
private boolean advLogLoaded;
private boolean scrollInterfaceLoaded;
private String pohOwner;
private HiscoreEndpoint hiscoreEndpoint; // hiscore endpoint for current player
private String lastBossKill;
private int lastPb = -1;
@Inject
private Client client;
@Inject
private ChatCommandsConfig config;
@Inject
private ConfigManager configManager;
@Inject
private ItemManager itemManager;
@Inject
private ChatMessageManager chatMessageManager;
@Inject
private ChatCommandManager chatCommandManager;
@Inject
private ScheduledExecutorService executor;
@Inject
private KeyManager keyManager;
@Inject
private ChatKeyboardListener chatKeyboardListener;
@Inject
private HiscoreClient hiscoreClient;
@Override
public void startUp()
{
keyManager.registerKeyListener(chatKeyboardListener);
chatCommandManager.registerCommandAsync(TOTAL_LEVEL_COMMAND_STRING, this::playerSkillLookup);
chatCommandManager.registerCommandAsync(CMB_COMMAND_STRING, this::combatLevelLookup);
chatCommandManager.registerCommand(PRICE_COMMAND_STRING, this::itemPriceLookup);
chatCommandManager.registerCommandAsync(LEVEL_COMMAND_STRING, this::playerSkillLookup);
chatCommandManager.registerCommandAsync(BOUNTY_HUNTER_HUNTER_COMMAND, this::bountyHunterHunterLookup);
chatCommandManager.registerCommandAsync(BOUNTY_HUNTER_ROGUE_COMMAND, this::bountyHunterRogueLookup);
chatCommandManager.registerCommandAsync(CLUES_COMMAND_STRING, this::clueLookup);
chatCommandManager.registerCommandAsync(LAST_MAN_STANDING_COMMAND, this::lastManStandingLookup);
chatCommandManager.registerCommandAsync(KILLCOUNT_COMMAND_STRING, this::killCountLookup, this::killCountSubmit);
chatCommandManager.registerCommandAsync(QP_COMMAND_STRING, this::questPointsLookup, this::questPointsSubmit);
chatCommandManager.registerCommandAsync(PB_COMMAND, this::personalBestLookup, this::personalBestSubmit);
chatCommandManager.registerCommandAsync(GC_COMMAND_STRING, this::gambleCountLookup, this::gambleCountSubmit);
chatCommandManager.registerCommandAsync(DUEL_ARENA_COMMAND, this::duelArenaLookup, this::duelArenaSubmit);
}
@Override
public void shutDown()
{
lastBossKill = null;
keyManager.unregisterKeyListener(chatKeyboardListener);
chatCommandManager.unregisterCommand(TOTAL_LEVEL_COMMAND_STRING);
chatCommandManager.unregisterCommand(CMB_COMMAND_STRING);
chatCommandManager.unregisterCommand(PRICE_COMMAND_STRING);
chatCommandManager.unregisterCommand(LEVEL_COMMAND_STRING);
chatCommandManager.unregisterCommand(CLUES_COMMAND_STRING);
chatCommandManager.unregisterCommand(KILLCOUNT_COMMAND_STRING);
chatCommandManager.unregisterCommand(QP_COMMAND_STRING);
chatCommandManager.unregisterCommand(PB_COMMAND);
chatCommandManager.unregisterCommand(GC_COMMAND_STRING);
chatCommandManager.unregisterCommand(DUEL_ARENA_COMMAND);
}
@Provides
ChatCommandsConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(ChatCommandsConfig.class);
}
private void setKc(String boss, int killcount)
{
configManager.setConfiguration("killcount." + client.getUsername().toLowerCase(),
boss.toLowerCase(), killcount);
}
private int getKc(String boss)
{
Integer killCount = configManager.getConfiguration("killcount." + client.getUsername().toLowerCase(),
boss.toLowerCase(), int.class);
return killCount == null ? 0 : killCount;
}
private void setPb(String boss, int seconds)
{
configManager.setConfiguration("personalbest." + client.getUsername().toLowerCase(),
boss.toLowerCase(), seconds);
}
private int getPb(String boss)
{
Integer personalBest = configManager.getConfiguration("personalbest." + client.getUsername().toLowerCase(),
boss.toLowerCase(), int.class);
return personalBest == null ? 0 : personalBest;
}
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}
String message = chatMessage.getMessage();
Matcher matcher = KILLCOUNT_PATTERN.matcher(message);
if (matcher.find())
{
String boss = matcher.group(1);
int kc = Integer.parseInt(matcher.group(2));
setKc(boss, kc);
// We either already have the pb, or need to remember the boss for the upcoming pb
if (lastPb > -1)
{
log.debug("Got out-of-order personal best for {}: {}", boss, lastPb);
setPb(boss, lastPb);
lastPb = -1;
}
else
{
lastBossKill = boss;
}
return;
}
matcher = WINTERTODT_PATTERN.matcher(message);
if (matcher.find())
{
int kc = Integer.parseInt(matcher.group(1));
setKc("Wintertodt", kc);
}
matcher = RAIDS_PATTERN.matcher(message);
if (matcher.find())
{
String boss = matcher.group(1);
int kc = Integer.parseInt(matcher.group(2));
setKc(boss, kc);
if (lastPb > -1)
{
// lastPb contains the last raid duration and not the personal best, because the raid
// complete message does not include the pb. We have to check if it is a new pb:
int currentPb = getPb(boss);
if (currentPb <= 0 || lastPb < currentPb)
{
setPb(boss, lastPb);
}
lastPb = -1;
}
lastBossKill = boss;
return;
}
matcher = DUEL_ARENA_WINS_PATTERN.matcher(message);
if (matcher.find())
{
final int oldWins = getKc("Duel Arena Wins");
final int wins = Integer.parseInt(matcher.group(2));
final String result = matcher.group(1);
int winningStreak = getKc("Duel Arena Win Streak");
int losingStreak = getKc("Duel Arena Lose Streak");
if (result.equals("won") && wins > oldWins)
{
losingStreak = 0;
winningStreak += 1;
}
else if (result.equals("were defeated"))
{
losingStreak += 1;
winningStreak = 0;
}
else
{
log.warn("unrecognized duel streak chat message: {}", message);
}
setKc("Duel Arena Wins", wins);
setKc("Duel Arena Win Streak", winningStreak);
setKc("Duel Arena Lose Streak", losingStreak);
}
matcher = DUEL_ARENA_LOSSES_PATTERN.matcher(message);
if (matcher.find())
{
int losses = Integer.parseInt(matcher.group(1));
setKc("Duel Arena Losses", losses);
}
matcher = BARROWS_PATTERN.matcher(message);
if (matcher.find())
{
int kc = Integer.parseInt(matcher.group(1));
setKc("Barrows Chests", kc);
}
matcher = KILL_DURATION_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = NEW_PB_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = RAIDS_PB_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = TOB_WAVE_PB_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = TOB_WAVE_DURATION_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = HS_PB_PATTERN.matcher(message);
if (matcher.find())
{
int floor = Integer.parseInt(matcher.group("floor"));
String floortime = matcher.group("floortime");
String floorpb = matcher.group("floorpb");
String otime = matcher.group("otime");
String opb = matcher.group("opb");
String pb = MoreObjects.firstNonNull(floorpb, floortime);
setPb("Hallowed Sepulchre Floor " + floor, timeStringToSeconds(pb));
if (otime != null)
{
pb = MoreObjects.firstNonNull(opb, otime);
setPb("Hallowed Sepulchre", timeStringToSeconds(pb));
}
}
matcher = HS_KC_FLOOR_PATTERN.matcher(message);
if (matcher.find())
{
int floor = Integer.parseInt(matcher.group(1));
int kc = Integer.parseInt(matcher.group(2));
setKc("Hallowed Sepulchre Floor " + floor, kc);
}
matcher = HS_KC_GHC_PATTERN.matcher(message);
if (matcher.find())
{
int kc = Integer.parseInt(matcher.group(1));
setKc("Hallowed Sepulchre", kc);
}
lastBossKill = null;
}
private static int timeStringToSeconds(String timeString)
{
String[] s = timeString.split(":");
if (s.length == 2) // mm:ss
{
return Integer.parseInt(s[0]) * 60 + Integer.parseInt(s[1]);
}
else if (s.length == 3) // h:mm:ss
{
return Integer.parseInt(s[0]) * 60 * 60 + Integer.parseInt(s[1]) * 60 + Integer.parseInt(s[2]);
}
return Integer.parseInt(timeString);
}
private void matchPb(Matcher matcher)
{
int seconds = timeStringToSeconds(matcher.group(1));
if (lastBossKill != null)
{
// Most bosses sent boss kill message, and then pb message, so we
// use the remembered lastBossKill
log.debug("Got personal best for {}: {}", lastBossKill, seconds);
setPb(lastBossKill, seconds);
lastPb = -1;
}
else
{
// Some bosses send the pb message, and then the kill message!
lastPb = seconds;
}
}
@Subscribe
public void onGameTick(GameTick event)
{
if (client.getLocalPlayer() == null)
{
return;
}
if (advLogLoaded)
{
advLogLoaded = false;
Widget adventureLog = client.getWidget(WidgetInfo.ADVENTURE_LOG);
Matcher advLogExploitsText = ADVENTURE_LOG_TITLE_PATTERN.matcher(adventureLog.getChild(ADV_LOG_EXPLOITS_TEXT_INDEX).getText());
if (advLogExploitsText.find())
{
pohOwner = advLogExploitsText.group(1);
}
}
if (bossLogLoaded && (pohOwner == null || pohOwner.equals(client.getLocalPlayer().getName())))
{
bossLogLoaded = false;
Widget title = client.getWidget(WidgetInfo.KILL_LOG_TITLE);
Widget bossMonster = client.getWidget(WidgetInfo.KILL_LOG_MONSTER);
Widget bossKills = client.getWidget(WidgetInfo.KILL_LOG_KILLS);
if (title == null || bossMonster == null || bossKills == null
|| !"Boss Kill Log".equals(title.getText()))
{
return;
}
Widget[] bossChildren = bossMonster.getChildren();
Widget[] killsChildren = bossKills.getChildren();
for (int i = 0; i < bossChildren.length; ++i)
{
Widget boss = bossChildren[i];
Widget kill = killsChildren[i];
String bossName = boss.getText().replace(":", "");
int kc = Integer.parseInt(kill.getText().replace(",", ""));
if (kc != getKc(longBossName(bossName)))
{
setKc(longBossName(bossName), kc);
}
}
}
if (scrollInterfaceLoaded)
{
scrollInterfaceLoaded = false;
if (client.getLocalPlayer().getName().equals(pohOwner))
{
String counterText = Text.sanitizeMultilineText(client.getWidget(WidgetInfo.GENERIC_SCROLL_TEXT).getText());
Matcher mCounterText = ADVENTURE_LOG_PB_PATTERN.matcher(counterText);
while (mCounterText.find())
{
String bossName = longBossName(mCounterText.group(1));
if (bossName.equalsIgnoreCase("chambers of xeric") ||
bossName.equalsIgnoreCase("chambers of xeric challenge mode"))
{
Matcher mCoxRuns = ADVENTURE_LOG_COX_PB_PATTERN.matcher(mCounterText.group());
int bestPbTime = Integer.MAX_VALUE;
while (mCoxRuns.find())
{
bestPbTime = Math.min(timeStringToSeconds(mCoxRuns.group(1)), bestPbTime);
}
// So we don't reset people's already saved PB's if they had one before the update
int currentPb = getPb(bossName);
if (currentPb == 0 || currentPb > bestPbTime)
{
setPb(bossName, bestPbTime);
}
}
else
{
String pbTime = mCounterText.group(2);
setPb(bossName, timeStringToSeconds(pbTime));
}
}
}
}
}
@Subscribe
public void onWidgetLoaded(WidgetLoaded widget)
{
switch (widget.getGroupId())
{
case ADVENTURE_LOG_ID:
advLogLoaded = true;
break;
case KILL_LOGS_GROUP_ID:
bossLogLoaded = true;
break;
case GENERIC_SCROLL_GROUP_ID:
scrollInterfaceLoaded = true;
break;
}
}
@Subscribe
public void onGameStateChanged(GameStateChanged event)
{
switch (event.getGameState())
{
case LOADING:
case HOPPING:
pohOwner = null;
}
}
@Subscribe
public void onVarbitChanged(VarbitChanged varbitChanged)
{
hiscoreEndpoint = getLocalHiscoreEndpointType();
}
private boolean killCountSubmit(ChatInput chatInput, String value)
{
int idx = value.indexOf(' ');
final String boss = longBossName(value.substring(idx + 1));
final int kc = getKc(boss);
if (kc <= 0)
{
return false;
}
final String playerName = client.getLocalPlayer().getName();
executor.execute(() ->
{
try
{
chatClient.submitKc(playerName, boss, kc);
}
catch (Exception ex)
{
log.warn("unable to submit killcount", ex);
}
finally
{
chatInput.resume();
}
});
return true;
}
private void killCountLookup(ChatMessage chatMessage, String message)
{
if (!config.killcount())
{
return;
}
if (message.length() <= KILLCOUNT_COMMAND_STRING.length())
{
return;
}
ChatMessageType type = chatMessage.getType();
String search = message.substring(KILLCOUNT_COMMAND_STRING.length() + 1);
final String player;
if (type.equals(ChatMessageType.PRIVATECHATOUT))
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
search = longBossName(search);
final int kc;
try
{
kc = chatClient.getKc(player, search);
}
catch (IOException ex)
{
log.debug("unable to lookup killcount", ex);
return;
}
String response = new ChatMessageBuilder()
.append(ChatColorType.HIGHLIGHT)
.append(search)
.append(ChatColorType.NORMAL)
.append(" kill count: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(kc))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
private boolean duelArenaSubmit(ChatInput chatInput, String value)
{
final int wins = getKc("Duel Arena Wins");
final int losses = getKc("Duel Arena Losses");
final int winningStreak = getKc("Duel Arena Win Streak");
final int losingStreak = getKc("Duel Arena Lose Streak");
if (wins <= 0 && losses <= 0 && winningStreak <= 0 && losingStreak <= 0)
{
return false;
}
final String playerName = client.getLocalPlayer().getName();
executor.execute(() ->
{
try
{
chatClient.submitDuels(playerName, wins, losses, winningStreak, losingStreak);
}
catch (Exception ex)
{
log.warn("unable to submit duels", ex);
}
finally
{
chatInput.resume();
}
});
return true;
}
private void duelArenaLookup(ChatMessage chatMessage, String message)
{
if (!config.duels())
{
return;
}
ChatMessageType type = chatMessage.getType();
final String player;
if (type == ChatMessageType.PRIVATECHATOUT)
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
Duels duels;
try
{
duels = chatClient.getDuels(player);
}
catch (IOException ex)
{
log.debug("unable to lookup duels", ex);
return;
}
final int wins = duels.getWins();
final int losses = duels.getLosses();
final int winningStreak = duels.getWinningStreak();
final int losingStreak = duels.getLosingStreak();
String response = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Duel Arena wins: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(wins))
.append(ChatColorType.NORMAL)
.append(" losses: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(losses))
.append(ChatColorType.NORMAL)
.append(" streak: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString((winningStreak != 0 ? winningStreak : -losingStreak)))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
private void questPointsLookup(ChatMessage chatMessage, String message)
{
if (!config.qp())
{
return;
}
ChatMessageType type = chatMessage.getType();
final String player;
if (type.equals(ChatMessageType.PRIVATECHATOUT))
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
int qp;
try
{
qp = chatClient.getQp(player);
}
catch (IOException ex)
{
log.debug("unable to lookup quest points", ex);
return;
}
String response = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Quest points: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(qp))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
private boolean questPointsSubmit(ChatInput chatInput, String value)
{
final int qp = client.getVar(VarPlayer.QUEST_POINTS);
final String playerName = client.getLocalPlayer().getName();
executor.execute(() ->
{
try
{
chatClient.submitQp(playerName, qp);
}
catch (Exception ex)
{
log.warn("unable to submit quest points", ex);
}
finally
{
chatInput.resume();
}
});
return true;
}
private void personalBestLookup(ChatMessage chatMessage, String message)
{
if (!config.pb())
{
return;
}
if (message.length() <= PB_COMMAND.length())
{
return;
}
ChatMessageType type = chatMessage.getType();
String search = message.substring(PB_COMMAND.length() + 1);
final String player;
if (type.equals(ChatMessageType.PRIVATECHATOUT))
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
search = longBossName(search);
final int pb;
try
{
pb = chatClient.getPb(player, search);
}
catch (IOException ex)
{
log.debug("unable to lookup personal best", ex);
return;
}
int minutes = pb / 60;
int seconds = pb % 60;
String response = new ChatMessageBuilder()
.append(ChatColorType.HIGHLIGHT)
.append(search)
.append(ChatColorType.NORMAL)
.append(" personal best: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%d:%02d", minutes, seconds))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
private boolean personalBestSubmit(ChatInput chatInput, String value)
{
int idx = value.indexOf(' ');
final String boss = longBossName(value.substring(idx + 1));
final int pb = getPb(boss);
if (pb <= 0)
{
return false;
}
final String playerName = client.getLocalPlayer().getName();
executor.execute(() ->
{
try
{
chatClient.submitPb(playerName, boss, pb);
}
catch (Exception ex)
{
log.warn("unable to submit personal best", ex);
}
finally
{
chatInput.resume();
}
});
return true;
}
private void gambleCountLookup(ChatMessage chatMessage, String message)
{
if (!config.gc())
{
return;
}
ChatMessageType type = chatMessage.getType();
final String player;
if (type == ChatMessageType.PRIVATECHATOUT)
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
int gc;
try
{
gc = chatClient.getGc(player);
}
catch (IOException ex)
{
log.debug("unable to lookup gamble count", ex);
return;
}
String response = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Barbarian Assault High-level gambles: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(gc))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
private boolean gambleCountSubmit(ChatInput chatInput, String value)
{
final int gc = client.getVar(Varbits.BA_GC);
final String playerName = client.getLocalPlayer().getName();
executor.execute(() ->
{
try
{
chatClient.submitGc(playerName, gc);
}
catch (Exception ex)
{
log.warn("unable to submit gamble count", ex);
}
finally
{
chatInput.resume();
}
});
return true;
}
/**
* Looks up the item price and changes the original message to the
* response.
*
* @param chatMessage The chat message containing the command.
* @param message The chat message
*/
private void itemPriceLookup(ChatMessage chatMessage, String message)
{
if (!config.price())
{
return;
}
if (message.length() <= PRICE_COMMAND_STRING.length())
{
return;
}
MessageNode messageNode = chatMessage.getMessageNode();
String search = message.substring(PRICE_COMMAND_STRING.length() + 1);
List<ItemPrice> results = itemManager.search(search);
if (!results.isEmpty())
{
ItemPrice item = retrieveFromList(results, search);
int itemId = item.getId();
int itemPrice = item.getPrice();
final ChatMessageBuilder builder = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Price of ")
.append(ChatColorType.HIGHLIGHT)
.append(item.getName())
.append(ChatColorType.NORMAL)
.append(": GE average ")
.append(ChatColorType.HIGHLIGHT)
.append(QuantityFormatter.formatNumber(itemPrice));
ItemComposition itemComposition = itemManager.getItemComposition(itemId);
if (itemComposition != null)
{
int alchPrice = Math.round(itemComposition.getPrice() * Constants.HIGH_ALCHEMY_MULTIPLIER);
builder
.append(ChatColorType.NORMAL)
.append(" HA value ")
.append(ChatColorType.HIGHLIGHT)
.append(QuantityFormatter.formatNumber(alchPrice));
}
String response = builder.build();
log.debug("Setting response {}", response);
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
}
/**
* Looks up the player skill and changes the original message to the
* response.
*
* @param chatMessage The chat message containing the command.
* @param message The chat message
*/
private void playerSkillLookup(ChatMessage chatMessage, String message)
{
if (!config.lvl())
{
return;
}
String search;
if (message.equalsIgnoreCase(TOTAL_LEVEL_COMMAND_STRING))
{
search = "total";
}
else
{
if (message.length() <= LEVEL_COMMAND_STRING.length())
{
return;
}
search = message.substring(LEVEL_COMMAND_STRING.length() + 1);
}
search = SkillAbbreviations.getFullName(search);
final HiscoreSkill skill;
try
{
skill = HiscoreSkill.valueOf(search.toUpperCase());
}
catch (IllegalArgumentException i)
{
return;
}
final HiscoreLookup lookup = getCorrectLookupFor(chatMessage);
try
{
final SingleHiscoreSkillResult result = hiscoreClient.lookup(lookup.getName(), skill, lookup.getEndpoint());
if (result == null)
{
log.warn("unable to look up skill {} for {}: not found", skill, search);
return;
}
final Skill hiscoreSkill = result.getSkill();
ChatMessageBuilder chatMessageBuilder = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Level ")
.append(ChatColorType.HIGHLIGHT)
.append(skill.getName()).append(": ").append(String.valueOf(hiscoreSkill.getLevel()))
.append(ChatColorType.NORMAL);
if (hiscoreSkill.getExperience() != -1)
{
chatMessageBuilder.append(" Experience: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", hiscoreSkill.getExperience()))
.append(ChatColorType.NORMAL);
}
if (hiscoreSkill.getRank() != -1)
{
chatMessageBuilder.append(" Rank: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", hiscoreSkill.getRank()));
}
final String response = chatMessageBuilder.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("unable to look up skill {} for {}", skill, search, ex);
}
}
private void combatLevelLookup(ChatMessage chatMessage, String message)
{
if (!config.lvl())
{
return;
}
ChatMessageType type = chatMessage.getType();
String player;
if (type == ChatMessageType.PRIVATECHATOUT)
{
player = client.getLocalPlayer().getName();
}
else
{
player = Text.sanitize(chatMessage.getName());
}
try
{
HiscoreResult playerStats = hiscoreClient.lookup(player);
if (playerStats == null)
{
log.warn("Error fetching hiscore data: not found");
return;
}
int attack = playerStats.getAttack().getLevel();
int strength = playerStats.getStrength().getLevel();
int defence = playerStats.getDefence().getLevel();
int hitpoints = playerStats.getHitpoints().getLevel();
int ranged = playerStats.getRanged().getLevel();
int prayer = playerStats.getPrayer().getLevel();
int magic = playerStats.getMagic().getLevel();
int combatLevel = Experience.getCombatLevel(attack, strength, defence, hitpoints, magic, ranged, prayer);
String response = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Combat Level: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(combatLevel))
.append(ChatColorType.NORMAL)
.append(" A: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(attack))
.append(ChatColorType.NORMAL)
.append(" S: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(strength))
.append(ChatColorType.NORMAL)
.append(" D: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(defence))
.append(ChatColorType.NORMAL)
.append(" H: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(hitpoints))
.append(ChatColorType.NORMAL)
.append(" R: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(ranged))
.append(ChatColorType.NORMAL)
.append(" P: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(prayer))
.append(ChatColorType.NORMAL)
.append(" M: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.valueOf(magic))
.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("Error fetching hiscore data", ex);
}
}
private void bountyHunterHunterLookup(ChatMessage chatMessage, String message)
{
if (!config.bh())
{
return;
}
minigameLookup(chatMessage, HiscoreSkill.BOUNTY_HUNTER_HUNTER);
}
private void bountyHunterRogueLookup(ChatMessage chatMessage, String message)
{
if (!config.bhRogue())
{
return;
}
minigameLookup(chatMessage, HiscoreSkill.BOUNTY_HUNTER_ROGUE);
}
private void lastManStandingLookup(ChatMessage chatMessage, String message)
{
if (!config.lms())
{
return;
}
minigameLookup(chatMessage, HiscoreSkill.LAST_MAN_STANDING);
}
private void minigameLookup(ChatMessage chatMessage, HiscoreSkill minigame)
{
try
{
final Skill hiscoreSkill;
final HiscoreLookup lookup = getCorrectLookupFor(chatMessage);
final HiscoreResult result = hiscoreClient.lookup(lookup.getName(), lookup.getEndpoint());
if (result == null)
{
log.warn("error looking up {} score: not found", minigame.getName().toLowerCase());
return;
}
switch (minigame)
{
case BOUNTY_HUNTER_HUNTER:
hiscoreSkill = result.getBountyHunterHunter();
break;
case BOUNTY_HUNTER_ROGUE:
hiscoreSkill = result.getBountyHunterRogue();
break;
case LAST_MAN_STANDING:
hiscoreSkill = result.getLastManStanding();
break;
default:
log.warn("error looking up {} score: not implemented", minigame.getName().toLowerCase());
return;
}
int score = hiscoreSkill.getLevel();
if (score == -1)
{
return;
}
ChatMessageBuilder chatMessageBuilder = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append(minigame.getName())
.append(" Score: ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(score));
int rank = hiscoreSkill.getRank();
if (rank != -1)
{
chatMessageBuilder.append(ChatColorType.NORMAL)
.append(" Rank: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", rank));
}
String response = chatMessageBuilder.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("error looking up {}", minigame.getName().toLowerCase(), ex);
}
}
private void clueLookup(ChatMessage chatMessage, String message)
{
if (!config.clue())
{
return;
}
String search;
if (message.equalsIgnoreCase(CLUES_COMMAND_STRING))
{
search = "total";
}
else
{
search = message.substring(CLUES_COMMAND_STRING.length() + 1);
}
try
{
final Skill hiscoreSkill;
final HiscoreLookup lookup = getCorrectLookupFor(chatMessage);
final HiscoreResult result = hiscoreClient.lookup(lookup.getName(), lookup.getEndpoint());
if (result == null)
{
log.warn("error looking up clues: not found");
return;
}
String level = search.toLowerCase();
switch (level)
{
case "beginner":
hiscoreSkill = result.getClueScrollBeginner();
break;
case "easy":
hiscoreSkill = result.getClueScrollEasy();
break;
case "medium":
hiscoreSkill = result.getClueScrollMedium();
break;
case "hard":
hiscoreSkill = result.getClueScrollHard();
break;
case "elite":
hiscoreSkill = result.getClueScrollElite();
break;
case "master":
hiscoreSkill = result.getClueScrollMaster();
break;
case "total":
hiscoreSkill = result.getClueScrollAll();
break;
default:
return;
}
int quantity = hiscoreSkill.getLevel();
int rank = hiscoreSkill.getRank();
if (quantity == -1)
{
return;
}
ChatMessageBuilder chatMessageBuilder = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Clue scroll (" + level + ")").append(": ")
.append(ChatColorType.HIGHLIGHT)
.append(Integer.toString(quantity));
if (rank != -1)
{
chatMessageBuilder.append(ChatColorType.NORMAL)
.append(" Rank: ")
.append(ChatColorType.HIGHLIGHT)
.append(String.format("%,d", rank));
}
String response = chatMessageBuilder.build();
log.debug("Setting response {}", response);
final MessageNode messageNode = chatMessage.getMessageNode();
messageNode.setRuneLiteFormatMessage(response);
chatMessageManager.update(messageNode);
client.refreshChat();
}
catch (IOException ex)
{
log.warn("error looking up clues", ex);
}
}
/**
* Gets correct lookup data for message
*
* @param chatMessage chat message
* @return hiscore lookup data
*/
private HiscoreLookup getCorrectLookupFor(final ChatMessage chatMessage)
{
Player localPlayer = client.getLocalPlayer();
final String player = Text.sanitize(chatMessage.getName());
// If we are sending the message then just use the local hiscore endpoint for the world
if (chatMessage.getType().equals(ChatMessageType.PRIVATECHATOUT)
|| player.equals(localPlayer.getName()))
{
return new HiscoreLookup(localPlayer.getName(), hiscoreEndpoint);
}
// Public chat on a leagues world is always league hiscores, regardless of icon
if (chatMessage.getType() == ChatMessageType.PUBLICCHAT || chatMessage.getType() == ChatMessageType.MODCHAT)
{
if (client.getWorldType().contains(WorldType.LEAGUE))
{
return new HiscoreLookup(player, HiscoreEndpoint.LEAGUE);
}
}
// Get ironman status from their icon in chat
HiscoreEndpoint endpoint = getHiscoreEndpointByName(chatMessage.getName());
return new HiscoreLookup(player, endpoint);
}
/**
* Compares the names of the items in the list with the original input.
* Returns the item if its name is equal to the original input or the
* shortest match if no exact match is found.
*
* @param items List of items.
* @param originalInput String with the original input.
* @return Item which has a name equal to the original input.
*/
private ItemPrice retrieveFromList(List<ItemPrice> items, String originalInput)
{
ItemPrice shortest = null;
for (ItemPrice item : items)
{
if (item.getName().toLowerCase().equals(originalInput.toLowerCase()))
{
return item;
}
if (shortest == null || item.getName().length() < shortest.getName().length())
{
shortest = item;
}
}
// Take a guess
return shortest;
}
/**
* Looks up the ironman status of the local player. Does NOT work on other players.
*
* @return hiscore endpoint
*/
private HiscoreEndpoint getLocalHiscoreEndpointType()
{
EnumSet<WorldType> worldType = client.getWorldType();
if (worldType.contains(WorldType.LEAGUE))
{
return HiscoreEndpoint.LEAGUE;
}
return toEndPoint(client.getAccountType());
}
/**
* Returns the ironman status based on the symbol in the name of the player.
*
* @param name player name
* @return hiscore endpoint
*/
private static HiscoreEndpoint getHiscoreEndpointByName(final String name)
{
if (name.contains(IconID.IRONMAN.toString()))
{
return toEndPoint(AccountType.IRONMAN);
}
else if (name.contains(IconID.ULTIMATE_IRONMAN.toString()))
{
return toEndPoint(AccountType.ULTIMATE_IRONMAN);
}
else if (name.contains(IconID.HARDCORE_IRONMAN.toString()))
{
return toEndPoint(AccountType.HARDCORE_IRONMAN);
}
else
{
return toEndPoint(AccountType.NORMAL);
}
}
/**
* Converts account type to hiscore endpoint
*
* @param accountType account type
* @return hiscore endpoint
*/
private static HiscoreEndpoint toEndPoint(final AccountType accountType)
{
switch (accountType)
{
case IRONMAN:
return HiscoreEndpoint.IRONMAN;
case ULTIMATE_IRONMAN:
return HiscoreEndpoint.ULTIMATE_IRONMAN;
case HARDCORE_IRONMAN:
return HiscoreEndpoint.HARDCORE_IRONMAN;
default:
return HiscoreEndpoint.NORMAL;
}
}
@Value
private static class HiscoreLookup
{
private final String name;
private final HiscoreEndpoint endpoint;
}
private static String longBossName(String boss)
{
switch (boss.toLowerCase())
{
case "corp":
return "Corporeal Beast";
case "jad":
case "tzhaar fight cave":
return "TzTok-Jad";
case "kq":
return "Kalphite Queen";
case "chaos ele":
return "Chaos Elemental";
case "dusk":
case "dawn":
case "gargs":
return "Grotesque Guardians";
case "crazy arch":
return "Crazy Archaeologist";
case "deranged arch":
return "Deranged Archaeologist";
case "mole":
return "Giant Mole";
case "vetion":
return "Vet'ion";
case "vene":
return "Venenatis";
case "kbd":
return "King Black Dragon";
case "vork":
return "Vorkath";
case "sire":
return "Abyssal Sire";
case "smoke devil":
case "thermy":
return "Thermonuclear Smoke Devil";
case "cerb":
return "Cerberus";
case "zuk":
case "inferno":
return "TzKal-Zuk";
case "hydra":
return "Alchemical Hydra";
// gwd
case "sara":
case "saradomin":
case "zilyana":
case "zily":
return "Commander Zilyana";
case "zammy":
case "zamorak":
case "kril":
case "kril trutsaroth":
return "K'ril Tsutsaroth";
case "arma":
case "kree":
case "kreearra":
case "armadyl":
return "Kree'arra";
case "bando":
case "bandos":
case "graardor":
return "General Graardor";
// dks
case "supreme":
return "Dagannoth Supreme";
case "rex":
return "Dagannoth Rex";
case "prime":
return "Dagannoth Prime";
case "wt":
return "Wintertodt";
case "barrows":
return "Barrows Chests";
case "herbi":
return "Herbiboar";
// cox
case "cox":
case "xeric":
case "chambers":
case "olm":
case "raids":
return "Chambers of Xeric";
// cox cm
case "cox cm":
case "xeric cm":
case "chambers cm":
case "olm cm":
case "raids cm":
case "chambers of xeric - challenge mode":
return "Chambers of Xeric Challenge Mode";
// tob
case "tob":
case "theatre":
case "verzik":
case "verzik vitur":
case "raids 2":
return "Theatre of Blood";
// agility course
case "prif":
case "prifddinas":
return "Prifddinas Agility Course";
// The Gauntlet
case "gaunt":
case "gauntlet":
case "the gauntlet":
return "Gauntlet";
// Corrupted Gauntlet
case "cgaunt":
case "cgauntlet":
case "the corrupted gauntlet":
return "Corrupted Gauntlet";
case "the nightmare":
return "Nightmare";
// Hallowed Sepulchre
case "hs":
case "sepulchre":
case "ghc":
return "Hallowed Sepulchre";
case "hs1":
case "hs 1":
return "Hallowed Sepulchre Floor 1";
case "hs2":
case "hs 2":
return "Hallowed Sepulchre Floor 2";
case "hs3":
case "hs 3":
return "Hallowed Sepulchre Floor 3";
case "hs4":
case "hs 4":
return "Hallowed Sepulchre Floor 4";
case "hs5":
case "hs 5":
return "Hallowed Sepulchre Floor 5";
default:
return WordUtils.capitalize(boss);
}
}
}
| chat commands: name pb matcher groups
| runelite-client/src/main/java/net/runelite/client/plugins/chatcommands/ChatCommandsPlugin.java | chat commands: name pb matcher groups | <ide><path>unelite-client/src/main/java/net/runelite/client/plugins/chatcommands/ChatCommandsPlugin.java
<ide> {
<ide> private static final Pattern KILLCOUNT_PATTERN = Pattern.compile("Your (.+) (?:kill|harvest|lap|completion) count is: <col=ff0000>(\\d+)</col>");
<ide> private static final Pattern RAIDS_PATTERN = Pattern.compile("Your completed (.+) count is: <col=ff0000>(\\d+)</col>");
<del> private static final Pattern RAIDS_PB_PATTERN = Pattern.compile("<col=ef20ff>Congratulations - your raid is complete!</col><br>Team size: <col=ff0000>(?:[0-9]+ players|Solo)</col> Duration:</col> <col=ff0000>([0-9:]+)</col> \\(new personal best\\)</col>");
<del> private static final Pattern TOB_WAVE_PB_PATTERN = Pattern.compile("^.*Theatre of Blood wave completion time: <col=ff0000>([0-9:]+)</col> \\(Personal best!\\)");
<del> private static final Pattern TOB_WAVE_DURATION_PATTERN = Pattern.compile("^.*Theatre of Blood wave completion time: <col=ff0000>[0-9:]+</col><br></col>Personal best: ([0-9:]+)");
<add> private static final Pattern RAIDS_PB_PATTERN = Pattern.compile("<col=ef20ff>Congratulations - your raid is complete!</col><br>Team size: <col=ff0000>(?:[0-9]+ players|Solo)</col> Duration:</col> <col=ff0000>(?<pb>[0-9:]+)</col> \\(new personal best\\)</col>");
<add> private static final Pattern TOB_WAVE_PB_PATTERN = Pattern.compile("^.*Theatre of Blood wave completion time: <col=ff0000>(?<pb>[0-9:]+)</col> \\(Personal best!\\)");
<add> private static final Pattern TOB_WAVE_DURATION_PATTERN = Pattern.compile("^.*Theatre of Blood wave completion time: <col=ff0000>[0-9:]+</col><br></col>Personal best: (?<pb>[0-9:]+)");
<ide> private static final Pattern WINTERTODT_PATTERN = Pattern.compile("Your subdued Wintertodt count is: <col=ff0000>(\\d+)</col>");
<ide> private static final Pattern BARROWS_PATTERN = Pattern.compile("Your Barrows chest count is: <col=ff0000>(\\d+)</col>");
<del> private static final Pattern KILL_DURATION_PATTERN = Pattern.compile("(?i)^(?:Fight |Lap |Challenge |Corrupted challenge )?duration: <col=ff0000>[0-9:]+</col>\\. Personal best: ([0-9:]+)");
<del> private static final Pattern NEW_PB_PATTERN = Pattern.compile("(?i)^(?:Fight |Lap |Challenge |Corrupted challenge )?duration: <col=ff0000>([0-9:]+)</col> \\(new personal best\\)");
<add> private static final Pattern KILL_DURATION_PATTERN = Pattern.compile("(?i)^(?:Fight |Lap |Challenge |Corrupted challenge )?duration: <col=ff0000>[0-9:]+</col>\\. Personal best: (?<pb>[0-9:]+)");
<add> private static final Pattern NEW_PB_PATTERN = Pattern.compile("(?i)^(?:Fight |Lap |Challenge |Corrupted challenge )?duration: <col=ff0000>(?<pb>[0-9:]+)</col> \\(new personal best\\)");
<ide> private static final Pattern DUEL_ARENA_WINS_PATTERN = Pattern.compile("You (were defeated|won)! You have(?: now)? won (\\d+) duels?");
<ide> private static final Pattern DUEL_ARENA_LOSSES_PATTERN = Pattern.compile("You have(?: now)? lost (\\d+) duels?");
<ide> private static final Pattern ADVENTURE_LOG_TITLE_PATTERN = Pattern.compile("The Exploits of (.+)");
<ide>
<ide> private void matchPb(Matcher matcher)
<ide> {
<del> int seconds = timeStringToSeconds(matcher.group(1));
<add> int seconds = timeStringToSeconds(matcher.group("pb"));
<ide> if (lastBossKill != null)
<ide> {
<ide> // Most bosses sent boss kill message, and then pb message, so we |
|
Java | apache-2.0 | 96fe213bfdbcf45c6bca52b811ca6b865e6e8350 | 0 | NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.util.bin.format.elf.relocation;
import ghidra.app.util.bin.format.elf.*;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.*;
import ghidra.util.exception.NotFoundException;
public class ARM_ElfRelocationHandler extends ElfRelocationHandler {
@Override
public boolean canRelocate(ElfHeader elf) {
return elf.e_machine() == ElfConstants.EM_ARM;
}
@Override
public void relocate(ElfRelocationContext elfRelocationContext, ElfRelocation relocation,
Address relocationAddress) throws MemoryAccessException, NotFoundException {
ElfHeader elf = elfRelocationContext.getElfHeader();
if (elf.e_machine() != ElfConstants.EM_ARM) {
return;
}
Program program = elfRelocationContext.getProgram();
Memory memory = program.getMemory();
boolean instructionBigEndian = program.getLanguage().getLanguageDescription().getInstructionEndian().isBigEndian();
int type = relocation.getType();
if (type == ARM_ElfRelocationConstants.R_ARM_NONE) {
return;
}
int symbolIndex = relocation.getSymbolIndex();
long addend = relocation.getAddend(); // will be 0 for REL case
ElfSymbol sym = elfRelocationContext.getSymbol(symbolIndex);
String symbolName = sym.getNameAsString();
boolean isThumb = isThumb(sym);
long offset = (int) relocationAddress.getOffset();
long symbolValue = elfRelocationContext.getSymbolValue(sym);
int newValue = 0;
switch (type) {
case ARM_ElfRelocationConstants.R_ARM_PC24: { // Target class: ARM Instruction
int oldValue = memory.getInt(relocationAddress, instructionBigEndian);
if (elfRelocationContext.extractAddend()) {
addend = (oldValue << 8 >> 6); // extract addend and sign-extend with *4 factor
}
newValue = (int) (symbolValue - offset + addend);
// if this a BLX instruction, must set bit24 to identify half-word
if ((oldValue & 0xf0000000) == 0xf0000000) {
newValue = (oldValue & 0xfe000000) | (((newValue >> 1) & 1) << 24) |
((newValue >> 2) & 0x00ffffff);
}
else {
newValue = (oldValue & 0xff000000) | ((newValue >> 2) & 0x00ffffff);
}
memory.setInt(relocationAddress, newValue, instructionBigEndian);
break;
}
case ARM_ElfRelocationConstants.R_ARM_ABS32: { // Target class: Data
if (elfRelocationContext.extractAddend()) {
addend = memory.getInt(relocationAddress);
}
newValue = (int) (symbolValue + addend);
if (isThumb) {
newValue |= 1;
}
memory.setInt(relocationAddress, newValue);
break;
}
case ARM_ElfRelocationConstants.R_ARM_REL32: { // Target class: Data
if (elfRelocationContext.extractAddend()) {
addend = memory.getInt(relocationAddress);
}
newValue = (int) (symbolValue + addend);
newValue -= offset; // PC relative
if (isThumb) {
newValue |= 1;
}
memory.setInt(relocationAddress, newValue);
break;
}
case ARM_ElfRelocationConstants.R_ARM_PREL31: { // Target class: Data
int oldValue = memory.getInt(relocationAddress);
if (elfRelocationContext.extractAddend()) {
addend = (oldValue << 1) >> 1;
}
newValue = (int) (symbolValue + addend);
newValue -= offset; // PC relative
if (isThumb) {
newValue |= 1;
}
newValue = (newValue & 0x7fffffff) + (oldValue & 0x80000000);
memory.setInt(relocationAddress, newValue);
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_PC_G0: { // Target class: ARM Instruction
int oldValue = memory.getInt(relocationAddress, instructionBigEndian);
newValue = (int) (symbolValue + addend);
newValue -= (offset + 8); // PC relative, PC will be 8 bytes after inst start
newValue = (oldValue & 0xff7ff000) | ((~(newValue >> 31) & 1) << 23) |
((newValue >> 2) & 0xfff);
memory.setInt(relocationAddress, newValue, instructionBigEndian);
break;
}
case ARM_ElfRelocationConstants.R_ARM_ABS16: { // Target class: Data
short sValue = (short) (symbolValue + addend);
memory.setShort(relocationAddress, sValue);
break;
}
case ARM_ElfRelocationConstants.R_ARM_ABS12: { // Target class: ARM Instruction
int oldValue = memory.getInt(relocationAddress, instructionBigEndian);
newValue = (int) (symbolValue + addend);
newValue = (oldValue & 0xfffff000) | (newValue & 0x00000fff);
memory.setInt(relocationAddress, newValue, instructionBigEndian);
break;
}
/*
case ARM_ElfRelocationConstants.R_ARM_THM_ABS5: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_ABS_8: { // Target class: Data
byte bValue = (byte) (symbolValue + addend);
memory.setByte(relocationAddress, bValue);
break;
}
/*
case ARM_ElfRelocationConstants.R_ARM_SBREL32: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_THM_JUMP24: // // Target class: Thumb32 Instruction
case ARM_ElfRelocationConstants.R_ARM_THM_CALL: {
newValue = (int) (symbolValue + addend);
// since it is adding in the oldvalue below, don't need to add in 4 for pc offset
newValue -= (offset);
short oldValueH = memory.getShort(relocationAddress, instructionBigEndian);
short oldValueL = memory.getShort(relocationAddress.add(2), instructionBigEndian);
boolean isBLX = (oldValueL & 0x1000) == 0;
int s = (oldValueH & (1 << 10)) >> 10;
int upper = oldValueH & 0x3ff;
int lower = oldValueL & 0x7ff;
int j1 = (oldValueL & (1 << 13)) >> 13;
int j2 = (oldValueL & (1 << 11)) >> 11;
int i1 = (j1 != s) ? 0 : 1;
int i2 = (j2 != s) ? 0 : 1;
int origaddend = (i1 << 23) | (i2 << 22) | (upper << 12) | (lower << 1);
origaddend = (origaddend | ((s ^ 1) << 24)) - (1 << 24);
newValue = newValue + origaddend;
newValue = newValue >> 1;
// for Thumb, have to be careful, LE is swapped on 2 bytes
short newValueH = (short) ((oldValueH & 0xf800) | (((newValue >> 11) & 0x00007ff)));
short newValueL = (short) ((oldValueL & 0xf800) | (newValue & 0x00007ff));
if (isBLX) {
newValueL &= 0xfffe;
}
memory.setShort(relocationAddress, newValueH, instructionBigEndian);
memory.setShort(relocationAddress.add(2), newValueL, instructionBigEndian);
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_PC8: { // Target class: Thumb16 Instruction
short oldValue = memory.getShort(relocationAddress, instructionBigEndian);
newValue = (int) (symbolValue + addend);
newValue -= (offset + 4); // PC relative, PC will be 4 bytes past inst start
newValue = newValue >> 1;
short sValue = (short) ((oldValue & 0xff00) | (newValue & 0x00ff));
memory.setShort(relocationAddress, sValue, instructionBigEndian);
break;
}
/*
case ARM_ElfRelocationConstants.R_ARM_BREL_ADJ: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_DESC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_SWI8: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_XPC25: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_XPC22: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_DTPMOD32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_DTPOFF32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_TPOFF32: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_GLOB_DAT: {
// Corresponds to resolved local/EXTERNAL symbols within GOT
if (elfRelocationContext.extractAddend()) {
addend = memory.getInt(relocationAddress);
}
newValue = (int) (symbolValue + addend);
if (isThumb) {
newValue |= 1;
}
memory.setInt(relocationAddress, newValue);
break;
}
case ARM_ElfRelocationConstants.R_ARM_JUMP_SLOT: { // Target class: Data
// Corresponds to lazy dynamically linked external symbols within
// GOT/PLT symbolValue corresponds to PLT entry for which we need to
// create and external function location. Don't bother changing
// GOT entry bytes if it refers to .plt block
Address symAddress = elfRelocationContext.getSymbolAddress(sym);
MemoryBlock block = memory.getBlock(symAddress);
boolean isPltSym = block != null && block.getName().startsWith(".plt");
boolean isExternalSym =
block != null && MemoryBlock.EXTERNAL_BLOCK_NAME.equals(block.getName());
if (!isPltSym) {
memory.setInt(relocationAddress, (int) symAddress.getOffset());
}
if (isPltSym || isExternalSym) {
Function extFunction =
elfRelocationContext.getLoadHelper().createExternalFunctionLinkage(
symbolName, symAddress, null);
if (extFunction == null) {
markAsError(program, relocationAddress, "R_ARM_JUMP_SLOT", symbolName,
"Failed to create R_ARM_JUMP_SLOT external function",
elfRelocationContext.getLog());
return;
}
}
break;
}
case ARM_ElfRelocationConstants.R_ARM_RELATIVE: { // Target class: Data
if (elfRelocationContext.extractAddend()) {
addend = memory.getInt(relocationAddress);
}
newValue =
(int) elfRelocationContext.getImageBaseWordAdjustmentOffset() + (int) addend;
memory.setInt(relocationAddress, newValue);
break;
}
/*
case ARM_ElfRelocationConstants.R_ARM_GOTOFF32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_BASE_PREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOT_BREL: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_JUMP24: // Target class: ARM Instruction
case ARM_ElfRelocationConstants.R_ARM_CALL:
case ARM_ElfRelocationConstants.R_ARM_GOT_PLT32:
int oldValue = memory.getInt(relocationAddress, instructionBigEndian);
newValue = (int) (symbolValue + addend);
newValue -= (offset + 8); // PC relative, PC will be 8 bytes past inst start
// is this a BLX instruction, must put the lower half word in bit24
// TODO: this might not appear on a BLX, but just in case
if ((oldValue & 0xff000000) == 0xfb000000) {
newValue = (oldValue & 0xfe000000) | (((newValue >> 1) & 1) << 24) |
((newValue >> 2) & 0x00ffffff);
}
else {
newValue = (oldValue & 0xff000000) | ((newValue >> 2) & 0x00ffffff);
}
memory.setInt(relocationAddress, newValue, instructionBigEndian);
break;
/*
case ARM_ElfRelocationConstants.R_ARM_BASE_ABS: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PCREL_7_0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PCREL_15_8: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PCREL_23_15: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_SBREL_11_0_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SBREL_19_12_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SBREL_27_20_CK: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TARGET1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_SBREL31: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_V4BX: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TARGET2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PREL31: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_MOVW_ABS_NC:
case ARM_ElfRelocationConstants.R_ARM_MOVT_ABS: { // Target Class: ARM Instruction
oldValue = memory.getInt(relocationAddress, instructionBigEndian);
newValue = oldValue;
oldValue = ((oldValue & 0xf0000) >> 4) | (oldValue & 0xfff);
oldValue = (oldValue ^ 0x8000) - 0x8000;
oldValue += symbolValue;
if (type == ARM_ElfRelocationConstants.R_ARM_MOVT_ABS)
oldValue >>= 16;
newValue &= 0xfff0f000;
newValue |= ((oldValue & 0xf000) << 4) |
(oldValue & 0x0fff);
memory.setInt(relocationAddress, newValue, instructionBigEndian);
break;
}
/*
case ARM_ElfRelocationConstants.R_ARM_MOVW_PREL_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVT_PREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVW_ABS_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVT_ABS: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVW_PREL_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVT_PREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_JUMP19: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_JUMP6: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_ALU_PREL_11_0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_PC12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ABS32_NOI: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_REL32_NOI: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PC_G0_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PC_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PC_G1_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PC_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PC_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_PC_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_PC_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_PC_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_PC_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_PC_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_PC_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_PC_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_PC_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SB_G0_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SB_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SB_G1_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SB_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SB_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_SB_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_SB_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_SB_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_SB_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_SB_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_SB_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_SB_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_SB_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_SB_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVW_BREL_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVT_BREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVW_BREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVW_BREL_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVT_BREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVW_BREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_GOTDESC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_CALL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_DESCSEQ: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_TLS_CALL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PLT32_ABS: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOT_ABS: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOT_PREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOT_BREL12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOTOFF12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOTRELAX: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GNU_VTENTRY: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GNU_VTINHERIT: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_JUMP11: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_JUMP8: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_GD32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_LDM32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_LDO32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_IE32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_LE32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_LDO12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_LE12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_IE12GP: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_3: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_4: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_5: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_6: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_7: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_8: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_9: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_10: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_11: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_13: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_14: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_15: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_TLS_DESCSEQ16: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_TLS_DESCSEQ32: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_COPY: {
markAsWarning(program, relocationAddress, "R_ARM_COPY", symbolName, symbolIndex,
"Runtime copy not supported", elfRelocationContext.getLog());
break;
}
default: {
markAsUnhandled(program, relocationAddress, type, symbolIndex, symbolName,
elfRelocationContext.getLog());
break;
}
}
}
private boolean isThumb(ElfSymbol symbol) {
if (symbol.isFunction() && (symbol.getValue() % 1) == 1) {
return true;
}
return false;
}
}
| Ghidra/Processors/ARM/src/main/java/ghidra/app/util/bin/format/elf/relocation/ARM_ElfRelocationHandler.java | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.util.bin.format.elf.relocation;
import ghidra.app.util.bin.format.elf.*;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.*;
import ghidra.util.exception.NotFoundException;
public class ARM_ElfRelocationHandler extends ElfRelocationHandler {
@Override
public boolean canRelocate(ElfHeader elf) {
return elf.e_machine() == ElfConstants.EM_ARM;
}
@Override
public void relocate(ElfRelocationContext elfRelocationContext, ElfRelocation relocation,
Address relocationAddress) throws MemoryAccessException, NotFoundException {
ElfHeader elf = elfRelocationContext.getElfHeader();
if (elf.e_machine() != ElfConstants.EM_ARM) {
return;
}
Program program = elfRelocationContext.getProgram();
Memory memory = program.getMemory();
boolean instructionBigEndian = program.getLanguage().getLanguageDescription().getInstructionEndian().isBigEndian();
int type = relocation.getType();
if (type == ARM_ElfRelocationConstants.R_ARM_NONE) {
return;
}
int symbolIndex = relocation.getSymbolIndex();
long addend = relocation.getAddend(); // will be 0 for REL case
ElfSymbol sym = elfRelocationContext.getSymbol(symbolIndex);
String symbolName = sym.getNameAsString();
boolean isThumb = isThumb(sym);
long offset = (int) relocationAddress.getOffset();
long symbolValue = elfRelocationContext.getSymbolValue(sym);
int newValue = 0;
switch (type) {
case ARM_ElfRelocationConstants.R_ARM_PC24: { // Target class: ARM Instruction
int oldValue = memory.getInt(relocationAddress, instructionBigEndian);
if (elfRelocationContext.extractAddend()) {
addend = (oldValue << 8 >> 6); // extract addend and sign-extend with *4 factor
}
newValue = (int) (symbolValue - offset + addend);
// if this a BLX instruction, must set bit24 to identify half-word
if ((oldValue & 0xf0000000) == 0xf0000000) {
newValue = (oldValue & 0xfe000000) | (((newValue >> 1) & 1) << 24) |
((newValue >> 2) & 0x00ffffff);
}
else {
newValue = (oldValue & 0xff000000) | ((newValue >> 2) & 0x00ffffff);
}
memory.setInt(relocationAddress, newValue, instructionBigEndian);
break;
}
case ARM_ElfRelocationConstants.R_ARM_ABS32: { // Target class: Data
if (elfRelocationContext.extractAddend()) {
addend = memory.getInt(relocationAddress);
}
newValue = (int) (symbolValue + addend);
if (isThumb) {
newValue |= 1;
}
memory.setInt(relocationAddress, newValue);
break;
}
case ARM_ElfRelocationConstants.R_ARM_REL32: { // Target class: Data
if (elfRelocationContext.extractAddend()) {
addend = memory.getInt(relocationAddress);
}
newValue = (int) (symbolValue + addend);
newValue -= offset; // PC relative
if (isThumb) {
newValue |= 1;
}
memory.setInt(relocationAddress, newValue);
break;
}
case ARM_ElfRelocationConstants.R_ARM_PREL31: { // Target class: Data
int oldValue = memory.getInt(relocationAddress);
if (elfRelocationContext.extractAddend()) {
addend = (oldValue << 1) >> 1;
}
newValue = (int) (symbolValue + addend);
newValue -= offset; // PC relative
if (isThumb) {
newValue |= 1;
}
newValue = (newValue & 0x7fffffff) + (oldValue & 0x80000000);
memory.setInt(relocationAddress, newValue);
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_PC_G0: { // Target class: ARM Instruction
int oldValue = memory.getInt(relocationAddress, instructionBigEndian);
newValue = (int) (symbolValue + addend);
newValue -= (offset + 8); // PC relative, PC will be 8 bytes after inst start
newValue = (oldValue & 0xff7ff000) | ((~(newValue >> 31) & 1) << 23) |
((newValue >> 2) & 0xfff);
memory.setInt(relocationAddress, newValue, instructionBigEndian);
break;
}
case ARM_ElfRelocationConstants.R_ARM_ABS16: { // Target class: Data
short sValue = (short) (symbolValue + addend);
memory.setShort(relocationAddress, sValue);
break;
}
case ARM_ElfRelocationConstants.R_ARM_ABS12: { // Target class: ARM Instruction
int oldValue = memory.getInt(relocationAddress, instructionBigEndian);
newValue = (int) (symbolValue + addend);
newValue = (oldValue & 0xfffff000) | (newValue & 0x00000fff);
memory.setInt(relocationAddress, newValue, instructionBigEndian);
break;
}
/*
case ARM_ElfRelocationConstants.R_ARM_THM_ABS5: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_ABS_8: { // Target class: Data
byte bValue = (byte) (symbolValue + addend);
memory.setByte(relocationAddress, bValue);
break;
}
/*
case ARM_ElfRelocationConstants.R_ARM_SBREL32: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_THM_JUMP24: // // Target class: Thumb32 Instruction
case ARM_ElfRelocationConstants.R_ARM_THM_CALL: {
newValue = (int) (symbolValue + addend);
// since it is adding in the oldvalue below, don't need to add in 4 for pc offset
newValue -= (offset);
short oldValueH = memory.getShort(relocationAddress, instructionBigEndian);
short oldValueL = memory.getShort(relocationAddress.add(2), instructionBigEndian);
boolean isBLX = (oldValueL & 0x1000) == 0;
int s = (oldValueH & (1 << 10)) >> 10;
int upper = oldValueH & 0x3ff;
int lower = oldValueL & 0x7ff;
int j1 = (oldValueL & (1 << 13)) >> 13;
int j2 = (oldValueL & (1 << 11)) >> 11;
int i1 = (j1 != s) ? 0 : 1;
int i2 = (j2 != s) ? 0 : 1;
int origaddend = (i1 << 23) | (i2 << 22) | (upper << 12) | (lower << 1);
origaddend = (origaddend | ((s ^ 1) << 24)) - (1 << 24);
newValue = newValue + origaddend;
newValue = newValue >> 1;
// for Thumb, have to be careful, LE is swapped on 2 bytes
short newValueH = (short) ((oldValueH & 0xf800) | (((newValue >> 11) & 0x00007ff)));
short newValueL = (short) ((oldValueL & 0xf800) | (newValue & 0x00007ff));
if (isBLX) {
newValueL &= 0xfffe;
}
memory.setShort(relocationAddress, newValueH, instructionBigEndian);
memory.setShort(relocationAddress.add(2), newValueL, instructionBigEndian);
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_PC8: { // Target class: Thumb16 Instruction
short oldValue = memory.getShort(relocationAddress, instructionBigEndian);
newValue = (int) (symbolValue + addend);
newValue -= (offset + 4); // PC relative, PC will be 4 bytes past inst start
newValue = newValue >> 1;
short sValue = (short) ((oldValue & 0xff00) | (newValue & 0x00ff));
memory.setShort(relocationAddress, sValue, instructionBigEndian);
break;
}
/*
case ARM_ElfRelocationConstants.R_ARM_BREL_ADJ: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_DESC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_SWI8: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_XPC25: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_XPC22: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_DTPMOD32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_DTPOFF32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_TPOFF32: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_GLOB_DAT: {
// Corresponds to resolved local/EXTERNAL symbols within GOT
if (elfRelocationContext.extractAddend()) {
addend = memory.getInt(relocationAddress);
}
newValue = (int) (symbolValue + addend);
if (isThumb) {
newValue |= 1;
}
memory.setInt(relocationAddress, newValue);
break;
}
case ARM_ElfRelocationConstants.R_ARM_JUMP_SLOT: { // Target class: Data
// Corresponds to lazy dynamically linked external symbols within
// GOT/PLT symbolValue corresponds to PLT entry for which we need to
// create and external function location. Don't bother changing
// GOT entry bytes if it refers to .plt block
Address symAddress = elfRelocationContext.getSymbolAddress(sym);
MemoryBlock block = memory.getBlock(symAddress);
boolean isPltSym = block != null && block.getName().startsWith(".plt");
boolean isExternalSym =
block != null && MemoryBlock.EXTERNAL_BLOCK_NAME.equals(block.getName());
if (!isPltSym) {
memory.setInt(relocationAddress, (int) symAddress.getOffset());
}
if (isPltSym || isExternalSym) {
Function extFunction =
elfRelocationContext.getLoadHelper().createExternalFunctionLinkage(
symbolName, symAddress, null);
if (extFunction == null) {
markAsError(program, relocationAddress, "R_ARM_JUMP_SLOT", symbolName,
"Failed to create R_ARM_JUMP_SLOT external function",
elfRelocationContext.getLog());
return;
}
}
break;
}
case ARM_ElfRelocationConstants.R_ARM_RELATIVE: { // Target class: Data
if (elfRelocationContext.extractAddend()) {
addend = memory.getInt(relocationAddress);
}
newValue =
(int) elfRelocationContext.getImageBaseWordAdjustmentOffset() + (int) addend;
memory.setInt(relocationAddress, newValue);
break;
}
/*
case ARM_ElfRelocationConstants.R_ARM_GOTOFF32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_BASE_PREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOT_BREL: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_JUMP24: // Target class: ARM Instruction
case ARM_ElfRelocationConstants.R_ARM_CALL:
case ARM_ElfRelocationConstants.R_ARM_GOT_PLT32:
int oldValue = memory.getInt(relocationAddress, instructionBigEndian);
newValue = (int) (symbolValue + addend);
newValue -= (offset + 8); // PC relative, PC will be 8 bytes past inst start
// is this a BLX instruction, must put the lower half word in bit24
// TODO: this might not appear on a BLX, but just in case
if ((oldValue & 0xff000000) == 0xfb000000) {
newValue = (oldValue & 0xfe000000) | (((newValue >> 1) & 1) << 24) |
((newValue >> 2) & 0x00ffffff);
}
else {
newValue = (oldValue & 0xff000000) | ((newValue >> 2) & 0x00ffffff);
}
memory.setInt(relocationAddress, newValue, instructionBigEndian);
break;
/*
case ARM_ElfRelocationConstants.R_ARM_BASE_ABS: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PCREL_7_0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PCREL_15_8: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PCREL_23_15: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_SBREL_11_0_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SBREL_19_12_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SBREL_27_20_CK: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TARGET1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_SBREL31: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_V4BX: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TARGET2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PREL31: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVW_ABS_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVT_ABS: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVW_PREL_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVT_PREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVW_ABS_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVT_ABS: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVW_PREL_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVT_PREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_JUMP19: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_JUMP6: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_ALU_PREL_11_0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_PC12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ABS32_NOI: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_REL32_NOI: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PC_G0_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PC_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PC_G1_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PC_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_PC_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_PC_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_PC_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_PC_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_PC_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_PC_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_PC_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_PC_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_PC_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SB_G0_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SB_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SB_G1_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SB_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_ALU_SB_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_SB_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_SB_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDR_SB_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_SB_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_SB_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDRS_SB_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_SB_G0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_SB_G1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_LDC_SB_G2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVW_BREL_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVT_BREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_MOVW_BREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVW_BREL_NC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVT_BREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_MOVW_BREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_GOTDESC: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_CALL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_DESCSEQ: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_TLS_CALL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PLT32_ABS: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOT_ABS: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOT_PREL: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOT_BREL12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOTOFF12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GOTRELAX: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GNU_VTENTRY: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_GNU_VTINHERIT: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_JUMP11: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_JUMP8: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_GD32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_LDM32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_LDO32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_IE32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_LE32: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_LDO12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_LE12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_TLS_IE12GP: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_0: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_1: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_2: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_3: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_4: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_5: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_6: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_7: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_8: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_9: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_10: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_11: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_12: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_13: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_14: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_PRIVATE_15: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_TLS_DESCSEQ16: {
break;
}
case ARM_ElfRelocationConstants.R_ARM_THM_TLS_DESCSEQ32: {
break;
}
*/
case ARM_ElfRelocationConstants.R_ARM_COPY: {
markAsWarning(program, relocationAddress, "R_ARM_COPY", symbolName, symbolIndex,
"Runtime copy not supported", elfRelocationContext.getLog());
break;
}
default: {
markAsUnhandled(program, relocationAddress, type, symbolIndex, symbolName,
elfRelocationContext.getLog());
break;
}
}
}
private boolean isThumb(ElfSymbol symbol) {
if (symbol.isFunction() && (symbol.getValue() % 1) == 1) {
return true;
}
return false;
}
}
| GP-555 Added support for R_ARM_MOVW_ABS_NC and R_ARM_MOVT_ABS elf
relocations
| Ghidra/Processors/ARM/src/main/java/ghidra/app/util/bin/format/elf/relocation/ARM_ElfRelocationHandler.java | GP-555 Added support for R_ARM_MOVW_ABS_NC and R_ARM_MOVT_ABS elf relocations | <ide><path>hidra/Processors/ARM/src/main/java/ghidra/app/util/bin/format/elf/relocation/ARM_ElfRelocationHandler.java
<ide> case ARM_ElfRelocationConstants.R_ARM_PREL31: {
<ide> break;
<ide> }
<del> case ARM_ElfRelocationConstants.R_ARM_MOVW_ABS_NC: {
<del> break;
<del> }
<del> case ARM_ElfRelocationConstants.R_ARM_MOVT_ABS: {
<del> break;
<del> }
<add>*/
<add> case ARM_ElfRelocationConstants.R_ARM_MOVW_ABS_NC:
<add> case ARM_ElfRelocationConstants.R_ARM_MOVT_ABS: { // Target Class: ARM Instruction
<add> oldValue = memory.getInt(relocationAddress, instructionBigEndian);
<add> newValue = oldValue;
<add>
<add> oldValue = ((oldValue & 0xf0000) >> 4) | (oldValue & 0xfff);
<add> oldValue = (oldValue ^ 0x8000) - 0x8000;
<add>
<add> oldValue += symbolValue;
<add> if (type == ARM_ElfRelocationConstants.R_ARM_MOVT_ABS)
<add> oldValue >>= 16;
<add>
<add> newValue &= 0xfff0f000;
<add> newValue |= ((oldValue & 0xf000) << 4) |
<add> (oldValue & 0x0fff);
<add>
<add> memory.setInt(relocationAddress, newValue, instructionBigEndian);
<add>
<add> break;
<add> }
<add>/*
<ide> case ARM_ElfRelocationConstants.R_ARM_MOVW_PREL_NC: {
<ide> break;
<ide> } |
|
Java | apache-2.0 | 000a91ad1a8f113484747baa171abfd5b23429ae | 0 | jmt4/Selenium2,jmt4/Selenium2,yumingjuan/selenium,yumingjuan/selenium,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,jmt4/Selenium2,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,yumingjuan/selenium,yumingjuan/selenium,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,yumingjuan/selenium,yumingjuan/selenium | /*
Copyright 2012 Software Freedom Conservancy
Copyright 2007-2012 Selenium committers
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.openqa.selenium;
import org.junit.Test;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.MoveTargetOutOfBoundsException;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JUnit4TestBase;
import org.openqa.selenium.testing.JavascriptEnabled;
import org.openqa.selenium.testing.TestUtilities;
import org.openqa.selenium.testing.drivers.Browser;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.openqa.selenium.TestWaiter.waitFor;
import static org.openqa.selenium.WaitingConditions.elementLocationToBe;
import static org.openqa.selenium.testing.Ignore.Driver.ANDROID;
import static org.openqa.selenium.testing.Ignore.Driver.CHROME;
import static org.openqa.selenium.testing.Ignore.Driver.HTMLUNIT;
import static org.openqa.selenium.testing.Ignore.Driver.IE;
import static org.openqa.selenium.testing.Ignore.Driver.IPHONE;
import static org.openqa.selenium.testing.Ignore.Driver.OPERA;
import static org.openqa.selenium.testing.Ignore.Driver.OPERA_MOBILE;
import static org.openqa.selenium.testing.Ignore.Driver.SAFARI;
import static org.openqa.selenium.testing.Ignore.Driver.SELENESE;
import static org.openqa.selenium.testing.TestUtilities.assumeFalse;
@Ignore(
value = {ANDROID, HTMLUNIT, IPHONE, SAFARI, SELENESE, OPERA_MOBILE},
reason = "HtmlUnit: Advanced mouse actions only implemented in rendered browsers" +
"Safari: not implemented (issue 4136)",
issues = {4136})
public class DragAndDropTest extends JUnit4TestBase {
@JavascriptEnabled
@Test
public void testDragAndDrop() {
if (Platform.getCurrent().is(Platform.MAC)) {
System.out.println("Skipping testDragAndDrop on Mac: See issue 2281.");
return;
}
assumeFalse(Browser.detect() == Browser.opera &&
TestUtilities.getEffectivePlatform().is(Platform.WINDOWS));
driver.get(pages.dragAndDropPage);
WebElement img = driver.findElement(By.id("test1"));
Point expectedLocation = img.getLocation();
drag(img, expectedLocation, 150, 200);
waitFor(elementLocationToBe(img, expectedLocation));
drag(img, expectedLocation, -50, -25);
waitFor(elementLocationToBe(img, expectedLocation));
drag(img, expectedLocation, 0, 0);
waitFor(elementLocationToBe(img, expectedLocation));
drag(img, expectedLocation, 1, -1);
waitFor(elementLocationToBe(img, expectedLocation));
}
@JavascriptEnabled
@Ignore(OPERA)
@Test
public void testDragAndDropToElement() {
driver.get(pages.dragAndDropPage);
WebElement img1 = driver.findElement(By.id("test1"));
WebElement img2 = driver.findElement(By.id("test2"));
new Actions(driver).dragAndDrop(img2, img1).perform();
assertEquals(img1.getLocation(), img2.getLocation());
}
@JavascriptEnabled
@Ignore(OPERA)
@Test
public void testDragAndDropToElementInIframe() {
driver.get(pages.iframePage);
final WebElement iframe = driver.findElement(By.tagName("iframe"));
((JavascriptExecutor) driver).executeScript("arguments[0].src = arguments[1]", iframe,
pages.dragAndDropPage);
driver.switchTo().frame(0);
WebElement img1 = driver.findElement(By.id("test1"));
WebElement img2 = driver.findElement(By.id("test2"));
new Actions(driver).dragAndDrop(img2, img1).perform();
assertEquals(img1.getLocation(), img2.getLocation());
}
@JavascriptEnabled
@Test
public void testElementInDiv() {
if (Platform.getCurrent().is(Platform.MAC)) {
System.out.println("Skipping testElementInDiv on Mac: See issue 2281.");
return;
}
driver.get(pages.dragAndDropPage);
WebElement img = driver.findElement(By.id("test3"));
Point expectedLocation = img.getLocation();
drag(img, expectedLocation, 100, 100);
assertEquals(expectedLocation, img.getLocation());
}
@JavascriptEnabled
@Ignore({CHROME, IE, OPERA})
@Test
public void testDragTooFar() {
driver.get(pages.dragAndDropPage);
Actions actions = new Actions(driver);
try {
WebElement img = driver.findElement(By.id("test1"));
// Attempt to drag the image outside of the bounds of the page.
actions.dragAndDropBy(img, Integer.MAX_VALUE, Integer.MAX_VALUE).perform();
fail("These coordinates are outside the page - expected to fail.");
} catch (MoveTargetOutOfBoundsException expected) {
// Release mouse button - move was interrupted in the middle.
new Actions(driver).release().perform();
}
}
@JavascriptEnabled
@NoDriverAfterTest
// We can't reliably resize the window back afterwards, cross-browser, so have to kill the
// window, otherwise we are stuck with a small window for the rest of the tests.
// TODO(dawagner): Remove @NoDriverAfterTest when we can reliably do window resizing
@Test
public void testShouldAllowUsersToDragAndDropToElementsOffTheCurrentViewPort() {
driver.get(pages.dragAndDropPage);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.resizeTo(300, 300);");
driver.get(pages.dragAndDropPage);
WebElement img = driver.findElement(By.id("test3"));
Point expectedLocation = img.getLocation();
drag(img, expectedLocation, 100, 100);
assertEquals(expectedLocation, img.getLocation());
}
private void drag(WebElement elem, Point expectedLocation,
int moveRightBy, int moveDownBy) {
new Actions(driver)
.dragAndDropBy(elem, moveRightBy, moveDownBy)
.perform();
expectedLocation.move(expectedLocation.x + moveRightBy, expectedLocation.y + moveDownBy);
}
@JavascriptEnabled
@Ignore(OPERA)
@Test
public void testDragAndDropOnJQueryItems() {
driver.get(pages.droppableItems);
WebElement toDrag = driver.findElement(By.id("draggable"));
WebElement dropInto = driver.findElement(By.id("droppable"));
// Wait until all event handlers are installed.
sleep(500);
new Actions(driver).dragAndDrop(toDrag, dropInto).perform();
String text = dropInto.findElement(By.tagName("p")).getText();
long waitEndTime = System.currentTimeMillis() + 15000;
while (!text.equals("Dropped!") && (System.currentTimeMillis() < waitEndTime)) {
sleep(200);
text = dropInto.findElement(By.tagName("p")).getText();
}
assertEquals("Dropped!", text);
WebElement reporter = driver.findElement(By.id("drop_reports"));
// Assert that only one mouse click took place and the mouse was moved
// during it.
String reporterText = reporter.getText();
Pattern pattern = Pattern.compile("start( move)* down( move)+ up( move)*");
Matcher matcher = pattern.matcher(reporterText);
assertTrue("Reporter text:" + reporterText, matcher.matches());
}
private static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted: " + e.toString());
}
}
} | java/client/test/org/openqa/selenium/DragAndDropTest.java | /*
Copyright 2012 Software Freedom Conservancy
Copyright 2007-2012 Selenium committers
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.openqa.selenium;
import org.junit.Test;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.MoveTargetOutOfBoundsException;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JUnit4TestBase;
import org.openqa.selenium.testing.JavascriptEnabled;
import org.openqa.selenium.testing.TestUtilities;
import org.openqa.selenium.testing.drivers.Browser;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.openqa.selenium.TestWaiter.waitFor;
import static org.openqa.selenium.WaitingConditions.elementLocationToBe;
import static org.openqa.selenium.testing.Ignore.Driver.ANDROID;
import static org.openqa.selenium.testing.Ignore.Driver.CHROME;
import static org.openqa.selenium.testing.Ignore.Driver.HTMLUNIT;
import static org.openqa.selenium.testing.Ignore.Driver.IE;
import static org.openqa.selenium.testing.Ignore.Driver.IPHONE;
import static org.openqa.selenium.testing.Ignore.Driver.OPERA;
import static org.openqa.selenium.testing.Ignore.Driver.OPERA_MOBILE;
import static org.openqa.selenium.testing.Ignore.Driver.SAFARI;
import static org.openqa.selenium.testing.Ignore.Driver.SELENESE;
import static org.openqa.selenium.testing.TestUtilities.assumeFalse;
@Ignore(
value = {ANDROID, HTMLUNIT, IPHONE, SAFARI, SELENESE, OPERA_MOBILE},
reason = "HtmlUnit: Advanced mouse actions only implemented in rendered browsers" +
"Safari: not implemented (issue 4136)",
issues = {4136})
public class DragAndDropTest extends JUnit4TestBase {
@JavascriptEnabled
@Test
public void testDragAndDrop() {
if (Platform.getCurrent().is(Platform.MAC)) {
System.out.println("Skipping testDragAndDrop on Mac: See issue 2281.");
return;
}
assumeFalse(Browser.detect() == Browser.opera &&
TestUtilities.getEffectivePlatform() == Platform.WINDOWS);
driver.get(pages.dragAndDropPage);
WebElement img = driver.findElement(By.id("test1"));
Point expectedLocation = img.getLocation();
drag(img, expectedLocation, 150, 200);
waitFor(elementLocationToBe(img, expectedLocation));
drag(img, expectedLocation, -50, -25);
waitFor(elementLocationToBe(img, expectedLocation));
drag(img, expectedLocation, 0, 0);
waitFor(elementLocationToBe(img, expectedLocation));
drag(img, expectedLocation, 1, -1);
waitFor(elementLocationToBe(img, expectedLocation));
}
@JavascriptEnabled
@Ignore({OPERA, OPERA_MOBILE})
@Test
public void testDragAndDropToElement() {
driver.get(pages.dragAndDropPage);
WebElement img1 = driver.findElement(By.id("test1"));
WebElement img2 = driver.findElement(By.id("test2"));
new Actions(driver).dragAndDrop(img2, img1).perform();
assertEquals(img1.getLocation(), img2.getLocation());
}
@JavascriptEnabled
@Ignore({OPERA, OPERA_MOBILE})
@Test
public void testDragAndDropToElementInIframe() {
driver.get(pages.iframePage);
final WebElement iframe = driver.findElement(By.tagName("iframe"));
((JavascriptExecutor) driver).executeScript("arguments[0].src = arguments[1]", iframe,
pages.dragAndDropPage);
driver.switchTo().frame(0);
WebElement img1 = driver.findElement(By.id("test1"));
WebElement img2 = driver.findElement(By.id("test2"));
new Actions(driver).dragAndDrop(img2, img1).perform();
assertEquals(img1.getLocation(), img2.getLocation());
}
@JavascriptEnabled
@Test
public void testElementInDiv() {
if (Platform.getCurrent().is(Platform.MAC)) {
System.out.println("Skipping testElementInDiv on Mac: See issue 2281.");
return;
}
driver.get(pages.dragAndDropPage);
WebElement img = driver.findElement(By.id("test3"));
Point expectedLocation = img.getLocation();
drag(img, expectedLocation, 100, 100);
assertEquals(expectedLocation, img.getLocation());
}
@JavascriptEnabled
@Ignore({CHROME, IE, OPERA, OPERA_MOBILE})
@Test
public void testDragTooFar() {
driver.get(pages.dragAndDropPage);
Actions actions = new Actions(driver);
try {
WebElement img = driver.findElement(By.id("test1"));
// Attempt to drag the image outside of the bounds of the page.
actions.dragAndDropBy(img, Integer.MAX_VALUE, Integer.MAX_VALUE).perform();
fail("These coordinates are outside the page - expected to fail.");
} catch (MoveTargetOutOfBoundsException expected) {
// Release mouse button - move was interrupted in the middle.
new Actions(driver).release().perform();
}
}
@JavascriptEnabled
@NoDriverAfterTest
// We can't reliably resize the window back afterwards, cross-browser, so have to kill the
// window, otherwise we are stuck with a small window for the rest of the tests.
// TODO(dawagner): Remove @NoDriverAfterTest when we can reliably do window resizing
@Test
public void testShouldAllowUsersToDragAndDropToElementsOffTheCurrentViewPort() {
driver.get(pages.dragAndDropPage);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.resizeTo(300, 300);");
driver.get(pages.dragAndDropPage);
WebElement img = driver.findElement(By.id("test3"));
Point expectedLocation = img.getLocation();
drag(img, expectedLocation, 100, 100);
assertEquals(expectedLocation, img.getLocation());
}
private void drag(WebElement elem, Point expectedLocation,
int moveRightBy, int moveDownBy) {
new Actions(driver)
.dragAndDropBy(elem, moveRightBy, moveDownBy)
.perform();
expectedLocation.move(expectedLocation.x + moveRightBy, expectedLocation.y + moveDownBy);
}
@JavascriptEnabled
@Ignore(OPERA)
@Test
public void testDragAndDropOnJQueryItems() {
driver.get(pages.droppableItems);
WebElement toDrag = driver.findElement(By.id("draggable"));
WebElement dropInto = driver.findElement(By.id("droppable"));
// Wait until all event handlers are installed.
sleep(500);
new Actions(driver).dragAndDrop(toDrag, dropInto).perform();
String text = dropInto.findElement(By.tagName("p")).getText();
long waitEndTime = System.currentTimeMillis() + 15000;
while (!text.equals("Dropped!") && (System.currentTimeMillis() < waitEndTime)) {
sleep(200);
text = dropInto.findElement(By.tagName("p")).getText();
}
assertEquals("Dropped!", text);
WebElement reporter = driver.findElement(By.id("drop_reports"));
// Assert that only one mouse click took place and the mouse was moved
// during it.
String reporterText = reporter.getText();
Pattern pattern = Pattern.compile("start( move)* down( move)+ up( move)*");
Matcher matcher = pattern.matcher(reporterText);
assertTrue("Reporter text:" + reporterText, matcher.matches());
}
private static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted: " + e.toString());
}
}
} | AndreasTolfTolfsen: Effective platform might be Windows 2008, so we need to use the platform comparison heuristic as we fail on all types of Windowses
git-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@17925 07704840-8298-11de-bf8c-fd130f914ac9
| java/client/test/org/openqa/selenium/DragAndDropTest.java | AndreasTolfTolfsen: Effective platform might be Windows 2008, so we need to use the platform comparison heuristic as we fail on all types of Windowses | <ide><path>ava/client/test/org/openqa/selenium/DragAndDropTest.java
<ide> return;
<ide> }
<ide> assumeFalse(Browser.detect() == Browser.opera &&
<del> TestUtilities.getEffectivePlatform() == Platform.WINDOWS);
<add> TestUtilities.getEffectivePlatform().is(Platform.WINDOWS));
<ide>
<ide> driver.get(pages.dragAndDropPage);
<ide> WebElement img = driver.findElement(By.id("test1"));
<ide> }
<ide>
<ide> @JavascriptEnabled
<del> @Ignore({OPERA, OPERA_MOBILE})
<add> @Ignore(OPERA)
<ide> @Test
<ide> public void testDragAndDropToElement() {
<ide> driver.get(pages.dragAndDropPage);
<ide> }
<ide>
<ide> @JavascriptEnabled
<del> @Ignore({OPERA, OPERA_MOBILE})
<add> @Ignore(OPERA)
<ide> @Test
<ide> public void testDragAndDropToElementInIframe() {
<ide> driver.get(pages.iframePage);
<ide> }
<ide>
<ide> @JavascriptEnabled
<del> @Ignore({CHROME, IE, OPERA, OPERA_MOBILE})
<add> @Ignore({CHROME, IE, OPERA})
<ide> @Test
<ide> public void testDragTooFar() {
<ide> driver.get(pages.dragAndDropPage); |
|
Java | bsd-2-clause | 80b5e56d49a43fce82b5c43996282c1d63cf3b54 | 0 | TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej | //
// Dataset.java
//
/*
ImageJ software for multidimensional image processing and analysis.
Copyright (c) 2010, ImageJDev.org.
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 names of the ImageJDev.org developers 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 HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package imagej.data;
import imagej.data.event.DatasetChangedEvent;
import imagej.data.event.DatasetCreatedEvent;
import imagej.data.event.DatasetDeletedEvent;
import imagej.event.Events;
import imagej.util.Log;
import imagej.util.Rect;
import net.imglib2.Cursor;
import net.imglib2.RandomAccess;
import net.imglib2.display.ColorTable16;
import net.imglib2.display.ColorTable8;
import net.imglib2.img.Axis;
import net.imglib2.img.Img;
import net.imglib2.img.ImgPlus;
import net.imglib2.img.Metadata;
import net.imglib2.img.basictypeaccess.PlanarAccess;
import net.imglib2.img.basictypeaccess.array.ArrayDataAccess;
import net.imglib2.img.basictypeaccess.array.ByteArray;
import net.imglib2.img.basictypeaccess.array.DoubleArray;
import net.imglib2.img.basictypeaccess.array.FloatArray;
import net.imglib2.img.basictypeaccess.array.IntArray;
import net.imglib2.img.basictypeaccess.array.LongArray;
import net.imglib2.img.basictypeaccess.array.ShortArray;
import net.imglib2.img.planar.PlanarImg;
import net.imglib2.img.planar.PlanarImgFactory;
import net.imglib2.type.NativeType;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.IntegerType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.integer.IntType;
import net.imglib2.type.numeric.integer.LongType;
import net.imglib2.type.numeric.integer.ShortType;
import net.imglib2.type.numeric.integer.Unsigned12BitType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.integer.UnsignedIntType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.type.numeric.real.FloatType;
/**
* Dataset is the primary image data structure in ImageJ. A Dataset wraps an
* ImgLib {@link ImgPlus}. It also provides a number of convenience methods,
* such as the ability to access pixels on a plane-by-plane basis, and create
* new Datasets of various types easily.
*
* @author Curtis Rueden
* @author Barry DeZonia
*/
public class Dataset implements Comparable<Dataset>, Metadata {
private ImgPlus<? extends RealType<?>> imgPlus;
private boolean rgbMerged;
// FIXME TEMP - the current selection for this Dataset. Temporarily located
// here for plugin testing purposes. Really should be viewcentric.
private Rect selection;
public void setSelection(final int minX, final int minY, final int maxX,
final int maxY)
{
selection.x = minX;
selection.y = minY;
selection.width = maxX - minX + 1;
selection.height = maxY - minY + 1;
}
public Rect getSelection() {
return selection;
}
// END FIXME TEMP
public Dataset(final ImgPlus<? extends RealType<?>> imgPlus) {
this.imgPlus = imgPlus;
rgbMerged = false;
selection = new Rect();
Events.publish(new DatasetCreatedEvent(this));
}
/**
* For use in legacy layer only, this flag allows the various legacy layer
* image translators to support color images correctly.
*/
public void setRGBMerged(final boolean rgbMerged) {
this.rgbMerged = rgbMerged;
}
/**
* For use in legacy layer only, this flag allows the various legacy layer
* image translators to support color images correctly.
*/
public boolean isRGBMerged() {
return rgbMerged;
}
public ImgPlus<? extends RealType<?>> getImgPlus() {
return imgPlus;
}
public void setImgPlus(final ImgPlus<? extends RealType<?>> imgPlus) {
if (this.imgPlus.numDimensions() != imgPlus.numDimensions()) {
throw new IllegalArgumentException("Invalid dimensionality: expected " +
this.imgPlus.numDimensions() + " but was " + imgPlus.numDimensions());
}
this.imgPlus = imgPlus;
// NB - keeping all the old metadata for now. TODO - revisit this?
// NB - keeping isRgbMerged status for now. TODO - revisit this?
selection = new Rect();
update();
}
/** Gets the dimensional extents of the dataset. */
public long[] getDims() {
final long[] dims = new long[imgPlus.numDimensions()];
imgPlus.dimensions(dims);
return dims;
}
/** Gets the dimensional extents of the dataset. */
public Axis[] getAxes() {
final Axis[] axes = new Axis[imgPlus.numDimensions()];
axes(axes);
return axes;
}
public Object getPlane(final int no) {
final Img<? extends RealType<?>> img = imgPlus.getImg();
if (!(img instanceof PlanarAccess)) return null;
// TODO - extract a copy the plane if it cannot be obtained by reference
final PlanarAccess<?> planarAccess = (PlanarAccess<?>) img;
final Object plane = planarAccess.getPlane(no);
if (!(plane instanceof ArrayDataAccess)) return null;
return ((ArrayDataAccess<?>) plane).getCurrentStorageArray();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void setPlane(final int no, final Object plane) {
final Img<? extends RealType<?>> img = imgPlus.getImg();
if (!(img instanceof PlanarAccess)) {
// cannot set by reference
Log.error("Cannot set plane for non-planar image");
return;
}
// TODO - copy the plane if it cannot be set by reference
final PlanarAccess planarAccess = (PlanarAccess) img;
ArrayDataAccess<?> array = null;
if (plane instanceof byte[]) {
array = new ByteArray((byte[]) plane);
}
else if (plane instanceof short[]) {
array = new ShortArray((short[]) plane);
}
else if (plane instanceof int[]) {
array = new IntArray((int[]) plane);
}
else if (plane instanceof float[]) {
array = new FloatArray((float[]) plane);
}
else if (plane instanceof long[]) {
array = new LongArray((long[]) plane);
}
else if (plane instanceof double[]) {
array = new DoubleArray((double[]) plane);
}
planarAccess.setPlane(no, array);
}
public double getDoubleValue(final long[] pos) {
// NB: This method is slow... will change anyway with ImgLib2.
final RandomAccess<? extends RealType<?>> cursor = imgPlus.randomAccess();
cursor.setPosition(pos);
final double value = cursor.get().getRealDouble();
return value;
}
public RealType<?> getType() {
return imgPlus.firstElement();
}
public boolean isSigned() {
return getType().getMinValue() < 0;
}
public boolean isInteger() {
return getType() instanceof IntegerType;
}
/** Gets a string description of the dataset's pixel type. */
public String getTypeLabel() {
if (isRGBMerged()) return "RGB";
final int bitsPerPixel = getType().getBitsPerPixel();
final String category =
isInteger() ? isSigned() ? "signed" : "unsigned" : "real";
return bitsPerPixel + "-bit (" + category + ")";
}
/** Creates a copy of the dataset. */
public Dataset duplicate() {
final Dataset d = duplicateBlank();
copyInto(d);
return d;
}
/** Creates a copy of the dataset, but without copying any pixel values. */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Dataset duplicateBlank() {
final ImgPlus untypedImg = imgPlus;
final Dataset d = new Dataset(createBlankCopy(untypedImg));
d.setRGBMerged(isRGBMerged());
return d;
}
/** Copies the dataset's pixels into the given target dataset. */
public void copyInto(final Dataset target) {
final Cursor<? extends RealType<?>> in = imgPlus.localizingCursor();
final RandomAccess<? extends RealType<?>> out =
target.getImgPlus().randomAccess();
final long[] position = new long[imgPlus.numDimensions()];
while (in.hasNext()) {
in.next();
final double value = in.get().getRealDouble();
in.localize(position);
out.setPosition(position);
out.get().setReal(value);
}
}
/** Informs interested parties that the dataset has changed somehow. */
public void update() {
Events.publish(new DatasetChangedEvent(this));
}
/**
* Deletes the given dataset, cleaning up resources and removing it from the
* object manager.
*/
public void delete() {
Events.publish(new DatasetDeletedEvent(this));
}
@Override
public String toString() {
return imgPlus.getName();
}
// -- Comparable methods --
@Override
public int compareTo(final Dataset dataset) {
return imgPlus.getName().compareTo(dataset.imgPlus.getName());
}
// -- Metadata methods --
@Override
public String getName() {
return imgPlus.getName();
}
@Override
public void setName(final String name) {
imgPlus.setName(name);
}
@Override
public int getAxisIndex(final Axis axis) {
return imgPlus.getAxisIndex(axis);
}
@Override
public Axis axis(final int d) {
return imgPlus.axis(d);
}
@Override
public void axes(final Axis[] axes) {
imgPlus.axes(axes);
}
@Override
public void setAxis(final Axis axis, final int d) {
imgPlus.setAxis(axis, d);
}
@Override
public double calibration(final int d) {
return imgPlus.calibration(d);
}
@Override
public void calibration(final double[] cal) {
imgPlus.calibration(cal);
}
@Override
public void setCalibration(final double cal, final int d) {
imgPlus.setCalibration(cal, d);
}
@Override
public int getValidBits() {
return imgPlus.getValidBits();
}
@Override
public void setValidBits(final int bits) {
imgPlus.setValidBits(bits);
}
@Override
public int getCompositeChannelCount() {
return imgPlus.getCompositeChannelCount();
}
@Override
public void setCompositeChannelCount(final int count) {
imgPlus.setCompositeChannelCount(count);
}
@Override
public ColorTable8 getColorTable8(final int no) {
return imgPlus.getColorTable8(no);
}
@Override
public void setColorTable(final ColorTable8 lut, final int no) {
imgPlus.setColorTable(lut, no);
}
@Override
public ColorTable16 getColorTable16(int no) {
return imgPlus.getColorTable16(no);
}
@Override
public void setColorTable(ColorTable16 lut, int no) {
imgPlus.setColorTable(lut, no);
}
@Override
public void setColorTableCount(final int count) {
imgPlus.setColorTableCount(count);
}
// -- Utility methods --
/**
* Creates a new dataset.
*
* @param dims The dataset's dimensional extents.
* @param name The dataset's name.
* @param axes The dataset's dimensional axis labels.
* @param bitsPerPixel The dataset's bit depth. Currently supported bit depths
* include 1, 8, 12, 16, 32 and 64.
* @param signed Whether the dataset's pixels can have negative values.
* @param floating Whether the dataset's pixels can have non-integer values.
* @return The newly created dataset.
* @throws IllegalArgumentException If the combination of bitsPerPixel, signed
* and floating parameters do not form a valid data type.
*/
public static Dataset create(final long[] dims, final String name,
final Axis[] axes, final int bitsPerPixel, final boolean signed,
final boolean floating)
{
if (bitsPerPixel == 1) {
if (signed || floating) invalidParams(bitsPerPixel, signed, floating);
return create(new BitType(), dims, name, axes);
}
if (bitsPerPixel == 8) {
if (floating) invalidParams(bitsPerPixel, signed, floating);
if (signed) return create(new ByteType(), dims, name, axes);
return create(new UnsignedByteType(), dims, name, axes);
}
if (bitsPerPixel == 12) {
if (signed || floating) invalidParams(bitsPerPixel, signed, floating);
return create(new Unsigned12BitType(), dims, name, axes);
}
if (bitsPerPixel == 16) {
if (floating) invalidParams(bitsPerPixel, signed, floating);
if (signed) return create(new ShortType(), dims, name, axes);
return create(new UnsignedShortType(), dims, name, axes);
}
if (bitsPerPixel == 32) {
if (floating) {
if (!signed) invalidParams(bitsPerPixel, signed, floating);
return create(new FloatType(), dims, name, axes);
}
if (signed) return create(new IntType(), dims, name, axes);
return create(new UnsignedIntType(), dims, name, axes);
}
if (bitsPerPixel == 64) {
if (!signed) invalidParams(bitsPerPixel, signed, floating);
if (floating) return create(new DoubleType(), dims, name, axes);
return create(new LongType(), dims, name, axes);
}
invalidParams(bitsPerPixel, signed, floating);
return null;
}
/**
* Creates a new dataset.
*
* @param <T> The type of the dataset.
* @param type The type of the dataset.
* @param dims The dataset's dimensional extents.
* @param name The dataset's name.
* @param axes The dataset's dimensional axis labels.
* @return The newly created dataset.
*/
public static <T extends RealType<T> & NativeType<T>> Dataset create(
final T type, final long[] dims, final String name, final Axis[] axes)
{
final PlanarImgFactory<T> imgFactory = new PlanarImgFactory<T>();
final PlanarImg<T, ?> planarImg = imgFactory.create(dims, type);
final ImgPlus<T> imgPlus = new ImgPlus<T>(planarImg, name, axes, null);
return new Dataset(imgPlus);
}
// -- Helper methods --
private static void invalidParams(final int bitsPerPixel,
final boolean signed, final boolean floating)
{
throw new IllegalArgumentException("Invalid parameters: bitsPerPixel=" +
bitsPerPixel + ", signed=" + signed + ", floating=" + floating);
}
/** Makes an image that has same type, container, and dimensions as refImage. */
private static <T extends RealType<T>> ImgPlus<T> createBlankCopy(
final ImgPlus<T> img)
{
final long[] dimensions = new long[img.numDimensions()];
img.dimensions(dimensions);
final Img<T> blankImg =
img.factory().create(dimensions, img.firstElement());
return new ImgPlus<T>(blankImg, img);
}
}
| core/data/src/main/java/imagej/data/Dataset.java | //
// Dataset.java
//
/*
ImageJ software for multidimensional image processing and analysis.
Copyright (c) 2010, ImageJDev.org.
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 names of the ImageJDev.org developers 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 HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package imagej.data;
import imagej.data.event.DatasetChangedEvent;
import imagej.data.event.DatasetCreatedEvent;
import imagej.data.event.DatasetDeletedEvent;
import imagej.event.Events;
import imagej.util.Log;
import imagej.util.Rect;
import net.imglib2.Cursor;
import net.imglib2.RandomAccess;
import net.imglib2.display.ColorTable16;
import net.imglib2.display.ColorTable8;
import net.imglib2.img.Axis;
import net.imglib2.img.Img;
import net.imglib2.img.ImgPlus;
import net.imglib2.img.Metadata;
import net.imglib2.img.basictypeaccess.PlanarAccess;
import net.imglib2.img.basictypeaccess.array.ArrayDataAccess;
import net.imglib2.img.basictypeaccess.array.ByteArray;
import net.imglib2.img.basictypeaccess.array.DoubleArray;
import net.imglib2.img.basictypeaccess.array.FloatArray;
import net.imglib2.img.basictypeaccess.array.IntArray;
import net.imglib2.img.basictypeaccess.array.LongArray;
import net.imglib2.img.basictypeaccess.array.ShortArray;
import net.imglib2.img.planar.PlanarImg;
import net.imglib2.img.planar.PlanarImgFactory;
import net.imglib2.type.NativeType;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.IntegerType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.integer.IntType;
import net.imglib2.type.numeric.integer.LongType;
import net.imglib2.type.numeric.integer.ShortType;
import net.imglib2.type.numeric.integer.Unsigned12BitType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.integer.UnsignedIntType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.type.numeric.real.FloatType;
/**
* Dataset is the primary image data structure in ImageJ. A Dataset wraps an
* ImgLib {@link ImgPlus}. It also provides a number of convenience methods,
* such as the ability to access pixels on a plane-by-plane basis, and create
* new Datasets of various types easily.
*
* @author Curtis Rueden
* @author Barry DeZonia
*/
public class Dataset implements Comparable<Dataset>, Metadata {
private ImgPlus<? extends RealType<?>> imgPlus;
private boolean rgbMerged;
// FIXME TEMP - the current selection for this Dataset. Temporarily located
// here for plugin testing purposes. Really should be viewcentric.
private Rect selection;
public void setSelection(final int minX, final int minY, final int maxX,
final int maxY)
{
selection.x = minX;
selection.y = minY;
selection.width = maxX - minX + 1;
selection.height = maxY - minY + 1;
}
public Rect getSelection() {
return selection;
}
// END FIXME TEMP
public Dataset(final ImgPlus<? extends RealType<?>> imgPlus) {
this.imgPlus = imgPlus;
rgbMerged = false;
selection = new Rect();
Events.publish(new DatasetCreatedEvent(this));
}
/**
* For use in legacy layer only, this flag allows the various legacy layer
* image translators to support color images correctly.
*/
public void setRGBMerged(final boolean rgbMerged) {
this.rgbMerged = rgbMerged;
}
/**
* For use in legacy layer only, this flag allows the various legacy layer
* image translators to support color images correctly.
*/
public boolean isRGBMerged() {
return rgbMerged;
}
public ImgPlus<? extends RealType<?>> getImgPlus() {
return imgPlus;
}
public void setImgPlus(final ImgPlus<? extends RealType<?>> imgPlus) {
if (this.imgPlus.numDimensions() != imgPlus.numDimensions()) {
throw new IllegalArgumentException("Invalid dimensionality: expected " +
this.imgPlus.numDimensions() + " but was " + imgPlus.numDimensions());
}
this.imgPlus = imgPlus;
// NB - keeping all the old metadata for now. TODO - revisit this?
// NB - keeping isRgbMerged status for now. TODO - revisit this?
selection = new Rect();
update();
}
/** Gets the dimensional extents of the dataset. */
public long[] getDims() {
final long[] dims = new long[imgPlus.numDimensions()];
imgPlus.dimensions(dims);
return dims;
}
/** Gets the dimensional extents of the dataset. */
public Axis[] getAxes() {
final Axis[] axes = new Axis[imgPlus.numDimensions()];
axes(axes);
return axes;
}
public Object getPlane(final int no) {
final Img<? extends RealType<?>> img = imgPlus.getImg();
if (!(img instanceof PlanarAccess)) return null;
// TODO - extract a copy the plane if it cannot be obtained by reference
final PlanarAccess<?> planarAccess = (PlanarAccess<?>) img;
final Object plane = planarAccess.getPlane(no);
if (!(plane instanceof ArrayDataAccess)) return null;
return ((ArrayDataAccess<?>) plane).getCurrentStorageArray();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void setPlane(final int no, final Object plane) {
final Img<? extends RealType<?>> wrappedImg = imgPlus.getImg();
if (!(wrappedImg instanceof PlanarAccess)) {
// cannot set by reference
Log.error("Cannot set plane for non-planar image");
return;
}
// TODO - copy the plane if it cannot be set by reference
final PlanarAccess planarAccess = (PlanarAccess) wrappedImg;
ArrayDataAccess<?> array = null;
if (plane instanceof byte[]) {
array = new ByteArray((byte[]) plane);
}
else if (plane instanceof short[]) {
array = new ShortArray((short[]) plane);
}
else if (plane instanceof int[]) {
array = new IntArray((int[]) plane);
}
else if (plane instanceof float[]) {
array = new FloatArray((float[]) plane);
}
else if (plane instanceof long[]) {
array = new LongArray((long[]) plane);
}
else if (plane instanceof double[]) {
array = new DoubleArray((double[]) plane);
}
planarAccess.setPlane(no, array);
}
public double getDoubleValue(final long[] pos) {
// NB: This method is slow... will change anyway with ImgLib2.
final RandomAccess<? extends RealType<?>> cursor = imgPlus.randomAccess();
cursor.setPosition(pos);
final double value = cursor.get().getRealDouble();
return value;
}
public RealType<?> getType() {
return imgPlus.firstElement();
}
public boolean isSigned() {
return getType().getMinValue() < 0;
}
public boolean isInteger() {
return getType() instanceof IntegerType;
}
/** Gets a string description of the dataset's pixel type. */
public String getTypeLabel() {
if (isRGBMerged()) return "RGB";
final int bitsPerPixel = getType().getBitsPerPixel();
final String category =
isInteger() ? isSigned() ? "signed" : "unsigned" : "real";
return bitsPerPixel + "-bit (" + category + ")";
}
/** Creates a copy of the dataset. */
public Dataset duplicate() {
final Dataset d = duplicateBlank();
copyInto(d);
return d;
}
/** Creates a copy of the dataset, but without copying any pixel values. */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Dataset duplicateBlank() {
final ImgPlus untypedImg = imgPlus;
final Dataset d = new Dataset(createBlankCopy(untypedImg));
d.setRGBMerged(isRGBMerged());
return d;
}
/** Copies the dataset's pixels into the given target dataset. */
public void copyInto(final Dataset target) {
final Cursor<? extends RealType<?>> in = imgPlus.localizingCursor();
final RandomAccess<? extends RealType<?>> out =
target.getImgPlus().randomAccess();
final long[] position = new long[imgPlus.numDimensions()];
while (in.hasNext()) {
in.next();
final double value = in.get().getRealDouble();
in.localize(position);
out.setPosition(position);
out.get().setReal(value);
}
}
/** Informs interested parties that the dataset has changed somehow. */
public void update() {
Events.publish(new DatasetChangedEvent(this));
}
/**
* Deletes the given dataset, cleaning up resources and removing it from the
* object manager.
*/
public void delete() {
Events.publish(new DatasetDeletedEvent(this));
}
@Override
public String toString() {
return imgPlus.getName();
}
// -- Comparable methods --
@Override
public int compareTo(final Dataset dataset) {
return imgPlus.getName().compareTo(dataset.imgPlus.getName());
}
// -- Metadata methods --
@Override
public String getName() {
return imgPlus.getName();
}
@Override
public void setName(final String name) {
imgPlus.setName(name);
}
@Override
public int getAxisIndex(final Axis axis) {
return imgPlus.getAxisIndex(axis);
}
@Override
public Axis axis(final int d) {
return imgPlus.axis(d);
}
@Override
public void axes(final Axis[] axes) {
imgPlus.axes(axes);
}
@Override
public void setAxis(final Axis axis, final int d) {
imgPlus.setAxis(axis, d);
}
@Override
public double calibration(final int d) {
return imgPlus.calibration(d);
}
@Override
public void calibration(final double[] cal) {
imgPlus.calibration(cal);
}
@Override
public void setCalibration(final double cal, final int d) {
imgPlus.setCalibration(cal, d);
}
@Override
public int getValidBits() {
return imgPlus.getValidBits();
}
@Override
public void setValidBits(final int bits) {
imgPlus.setValidBits(bits);
}
@Override
public int getCompositeChannelCount() {
return imgPlus.getCompositeChannelCount();
}
@Override
public void setCompositeChannelCount(final int count) {
imgPlus.setCompositeChannelCount(count);
}
@Override
public ColorTable8 getColorTable8(final int no) {
return imgPlus.getColorTable8(no);
}
@Override
public void setColorTable(final ColorTable8 lut, final int no) {
imgPlus.setColorTable(lut, no);
}
@Override
public ColorTable16 getColorTable16(int no) {
return imgPlus.getColorTable16(no);
}
@Override
public void setColorTable(ColorTable16 lut, int no) {
imgPlus.setColorTable(lut, no);
}
@Override
public void setColorTableCount(final int count) {
imgPlus.setColorTableCount(count);
}
// -- Utility methods --
/**
* Creates a new dataset.
*
* @param dims The dataset's dimensional extents.
* @param name The dataset's name.
* @param axes The dataset's dimensional axis labels.
* @param bitsPerPixel The dataset's bit depth. Currently supported bit depths
* include 1, 8, 12, 16, 32 and 64.
* @param signed Whether the dataset's pixels can have negative values.
* @param floating Whether the dataset's pixels can have non-integer values.
* @return The newly created dataset.
* @throws IllegalArgumentException If the combination of bitsPerPixel, signed
* and floating parameters do not form a valid data type.
*/
public static Dataset create(final long[] dims, final String name,
final Axis[] axes, final int bitsPerPixel, final boolean signed,
final boolean floating)
{
if (bitsPerPixel == 1) {
if (signed || floating) invalidParams(bitsPerPixel, signed, floating);
return create(new BitType(), dims, name, axes);
}
if (bitsPerPixel == 8) {
if (floating) invalidParams(bitsPerPixel, signed, floating);
if (signed) return create(new ByteType(), dims, name, axes);
return create(new UnsignedByteType(), dims, name, axes);
}
if (bitsPerPixel == 12) {
if (signed || floating) invalidParams(bitsPerPixel, signed, floating);
return create(new Unsigned12BitType(), dims, name, axes);
}
if (bitsPerPixel == 16) {
if (floating) invalidParams(bitsPerPixel, signed, floating);
if (signed) return create(new ShortType(), dims, name, axes);
return create(new UnsignedShortType(), dims, name, axes);
}
if (bitsPerPixel == 32) {
if (floating) {
if (!signed) invalidParams(bitsPerPixel, signed, floating);
return create(new FloatType(), dims, name, axes);
}
if (signed) return create(new IntType(), dims, name, axes);
return create(new UnsignedIntType(), dims, name, axes);
}
if (bitsPerPixel == 64) {
if (!signed) invalidParams(bitsPerPixel, signed, floating);
if (floating) return create(new DoubleType(), dims, name, axes);
return create(new LongType(), dims, name, axes);
}
invalidParams(bitsPerPixel, signed, floating);
return null;
}
/**
* Creates a new dataset.
*
* @param <T> The type of the dataset.
* @param type The type of the dataset.
* @param dims The dataset's dimensional extents.
* @param name The dataset's name.
* @param axes The dataset's dimensional axis labels.
* @return The newly created dataset.
*/
public static <T extends RealType<T> & NativeType<T>> Dataset create(
final T type, final long[] dims, final String name, final Axis[] axes)
{
final PlanarImgFactory<T> imgFactory = new PlanarImgFactory<T>();
final PlanarImg<T, ?> planarImg = imgFactory.create(dims, type);
final ImgPlus<T> imgPlus = new ImgPlus<T>(planarImg, name, axes, null);
return new Dataset(imgPlus);
}
// -- Helper methods --
private static void invalidParams(final int bitsPerPixel,
final boolean signed, final boolean floating)
{
throw new IllegalArgumentException("Invalid parameters: bitsPerPixel=" +
bitsPerPixel + ", signed=" + signed + ", floating=" + floating);
}
/** Makes an image that has same type, container, and dimensions as refImage. */
private static <T extends RealType<T>> ImgPlus<T> createBlankCopy(
final ImgPlus<T> img)
{
final long[] dimensions = new long[img.numDimensions()];
img.dimensions(dimensions);
final Img<T> blankImg =
img.factory().create(dimensions, img.firstElement());
return new ImgPlus<T>(blankImg, img);
}
}
| Minor tweak, for consistency.
This used to be revision r2766.
| core/data/src/main/java/imagej/data/Dataset.java | Minor tweak, for consistency. | <ide><path>ore/data/src/main/java/imagej/data/Dataset.java
<ide>
<ide> @SuppressWarnings({ "rawtypes", "unchecked" })
<ide> public void setPlane(final int no, final Object plane) {
<del> final Img<? extends RealType<?>> wrappedImg = imgPlus.getImg();
<del> if (!(wrappedImg instanceof PlanarAccess)) {
<add> final Img<? extends RealType<?>> img = imgPlus.getImg();
<add> if (!(img instanceof PlanarAccess)) {
<ide> // cannot set by reference
<ide> Log.error("Cannot set plane for non-planar image");
<ide> return;
<ide> }
<ide> // TODO - copy the plane if it cannot be set by reference
<del> final PlanarAccess planarAccess = (PlanarAccess) wrappedImg;
<add> final PlanarAccess planarAccess = (PlanarAccess) img;
<ide> ArrayDataAccess<?> array = null;
<ide> if (plane instanceof byte[]) {
<ide> array = new ByteArray((byte[]) plane); |
|
Java | epl-1.0 | cd2fee2b9be854daa54cc12f90163b12926ab9be | 0 | Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1 | /*******************************************************************************
* Copyright (c) 2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.chart.reportitem.ui.views.provider;
import java.util.List;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.attribute.AxisType;
import org.eclipse.birt.chart.model.attribute.Bounds;
import org.eclipse.birt.chart.model.component.Axis;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.component.impl.SeriesImpl;
import org.eclipse.birt.chart.model.data.BaseSampleData;
import org.eclipse.birt.chart.model.data.DataFactory;
import org.eclipse.birt.chart.model.data.OrthogonalSampleData;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SampleData;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.data.impl.QueryImpl;
import org.eclipse.birt.chart.model.data.impl.SeriesDefinitionImpl;
import org.eclipse.birt.chart.model.impl.ChartWithAxesImpl;
import org.eclipse.birt.chart.model.type.impl.BarSeriesImpl;
import org.eclipse.birt.chart.reportitem.ChartReportItemImpl;
import org.eclipse.birt.chart.reportitem.api.ChartCubeUtil;
import org.eclipse.birt.chart.reportitem.api.ChartInXTabStatusManager;
import org.eclipse.birt.chart.reportitem.api.ChartItemUtil;
import org.eclipse.birt.chart.reportitem.api.ChartReportItemConstants;
import org.eclipse.birt.chart.reportitem.ui.ChartXTabUIUtil;
import org.eclipse.birt.chart.reportitem.ui.i18n.Messages;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;
import org.eclipse.birt.report.item.crosstab.core.de.AggregationCellHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabCellHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;
import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.MeasureViewHandle;
import org.eclipse.birt.report.item.crosstab.internal.ui.util.CrosstabUIHelper;
import org.eclipse.birt.report.item.crosstab.ui.extension.AggregationCellViewAdapter;
import org.eclipse.birt.report.item.crosstab.ui.extension.SwitchCellInfo;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
/**
* Provider for conversion between chart and text in cross tab
*/
public class ChartAggregationCellViewProvider extends
AggregationCellViewAdapter
{
public String getViewName( )
{
return ChartReportItemConstants.CHART_EXTENSION_NAME;
}
public String getViewDisplayName( )
{
return Messages.getString( "ChartAggregationCellViewProvider.Chart.DisplayName" ); //$NON-NLS-1$
}
public boolean matchView( AggregationCellHandle cell )
{
ExtendedItemHandle handle = getChartHandle( cell );
if ( handle != null )
{
// Only return true for plot chart
return ChartCubeUtil.isPlotChart( handle );
}
return false;
}
public void switchView( SwitchCellInfo info )
{
AggregationCellHandle cell = info.getAggregationCell( );
try
{
ChartWithAxes cm = createDefaultChart( info );
// Get the measure binding expression and drop the DataItemHandle
Object content = ChartCubeUtil.getFirstContent( cell );
if ( content instanceof DesignElementHandle )
{
( (DesignElementHandle) content ).dropAndClear( );
}
// Create the ExtendedItemHandle with default chart model
ExtendedItemHandle chartHandle = ChartCubeUtil.createChartHandle( cell.getModelHandle( ),
ChartReportItemConstants.TYPE_PLOT_CHART,
null );
ChartReportItemImpl reportItem = (ChartReportItemImpl) chartHandle.getReportItem( );
reportItem.setModel( cm );
cell.addContent( chartHandle, 0 );
// Set default bounds for chart model and handle
Bounds bounds = ChartItemUtil.createDefaultChartBounds( chartHandle,
cm );
cm.getBlock( ).setBounds( bounds );
chartHandle.setWidth( bounds.getWidth( ) + "pt" ); //$NON-NLS-1$
chartHandle.setHeight( bounds.getHeight( ) + "pt" ); //$NON-NLS-1$
// If adding chart in total cell and there are charts in other
// total cells, do not update direction.
if ( ChartCubeUtil.isAggregationCell( cell )
&& !checkChartInAllTotalCells( cell, cm.isTransposed( ) ) )
{
// Update xtab direction for multiple measure case
ChartCubeUtil.updateXTabDirection( cell.getCrosstab( ),
cm.isTransposed( ) );
}
// Set span and add axis cell
ChartCubeUtil.addAxisChartInXTab( cell,
cm,
chartHandle,
info.isNew( ) );
ChartInXTabStatusManager.updateGrandItemStatus( cell );
// In fixed layout, need to set width for other cells
if ( cell.getCrosstab( ).getModuleHandle( ) instanceof ReportDesignHandle
&& DesignChoiceConstants.REPORT_LAYOUT_PREFERENCE_FIXED_LAYOUT.equals( ( (ReportDesignHandle) cell.getCrosstab( )
.getModuleHandle( ) ).getLayoutPreference( ) ) )
{
CrosstabUIHelper.validateFixedColumnWidth( (ExtendedItemHandle) cell.getCrosstabHandle( ) );
}
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
}
public void restoreView( AggregationCellHandle cell )
{
try
{
if ( ( (MeasureViewHandle) cell.getContainer( ) ).getAggregationCount( ) > 1 )
{
// If total aggregation cell is still existent, do not remove
// size and grandtotal row/column
return;
}
ExtendedItemHandle chartHandle = getChartHandle( cell );
Chart cm = ChartItemUtil.getChartFromHandle( chartHandle );
// If it's axis chart, only remove axis in chart model
if ( ChartCubeUtil.isAxisChart( chartHandle ) )
{
Axis yAxis = ( (ChartWithAxes) cm ).getAxes( )
.get( 0 )
.getAssociatedAxes( )
.get( 0 );
yAxis.getLineAttributes( ).setVisible( false );
yAxis.getLabel( ).setVisible( false );
yAxis.getMajorGrid( ).getTickAttributes( ).setVisible( false );
return;
}
// Set null size back
CrosstabCellHandle levelCell = ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.ROW_AXIS_TYPE );
if ( levelCell != null )
{
cell.getCrosstab( ).setRowHeight( levelCell, null );
}
levelCell = ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.COLUMN_AXIS_TYPE );
if ( levelCell != null )
{
cell.getCrosstab( ).setColumnWidth( levelCell, null );
}
// Remove axis chart
ChartCubeUtil.removeAxisChartInXTab( cell,
ChartXTabUIUtil.isTransposedChartWithAxes( cm ),
true );
// Plot chart will be removed by designer itself
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
}
private ChartWithAxes createDefaultChart( SwitchCellInfo info )
{
AggregationCellHandle cell = info.getAggregationCell( );
// Get data type of measure
boolean bDateTypeMeasure = false;
if ( info.getMeasureInfo( ) != null )
{
String dataType = info.getCrosstab( )
.getCube( )
.getMeasure( info.getMeasureInfo( ).getMeasureName( ) )
.getDataType( );
bDateTypeMeasure = DesignChoiceConstants.COLUMN_DATA_TYPE_DATE.equals( dataType )
|| DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME.equals( dataType );
}
ChartWithAxes cm = ChartWithAxesImpl.create( );
cm.setType( "Bar Chart" );//$NON-NLS-1$
cm.setSubType( "Side-by-side" );//$NON-NLS-1$
cm.setUnits( "Points" ); //$NON-NLS-1$
cm.setUnitSpacing( 50 );
cm.getLegend( ).setVisible( false );
cm.getTitle( ).setVisible( false );
String exprMeasure = ChartCubeUtil.generateComputedColumnName( cell );
String exprCategory = null;
// Compute the correct chart direction according to xtab
if ( checkTransposed( cell ) )
{
cm.setTransposed( true );
cm.setReverseCategory( true );
// Get the row dimension binding name as Category expression
Object content = ChartCubeUtil.getFirstContent( ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.ROW_AXIS_TYPE ) );
if ( content instanceof DataItemHandle )
{
DataItemHandle dataItemHandle = (DataItemHandle) content;
exprCategory = dataItemHandle.getResultSetColumn( );
}
}
else
{
// Get the column dimension binding name as Category expression
Object content = ChartCubeUtil.getFirstContent( ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.COLUMN_AXIS_TYPE ) );
if ( content instanceof DataItemHandle )
{
DataItemHandle dataItemHandle = (DataItemHandle) content;
exprCategory = dataItemHandle.getResultSetColumn( );
}
}
// Add base series
Axis xAxis = cm.getBaseAxes( )[0];
SeriesDefinition sdBase = SeriesDefinitionImpl.create( );
sdBase.getSeriesPalette( ).shift( 0 );
Series series = SeriesImpl.create( );
sdBase.getSeries( ).add( series );
xAxis.setCategoryAxis( true );
xAxis.getSeriesDefinitions( ).add( sdBase );
if ( exprCategory != null )
{
Query query = QueryImpl.create( ExpressionUtil.createJSDataExpression( exprCategory ) );
series.getDataDefinition( ).add( query );
}
// Add orthogonal series
Axis yAxis = cm.getOrthogonalAxes( xAxis, true )[0];
SeriesDefinition sdOrth = SeriesDefinitionImpl.create( );
sdOrth.getSeriesPalette( ).shift( 0 );
series = BarSeriesImpl.create( );
sdOrth.getSeries( ).add( series );
yAxis.getSeriesDefinitions( ).add( sdOrth );
if ( bDateTypeMeasure )
{
yAxis.setType( AxisType.DATE_TIME_LITERAL );
}
if ( exprMeasure != null )
{
Query query = QueryImpl.create( ExpressionUtil.createJSDataExpression( exprMeasure ) );
series.getDataDefinition( ).add( query );
}
// Add sample data
SampleData sampleData = DataFactory.eINSTANCE.createSampleData( );
sampleData.getBaseSampleData( ).clear( );
sampleData.getOrthogonalSampleData( ).clear( );
// Create Base Sample Data
BaseSampleData sampleDataBase = DataFactory.eINSTANCE.createBaseSampleData( );
sampleDataBase.setDataSetRepresentation( ChartUtil.getNewSampleData( xAxis.getType( ),
0 ) );
sampleData.getBaseSampleData( ).add( sampleDataBase );
// Create Orthogonal Sample Data (with simulation count of 2)
OrthogonalSampleData sampleDataOrth = DataFactory.eINSTANCE.createOrthogonalSampleData( );
sampleDataOrth.setDataSetRepresentation( ChartUtil.getNewSampleData( yAxis.getType( ),
0 ) );
sampleDataOrth.setSeriesDefinitionIndex( 0 );
sampleData.getOrthogonalSampleData( ).add( sampleDataOrth );
cm.setSampleData( sampleData );
return cm;
}
private void updateChartQueries( ChartWithAxes cm,
AggregationCellHandle cell )
{
// Replace the query expression in chart model
String exprMeasure = ChartCubeUtil.generateComputedColumnName( cell );
String exprCategory = null;
if ( cm.isTransposed( ) )
{
// Get the row dimension binding name as Category
// expression
Object content = ChartCubeUtil.getFirstContent( ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.ROW_AXIS_TYPE ) );
if ( content instanceof DataItemHandle )
{
DataItemHandle dataItemHandle = (DataItemHandle) content;
exprCategory = dataItemHandle.getResultSetColumn( );
}
}
else
{
// Get the column dimension binding name as Category
// expression
Object content = ChartCubeUtil.getFirstContent( ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.COLUMN_AXIS_TYPE ) );
if ( content instanceof DataItemHandle )
{
DataItemHandle dataItemHandle = (DataItemHandle) content;
exprCategory = dataItemHandle.getResultSetColumn( );
}
}
if ( exprCategory != null )
{
SeriesDefinition sdCategory = cm.getBaseAxes( )[0].getSeriesDefinitions( )
.get( 0 );
Query queryCategory = sdCategory.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
queryCategory.setDefinition( ExpressionUtil.createJSDataExpression( exprCategory ) );
}
if ( exprMeasure != null )
{
SeriesDefinition sdValue = cm.getOrthogonalAxes( cm.getBaseAxes( )[0],
true )[0].getSeriesDefinitions( ).get( 0 );
Query queryValue = sdValue.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
queryValue.setDefinition( ExpressionUtil.createJSDataExpression( exprMeasure ) );
}
}
private ExtendedItemHandle getChartHandle( CrosstabCellHandle cell )
{
Object content = ChartCubeUtil.getFirstContent( cell );
if ( ChartCubeUtil.isChartHandle( content ) )
{
return (ExtendedItemHandle) content;
}
return null;
}
private boolean checkTransposed( AggregationCellHandle cell )
{
if ( ChartCubeUtil.isDetailCell( cell ) )
{
// If no column area, transpose chart.
if ( cell.getAggregationOnColumn( ) == null )
{
return true;
}
// If no row area, chart must be horizontal.
if ( cell.getAggregationOnRow( ) == null )
{
return false;
}
// If column grand/sub total cell already has chart, transpose
// current chart to keep the same direction
MeasureViewHandle mv = (MeasureViewHandle) cell.getContainer( );
for ( int i = 0; i < mv.getAggregationCount( ); i++ )
{
AggregationCellHandle otherCell = mv.getAggregationCell( i );
if ( cell.getDimensionView( ICrosstabConstants.ROW_AXIS_TYPE ) == otherCell.getDimensionView( ICrosstabConstants.ROW_AXIS_TYPE )
&& cell.getLevelView( ICrosstabConstants.ROW_AXIS_TYPE ) == otherCell.getLevelView( ICrosstabConstants.ROW_AXIS_TYPE ) )
{
Object content = ChartCubeUtil.getFirstContent( otherCell );
if ( ChartCubeUtil.isPlotChart( (DesignElementHandle) content ) )
{
return true;
}
}
}
// If chart in measure cell, use the original direction
Object content = ChartCubeUtil.getFirstContent( cell );
if ( ChartCubeUtil.isPlotChart( (DesignElementHandle) content ) )
{
return ( (ChartWithAxes) ChartCubeUtil.getChartFromHandle( (ExtendedItemHandle) content ) ).isTransposed( );
}
}
if ( ChartCubeUtil.isAggregationCell( cell ) )
{
LevelHandle levelRow = cell.getAggregationOnRow( );
LevelHandle levelColumn = cell.getAggregationOnColumn( );
// If in column grand total, transpose chart
if ( levelRow != null && levelColumn == null )
{
return true;
}
// If in row grand total, non-transpose chart
if ( levelRow == null && levelColumn != null )
{
return false;
}
// If in sub total
if ( levelRow != null && levelColumn != null )
{
// If column area's subtotal, transpose the chart
return isInSubtotal( cell, ICrosstabConstants.COLUMN_AXIS_TYPE );
}
return false;
}
// Use the direction of first chart in multiple measure case
List<ExtendedItemHandle> chartInOtherMeasure = ChartCubeUtil.findChartInOtherMeasures( cell,
true );
if ( !chartInOtherMeasure.isEmpty( ) )
{
return ( (ChartWithAxes) ChartCubeUtil.getChartFromHandle( chartInOtherMeasure.get( 0 ) ) ).isTransposed( );
}
// Default chart direction is the same with xtab's
return cell.getCrosstab( )
.getMeasureDirection( )
.equals( ICrosstabConstants.MEASURE_DIRECTION_HORIZONTAL );
}
private boolean isInSubtotal( AggregationCellHandle cell, int axisType )
{
int levelCount = ChartCubeUtil.getLevelCount( cell.getCrosstab( ),
axisType );
if ( levelCount > 1 )
{
LevelViewHandle currentLevel = cell.getLevelView( axisType );
for ( int i = 0; i < levelCount; i++ )
{
LevelViewHandle level = ChartCubeUtil.getLevel( cell.getCrosstab( ),
axisType,
i );
if ( level == currentLevel )
{
// If not last level, it's subtotal
return i < levelCount - 1;
}
}
}
return false;
}
@Override
public void updateView( AggregationCellHandle cell, int type )
{
Object contentItem = ChartCubeUtil.getFirstContent( cell );
if ( contentItem instanceof ExtendedItemHandle )
{
ExtendedItemHandle handle = (ExtendedItemHandle) contentItem;
try
{
if ( ChartCubeUtil.isPlotChart( handle ) )
{
// Update plot chart
// Reset query expressions
ChartReportItemImpl reportItem = (ChartReportItemImpl) handle.getReportItem( );
ChartWithAxes cm = (ChartWithAxes) reportItem.getProperty( ChartReportItemConstants.PROPERTY_CHART );
ChartWithAxes cmNew = cm;
if ( cm == null )
{
return;
}
cmNew = cm.copyInstance( );
if ( type == CHANGE_ORIENTATION_TYPE
&& cell.getAggregationOnColumn( ) != null
&& cell.getAggregationOnRow( ) != null
&& !ChartCubeUtil.isAggregationCell( cell ) )
{
// If event is from xtab direction and xtab has two
// aggregations and not in total cell, change chart's
// direction. Otherwise, change xtab's direction
cmNew.setTransposed( cell.getCrosstab( )
.getMeasureDirection( )
.equals( ICrosstabConstants.MEASURE_DIRECTION_HORIZONTAL ) );
cmNew.setReverseCategory( cmNew.isTransposed( ) );
}
updateChartQueries( cmNew, cell );
reportItem.executeSetModelCommand( handle, cm, cmNew );
// Reset cell span
if ( cmNew.isTransposed( ) )
{
cell.setSpanOverOnRow( cell.getAggregationOnRow( ) );
cell.setSpanOverOnColumn( null );
}
else
{
cell.setSpanOverOnColumn( cell.getAggregationOnColumn( ) );
cell.setSpanOverOnRow( null );
}
if ( type == CHANGE_ORIENTATION_TYPE )
{
ChartCubeUtil.updateXTabForAxis( cell,
handle,
cm.isTransposed( ),
cmNew );
}
else
{
// Replace date item with axis chart
ChartCubeUtil.updateAxisChart( cell, cmNew, handle );
// Update xtab direction for multiple measure case
ChartCubeUtil.updateXTabDirection( cell.getCrosstab( ),
cmNew.isTransposed( ) );
}
ChartInXTabStatusManager.updateGrandItemStatus( cell );
}
else if ( ChartCubeUtil.isAxisChart( handle ) )
{
// Remove axis chart if host chart does not exist
ExtendedItemHandle hostChartHandle = (ExtendedItemHandle) handle.getElementProperty( ChartReportItemConstants.PROPERTY_HOST_CHART );
if ( hostChartHandle == null )
{
handle.dropAndClear( );
return;
}
if ( type != CHANGE_ORIENTATION_TYPE )
{
ChartReportItemImpl reportItem = (ChartReportItemImpl) handle.getReportItem( );
ChartWithAxes cm = (ChartWithAxes) reportItem.getProperty( ChartReportItemConstants.PROPERTY_CHART );
// Update xtab direction for multiple measure case
ChartCubeUtil.updateXTabDirection( cell.getCrosstab( ),
cm.isTransposed( ) );
}
}
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
}
}
@Override
public boolean canSwitch( SwitchCellInfo info )
{
AggregationCellHandle cell = info.getAggregationCell( );
if ( cell != null )
{
// Do not allow switching to Chart for no aggregation case
if ( cell.getAggregationOnRow( ) == null
&& cell.getAggregationOnColumn( ) == null )
{
return false;
}
}
CrosstabReportItemHandle xtab = info.getCrosstab( );
if ( info.getType( ) == SwitchCellInfo.GRAND_TOTAL
|| info.getType( ) == SwitchCellInfo.SUB_TOTAL )
{
// Do not allow switching to Chart for no dimension case in total
// cell
if ( xtab.getDimensionCount( ICrosstabConstants.ROW_AXIS_TYPE ) == 0
|| xtab.getDimensionCount( ICrosstabConstants.COLUMN_AXIS_TYPE ) == 0 )
{
return false;
}
// If axis chart in total cell, don't allow to switch it to Chart
// view.
if ( ChartCubeUtil.findAxisChartInCell( cell ) != null )
{
return false;
}
}
// Not allow to switch string measure to chart
if ( info.getCrosstab( ).getCube( ) != null
&& info.getMeasureInfo( ) != null )
{
if ( info.getMeasureInfo( ).getMeasureName( ) == null )
{
return false;
}
String dataType = info.getCrosstab( )
.getCube( )
.getMeasure( info.getMeasureInfo( ).getMeasureName( ) )
.getDataType( );
return !DesignChoiceConstants.COLUMN_DATA_TYPE_STRING.equals( dataType );
}
return true;
}
private boolean checkChartInAllTotalCells( AggregationCellHandle cell,
boolean bTransposed )
{
MeasureViewHandle mv = (MeasureViewHandle) cell.getContainer( );
int count = mv.getAggregationCount( );
if ( count <= 1 )
{
return false;
}
for ( int i = 0; i < count; i++ )
{
AggregationCellHandle totalCell = mv.getAggregationCell( i );
if ( totalCell != null )
{
Object content = ChartCubeUtil.getFirstContent( totalCell );
if ( ChartCubeUtil.isChartHandle( content ) )
{
return true;
}
}
}
return false;
}
}
| chart/org.eclipse.birt.chart.reportitem.ui/src/org/eclipse/birt/chart/reportitem/ui/views/provider/ChartAggregationCellViewProvider.java | /*******************************************************************************
* Copyright (c) 2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.chart.reportitem.ui.views.provider;
import java.util.List;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.attribute.AxisType;
import org.eclipse.birt.chart.model.attribute.Bounds;
import org.eclipse.birt.chart.model.component.Axis;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.component.impl.SeriesImpl;
import org.eclipse.birt.chart.model.data.BaseSampleData;
import org.eclipse.birt.chart.model.data.DataFactory;
import org.eclipse.birt.chart.model.data.OrthogonalSampleData;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SampleData;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.data.impl.QueryImpl;
import org.eclipse.birt.chart.model.data.impl.SeriesDefinitionImpl;
import org.eclipse.birt.chart.model.impl.ChartWithAxesImpl;
import org.eclipse.birt.chart.model.type.impl.BarSeriesImpl;
import org.eclipse.birt.chart.reportitem.ChartReportItemImpl;
import org.eclipse.birt.chart.reportitem.api.ChartCubeUtil;
import org.eclipse.birt.chart.reportitem.api.ChartInXTabStatusManager;
import org.eclipse.birt.chart.reportitem.api.ChartItemUtil;
import org.eclipse.birt.chart.reportitem.api.ChartReportItemConstants;
import org.eclipse.birt.chart.reportitem.ui.ChartXTabUIUtil;
import org.eclipse.birt.chart.reportitem.ui.i18n.Messages;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;
import org.eclipse.birt.report.item.crosstab.core.de.AggregationCellHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabCellHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;
import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.MeasureViewHandle;
import org.eclipse.birt.report.item.crosstab.internal.ui.util.CrosstabUIHelper;
import org.eclipse.birt.report.item.crosstab.ui.extension.AggregationCellViewAdapter;
import org.eclipse.birt.report.item.crosstab.ui.extension.SwitchCellInfo;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
/**
* Provider for conversion between chart and text in cross tab
*/
public class ChartAggregationCellViewProvider extends
AggregationCellViewAdapter
{
public String getViewName( )
{
return ChartReportItemConstants.CHART_EXTENSION_NAME;
}
public String getViewDisplayName( )
{
return Messages.getString( "ChartAggregationCellViewProvider.Chart.DisplayName" ); //$NON-NLS-1$
}
public boolean matchView( AggregationCellHandle cell )
{
ExtendedItemHandle handle = getChartHandle( cell );
if ( handle != null )
{
// Only return true for plot chart
return ChartCubeUtil.isPlotChart( handle );
}
return false;
}
public void switchView( SwitchCellInfo info )
{
AggregationCellHandle cell = info.getAggregationCell( );
try
{
ChartWithAxes cm = createDefaultChart( info );
// Get the measure binding expression and drop the DataItemHandle
Object content = ChartCubeUtil.getFirstContent( cell );
if ( content instanceof DesignElementHandle )
{
( (DesignElementHandle) content ).dropAndClear( );
}
// Create the ExtendedItemHandle with default chart model
ExtendedItemHandle chartHandle = ChartCubeUtil.createChartHandle( cell.getModelHandle( ),
ChartReportItemConstants.TYPE_PLOT_CHART,
null );
ChartReportItemImpl reportItem = (ChartReportItemImpl) chartHandle.getReportItem( );
reportItem.setModel( cm );
cell.addContent( chartHandle, 0 );
// Set default bounds for chart model and handle
Bounds bounds = ChartItemUtil.createDefaultChartBounds( chartHandle,
cm );
cm.getBlock( ).setBounds( bounds );
chartHandle.setWidth( bounds.getWidth( ) + "pt" ); //$NON-NLS-1$
chartHandle.setHeight( bounds.getHeight( ) + "pt" ); //$NON-NLS-1$
// Update xtab direction for multiple measure case
ChartCubeUtil.updateXTabDirection( cell.getCrosstab( ),
cm.isTransposed( ) );
// Set span and add axis cell
ChartCubeUtil.addAxisChartInXTab( cell,
cm,
chartHandle,
info.isNew( ) );
ChartInXTabStatusManager.updateGrandItemStatus( cell );
// In fixed layout, need to set width for other cells
if ( cell.getCrosstab( ).getModuleHandle( ) instanceof ReportDesignHandle
&& DesignChoiceConstants.REPORT_LAYOUT_PREFERENCE_FIXED_LAYOUT.equals( ( (ReportDesignHandle) cell.getCrosstab( )
.getModuleHandle( ) ).getLayoutPreference( ) ) )
{
CrosstabUIHelper.validateFixedColumnWidth( (ExtendedItemHandle) cell.getCrosstabHandle( ) );
}
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
}
public void restoreView( AggregationCellHandle cell )
{
try
{
if ( ( (MeasureViewHandle) cell.getContainer( ) ).getAggregationCount( ) > 1 )
{
// If total aggregation cell is still existent, do not remove
// size and grandtotal row/column
return;
}
ExtendedItemHandle chartHandle = getChartHandle( cell );
Chart cm = ChartItemUtil.getChartFromHandle( chartHandle );
// If it's axis chart, only remove axis in chart model
if ( ChartCubeUtil.isAxisChart( chartHandle ) )
{
Axis yAxis = ( (ChartWithAxes) cm ).getAxes( )
.get( 0 )
.getAssociatedAxes( )
.get( 0 );
yAxis.getLineAttributes( ).setVisible( false );
yAxis.getLabel( ).setVisible( false );
yAxis.getMajorGrid( ).getTickAttributes( ).setVisible( false );
return;
}
// Set null size back
CrosstabCellHandle levelCell = ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.ROW_AXIS_TYPE );
if ( levelCell != null )
{
cell.getCrosstab( ).setRowHeight( levelCell, null );
}
levelCell = ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.COLUMN_AXIS_TYPE );
if ( levelCell != null )
{
cell.getCrosstab( ).setColumnWidth( levelCell, null );
}
// Remove axis chart
ChartCubeUtil.removeAxisChartInXTab( cell,
ChartXTabUIUtil.isTransposedChartWithAxes( cm ),
true );
// Plot chart will be removed by designer itself
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
}
private ChartWithAxes createDefaultChart( SwitchCellInfo info )
{
AggregationCellHandle cell = info.getAggregationCell( );
// Get data type of measure
boolean bDateTypeMeasure = false;
if ( info.getMeasureInfo( ) != null )
{
String dataType = info.getCrosstab( )
.getCube( )
.getMeasure( info.getMeasureInfo( ).getMeasureName( ) )
.getDataType( );
bDateTypeMeasure = DesignChoiceConstants.COLUMN_DATA_TYPE_DATE.equals( dataType )
|| DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME.equals( dataType );
}
ChartWithAxes cm = ChartWithAxesImpl.create( );
cm.setType( "Bar Chart" );//$NON-NLS-1$
cm.setSubType( "Side-by-side" );//$NON-NLS-1$
cm.setUnits( "Points" ); //$NON-NLS-1$
cm.setUnitSpacing( 50 );
cm.getLegend( ).setVisible( false );
cm.getTitle( ).setVisible( false );
String exprMeasure = ChartCubeUtil.generateComputedColumnName( cell );
String exprCategory = null;
// Compute the correct chart direction according to xtab
if ( checkTransposed( cell ) )
{
cm.setTransposed( true );
cm.setReverseCategory( true );
// Get the row dimension binding name as Category expression
Object content = ChartCubeUtil.getFirstContent( ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.ROW_AXIS_TYPE ) );
if ( content instanceof DataItemHandle )
{
DataItemHandle dataItemHandle = (DataItemHandle) content;
exprCategory = dataItemHandle.getResultSetColumn( );
}
}
else
{
// Get the column dimension binding name as Category expression
Object content = ChartCubeUtil.getFirstContent( ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.COLUMN_AXIS_TYPE ) );
if ( content instanceof DataItemHandle )
{
DataItemHandle dataItemHandle = (DataItemHandle) content;
exprCategory = dataItemHandle.getResultSetColumn( );
}
}
// Add base series
Axis xAxis = cm.getBaseAxes( )[0];
SeriesDefinition sdBase = SeriesDefinitionImpl.create( );
sdBase.getSeriesPalette( ).shift( 0 );
Series series = SeriesImpl.create( );
sdBase.getSeries( ).add( series );
xAxis.setCategoryAxis( true );
xAxis.getSeriesDefinitions( ).add( sdBase );
if ( exprCategory != null )
{
Query query = QueryImpl.create( ExpressionUtil.createJSDataExpression( exprCategory ) );
series.getDataDefinition( ).add( query );
}
// Add orthogonal series
Axis yAxis = cm.getOrthogonalAxes( xAxis, true )[0];
SeriesDefinition sdOrth = SeriesDefinitionImpl.create( );
sdOrth.getSeriesPalette( ).shift( 0 );
series = BarSeriesImpl.create( );
sdOrth.getSeries( ).add( series );
yAxis.getSeriesDefinitions( ).add( sdOrth );
if ( bDateTypeMeasure )
{
yAxis.setType( AxisType.DATE_TIME_LITERAL );
}
if ( exprMeasure != null )
{
Query query = QueryImpl.create( ExpressionUtil.createJSDataExpression( exprMeasure ) );
series.getDataDefinition( ).add( query );
}
// Add sample data
SampleData sampleData = DataFactory.eINSTANCE.createSampleData( );
sampleData.getBaseSampleData( ).clear( );
sampleData.getOrthogonalSampleData( ).clear( );
// Create Base Sample Data
BaseSampleData sampleDataBase = DataFactory.eINSTANCE.createBaseSampleData( );
sampleDataBase.setDataSetRepresentation( ChartUtil.getNewSampleData( xAxis.getType( ),
0 ) );
sampleData.getBaseSampleData( ).add( sampleDataBase );
// Create Orthogonal Sample Data (with simulation count of 2)
OrthogonalSampleData sampleDataOrth = DataFactory.eINSTANCE.createOrthogonalSampleData( );
sampleDataOrth.setDataSetRepresentation( ChartUtil.getNewSampleData( yAxis.getType( ),
0 ) );
sampleDataOrth.setSeriesDefinitionIndex( 0 );
sampleData.getOrthogonalSampleData( ).add( sampleDataOrth );
cm.setSampleData( sampleData );
return cm;
}
private void updateChartQueries( ChartWithAxes cm,
AggregationCellHandle cell )
{
// Replace the query expression in chart model
String exprMeasure = ChartCubeUtil.generateComputedColumnName( cell );
String exprCategory = null;
if ( cm.isTransposed( ) )
{
// Get the row dimension binding name as Category
// expression
Object content = ChartCubeUtil.getFirstContent( ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.ROW_AXIS_TYPE ) );
if ( content instanceof DataItemHandle )
{
DataItemHandle dataItemHandle = (DataItemHandle) content;
exprCategory = dataItemHandle.getResultSetColumn( );
}
}
else
{
// Get the column dimension binding name as Category
// expression
Object content = ChartCubeUtil.getFirstContent( ChartCubeUtil.getInnermostLevelCell( cell.getCrosstab( ),
ICrosstabConstants.COLUMN_AXIS_TYPE ) );
if ( content instanceof DataItemHandle )
{
DataItemHandle dataItemHandle = (DataItemHandle) content;
exprCategory = dataItemHandle.getResultSetColumn( );
}
}
if ( exprCategory != null )
{
SeriesDefinition sdCategory = cm.getBaseAxes( )[0].getSeriesDefinitions( )
.get( 0 );
Query queryCategory = sdCategory.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
queryCategory.setDefinition( ExpressionUtil.createJSDataExpression( exprCategory ) );
}
if ( exprMeasure != null )
{
SeriesDefinition sdValue = cm.getOrthogonalAxes( cm.getBaseAxes( )[0],
true )[0].getSeriesDefinitions( ).get( 0 );
Query queryValue = sdValue.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
queryValue.setDefinition( ExpressionUtil.createJSDataExpression( exprMeasure ) );
}
}
private ExtendedItemHandle getChartHandle( CrosstabCellHandle cell )
{
Object content = ChartCubeUtil.getFirstContent( cell );
if ( ChartCubeUtil.isChartHandle( content ) )
{
return (ExtendedItemHandle) content;
}
return null;
}
private boolean checkTransposed( AggregationCellHandle cell )
{
if ( ChartCubeUtil.isDetailCell( cell ) )
{
// If no column area, transpose chart.
if ( cell.getAggregationOnColumn( ) == null )
{
return true;
}
// If no row area, chart must be horizontal.
if ( cell.getAggregationOnRow( ) == null )
{
return false;
}
// If column grand/sub total cell already has chart, transpose
// current chart to keep the same direction
MeasureViewHandle mv = (MeasureViewHandle) cell.getContainer( );
for ( int i = 0; i < mv.getAggregationCount( ); i++ )
{
AggregationCellHandle otherCell = mv.getAggregationCell( i );
if ( cell.getDimensionView( ICrosstabConstants.ROW_AXIS_TYPE ) == otherCell.getDimensionView( ICrosstabConstants.ROW_AXIS_TYPE )
&& cell.getLevelView( ICrosstabConstants.ROW_AXIS_TYPE ) == otherCell.getLevelView( ICrosstabConstants.ROW_AXIS_TYPE ) )
{
Object content = ChartCubeUtil.getFirstContent( otherCell );
if ( ChartCubeUtil.isPlotChart( (DesignElementHandle) content ) )
{
return true;
}
}
}
// If chart in measure cell, use the original direction
Object content = ChartCubeUtil.getFirstContent( cell );
if ( ChartCubeUtil.isPlotChart( (DesignElementHandle) content ) )
{
return ( (ChartWithAxes) ChartCubeUtil.getChartFromHandle( (ExtendedItemHandle) content ) ).isTransposed( );
}
}
if ( ChartCubeUtil.isAggregationCell( cell ) )
{
LevelHandle levelRow = cell.getAggregationOnRow( );
LevelHandle levelColumn = cell.getAggregationOnColumn( );
// If in column grand total, transpose chart
if ( levelRow != null && levelColumn == null )
{
return true;
}
// If in row grand total, non-transpose chart
if ( levelRow == null && levelColumn != null )
{
return false;
}
// If in sub total
if ( levelRow != null && levelColumn != null )
{
// If column area's subtotal, transpose the chart
return isInSubtotal( cell, ICrosstabConstants.COLUMN_AXIS_TYPE );
}
return false;
}
// Use the direction of first chart in multiple measure case
List<ExtendedItemHandle> chartInOtherMeasure = ChartCubeUtil.findChartInOtherMeasures( cell,
true );
if ( !chartInOtherMeasure.isEmpty( ) )
{
return ( (ChartWithAxes) ChartCubeUtil.getChartFromHandle( chartInOtherMeasure.get( 0 ) ) ).isTransposed( );
}
// Default chart direction is the same with xtab's
return cell.getCrosstab( )
.getMeasureDirection( )
.equals( ICrosstabConstants.MEASURE_DIRECTION_HORIZONTAL );
}
private boolean isInSubtotal( AggregationCellHandle cell, int axisType )
{
int levelCount = ChartCubeUtil.getLevelCount( cell.getCrosstab( ),
axisType );
if ( levelCount > 1 )
{
LevelViewHandle currentLevel = cell.getLevelView( axisType );
for ( int i = 0; i < levelCount; i++ )
{
LevelViewHandle level = ChartCubeUtil.getLevel( cell.getCrosstab( ),
axisType,
i );
if ( level == currentLevel )
{
// If not last level, it's subtotal
return i < levelCount - 1;
}
}
}
return false;
}
@Override
public void updateView( AggregationCellHandle cell, int type )
{
Object contentItem = ChartCubeUtil.getFirstContent( cell );
if ( contentItem instanceof ExtendedItemHandle )
{
ExtendedItemHandle handle = (ExtendedItemHandle) contentItem;
try
{
if ( ChartCubeUtil.isPlotChart( handle ) )
{
// Update plot chart
// Reset query expressions
ChartReportItemImpl reportItem = (ChartReportItemImpl) handle.getReportItem( );
ChartWithAxes cm = (ChartWithAxes) reportItem.getProperty( ChartReportItemConstants.PROPERTY_CHART );
ChartWithAxes cmNew = cm;
if ( cm == null )
{
return;
}
cmNew = cm.copyInstance( );
if ( type == CHANGE_ORIENTATION_TYPE
&& cell.getAggregationOnColumn( ) != null
&& cell.getAggregationOnRow( ) != null
&& !ChartCubeUtil.isAggregationCell( cell ) )
{
// If event is from xtab direction and xtab has two
// aggregations and not in total cell, change chart's
// direction. Otherwise, change xtab's direction
cmNew.setTransposed( cell.getCrosstab( )
.getMeasureDirection( )
.equals( ICrosstabConstants.MEASURE_DIRECTION_HORIZONTAL ) );
cmNew.setReverseCategory( cmNew.isTransposed( ) );
}
updateChartQueries( cmNew, cell );
reportItem.executeSetModelCommand( handle, cm, cmNew );
// Reset cell span
if ( cmNew.isTransposed( ) )
{
cell.setSpanOverOnRow( cell.getAggregationOnRow( ) );
cell.setSpanOverOnColumn( null );
}
else
{
cell.setSpanOverOnColumn( cell.getAggregationOnColumn( ) );
cell.setSpanOverOnRow( null );
}
if ( type == CHANGE_ORIENTATION_TYPE )
{
ChartCubeUtil.updateXTabForAxis( cell,
handle,
cm.isTransposed( ),
cmNew );
}
else
{
// Replace date item with axis chart
ChartCubeUtil.updateAxisChart( cell, cmNew, handle );
// Update xtab direction for multiple measure case
ChartCubeUtil.updateXTabDirection( cell.getCrosstab( ),
cmNew.isTransposed( ) );
}
ChartInXTabStatusManager.updateGrandItemStatus( cell );
}
else if ( ChartCubeUtil.isAxisChart( handle ) )
{
// Remove axis chart if host chart does not exist
ExtendedItemHandle hostChartHandle = (ExtendedItemHandle) handle.getElementProperty( ChartReportItemConstants.PROPERTY_HOST_CHART );
if ( hostChartHandle == null )
{
handle.dropAndClear( );
return;
}
if ( type != CHANGE_ORIENTATION_TYPE )
{
ChartReportItemImpl reportItem = (ChartReportItemImpl) handle.getReportItem( );
ChartWithAxes cm = (ChartWithAxes) reportItem.getProperty( ChartReportItemConstants.PROPERTY_CHART );
// Update xtab direction for multiple measure case
ChartCubeUtil.updateXTabDirection( cell.getCrosstab( ),
cm.isTransposed( ) );
}
}
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
}
}
@Override
public boolean canSwitch( SwitchCellInfo info )
{
AggregationCellHandle cell = info.getAggregationCell( );
if ( cell != null )
{
// Do not allow switching to Chart for no aggregation case
if ( cell.getAggregationOnRow( ) == null
&& cell.getAggregationOnColumn( ) == null )
{
return false;
}
}
CrosstabReportItemHandle xtab = info.getCrosstab( );
if ( info.getType( ) == SwitchCellInfo.GRAND_TOTAL
|| info.getType( ) == SwitchCellInfo.SUB_TOTAL )
{
// Do not allow switching to Chart for no dimension case in total
// cell
if ( xtab.getDimensionCount( ICrosstabConstants.ROW_AXIS_TYPE ) == 0
|| xtab.getDimensionCount( ICrosstabConstants.COLUMN_AXIS_TYPE ) == 0 )
{
return false;
}
// If axis chart in total cell, don't allow to switch it to Chart
// view.
if ( ChartCubeUtil.findAxisChartInCell( cell ) != null )
{
return false;
}
}
// Not allow to switch string measure to chart
if ( info.getCrosstab( ).getCube( ) != null
&& info.getMeasureInfo( ) != null )
{
if ( info.getMeasureInfo( ).getMeasureName( ) == null )
{
return false;
}
String dataType = info.getCrosstab( )
.getCube( )
.getMeasure( info.getMeasureInfo( ).getMeasureName( ) )
.getDataType( );
return !DesignChoiceConstants.COLUMN_DATA_TYPE_STRING.equals( dataType );
}
return true;
}
}
| TED#35970
The issue only occurs when there are both chart views in two different grand total cells. Adding chart view will affect xtab direction to keep consistent, but xtab UI will add data items for empty cell once direction changed.
Now the fix is that if there has already been one chart view in grand/sub total, adding chart view in the other grand/sub total won't update xtab direction.
| chart/org.eclipse.birt.chart.reportitem.ui/src/org/eclipse/birt/chart/reportitem/ui/views/provider/ChartAggregationCellViewProvider.java | TED#35970 The issue only occurs when there are both chart views in two different grand total cells. Adding chart view will affect xtab direction to keep consistent, but xtab UI will add data items for empty cell once direction changed. Now the fix is that if there has already been one chart view in grand/sub total, adding chart view in the other grand/sub total won't update xtab direction. | <ide><path>hart/org.eclipse.birt.chart.reportitem.ui/src/org/eclipse/birt/chart/reportitem/ui/views/provider/ChartAggregationCellViewProvider.java
<ide> ChartReportItemImpl reportItem = (ChartReportItemImpl) chartHandle.getReportItem( );
<ide> reportItem.setModel( cm );
<ide> cell.addContent( chartHandle, 0 );
<del>
<add>
<ide> // Set default bounds for chart model and handle
<ide> Bounds bounds = ChartItemUtil.createDefaultChartBounds( chartHandle,
<ide> cm );
<ide> chartHandle.setWidth( bounds.getWidth( ) + "pt" ); //$NON-NLS-1$
<ide> chartHandle.setHeight( bounds.getHeight( ) + "pt" ); //$NON-NLS-1$
<ide>
<del> // Update xtab direction for multiple measure case
<del> ChartCubeUtil.updateXTabDirection( cell.getCrosstab( ),
<del> cm.isTransposed( ) );
<add> // If adding chart in total cell and there are charts in other
<add> // total cells, do not update direction.
<add> if ( ChartCubeUtil.isAggregationCell( cell )
<add> && !checkChartInAllTotalCells( cell, cm.isTransposed( ) ) )
<add> {
<add> // Update xtab direction for multiple measure case
<add> ChartCubeUtil.updateXTabDirection( cell.getCrosstab( ),
<add> cm.isTransposed( ) );
<add> }
<ide>
<ide> // Set span and add axis cell
<ide> ChartCubeUtil.addAxisChartInXTab( cell,
<ide> info.isNew( ) );
<ide>
<ide> ChartInXTabStatusManager.updateGrandItemStatus( cell );
<del>
<del> // In fixed layout, need to set width for other cells
<add>
<add> // In fixed layout, need to set width for other cells
<ide> if ( cell.getCrosstab( ).getModuleHandle( ) instanceof ReportDesignHandle
<ide> && DesignChoiceConstants.REPORT_LAYOUT_PREFERENCE_FIXED_LAYOUT.equals( ( (ReportDesignHandle) cell.getCrosstab( )
<ide> .getModuleHandle( ) ).getLayoutPreference( ) ) )
<ide> return true;
<ide> }
<ide>
<add> private boolean checkChartInAllTotalCells( AggregationCellHandle cell,
<add> boolean bTransposed )
<add> {
<add> MeasureViewHandle mv = (MeasureViewHandle) cell.getContainer( );
<add> int count = mv.getAggregationCount( );
<add> if ( count <= 1 )
<add> {
<add> return false;
<add> }
<add> for ( int i = 0; i < count; i++ )
<add> {
<add> AggregationCellHandle totalCell = mv.getAggregationCell( i );
<add> if ( totalCell != null )
<add> {
<add> Object content = ChartCubeUtil.getFirstContent( totalCell );
<add> if ( ChartCubeUtil.isChartHandle( content ) )
<add> {
<add> return true;
<add> }
<add> }
<add> }
<add> return false;
<add> }
<ide> } |
|
JavaScript | mit | a7a6cd2ad17bed4971aa2f34a5270e13b15b74fe | 0 | sbyrnes/bloom.js,sbyrnes/bloom.js | /**
* Bloom.js
*
* Javascript implementation of a Bloom Filter.
*
* @author <a href="mailto:[email protected]">Sean Byrnes</a>
* @see https://github.com/sbyrnes/bloom.js
*/
var MurmurHash = require('./murmurhash.js');
var BitArray = require('bit-array');
var DEFAULT_NUM_BUCKETS = 1000;
var DEFAULT_NUM_HASHES = 5;
var BloomFilter = function (buckets, hashes) {
if(buckets) this.numBuckets = buckets;
else this.numBuckets = DEFAULT_NUM_BUCKETS;
if(hashes) this.numHashes = hashes;
else this.numHashes = DEFAULT_NUM_HASHES;
this.bitVector = new BitArray(this.numBuckets);
}
/**
* Adds a value to the filter set.
* @param value The value to add to the set.
*/
BloomFilter.prototype.add = function(value)
{
this.hashify(String(value), function(index, bitVector) { bitVector.set(index, true); });
}
/**
* Tests whether a given value is a member of the filter set.
* @param value The value to test for.
* @return False if not in the set. True if likely to be in the set.
*/
BloomFilter.prototype.contains = function(value)
{
var result = true;
this.hashify(String(value), function(index, bitVector) { if(!bitVector.get(index)) result = false; });
return result;
}
/**
* Calculates hashes on the given value and involkes operator on each of the values.
* @param value The value to hashify.
* @param operator The function to call on all hash values individually.
*/
BloomFilter.prototype.hashify = function(value, operator)
{
// We can calculate many hash values from only a few actual hashes, using the method
// described here: https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf
var hash1 = hash(value, 0);
var hash2 = hash(value, hash1);
// Generate indexes using the function:
// h_i(x) = (h1(x) + i * h2(x)) % numBuckets
for(i = 0; i < this.numHashes; i++)
{
var index = Math.abs((hash1 + i * hash2) % this.numBuckets);
operator(index, this.bitVector);
}
}
/**
* Returns the filter set data for persistence or sharing.
* @return The filter data as a byte array.
*/
BloomFilter.prototype.getData = function()
{
return this.bitVector;
}
/**
* Loads the given filter data.
* @param data The filter data as a byte array.
* @return True if successful, false otherwise.
*/
BloomFilter.prototype.loadData = function(data)
{
// TODO: We should probably validate the data.
return this.bitVector = data;
}
/***** Hash Functions *********/
// Abstraction wrapper function to make it easier to swap in hash functions later.
function hash(value, seed)
{
return MurmurHash.murmurhash3_32_gc(value, seed);
}
module.exports = BloomFilter;
/**
* Estimate the false positive rate for a given set of usage parameters
* @param numValues The number of unique values in the set to be added to the filter.
* @param numBuckets The number of unique buckets (bits) in the filter
* @param numHashes The number of hashes to use.
* @return Estimated false positive percentage as a float.
*/
function estimateFalsePositiveRate(numValues, numBuckets, numHashes)
{
// Formula for false positives is (1-e^(-kn/m))^k
// k - number of hashes
// n - number of set entries
// m - number of buckets
var expectedFalsePositivesRate = Math.pow((1 - Math.exp(-numHashes * numValues / numBuckets)), numHashes);
return expectedFalsePositivesRate;
}
module.exports.estimateFalsePositiveRate = estimateFalsePositiveRate; | bloom.js | /**
* Bloom.js
*
* Javascript implementation of a Bloom Filter.
*
* @author <a href="mailto:[email protected]">Sean Byrnes</a>
* @see https://github.com/sbyrnes/bloom.js
*/
var MurmurHash = require('./murmurhash.js');
var BitArray = require('bit-array');
var DEFAULT_NUM_BUCKETS = 1000;
var DEFAULT_NUM_HASHES = 5;
var BloomFilter = function (buckets, hashes) {
if(buckets) this.numBuckets = buckets;
else this.numBuckets = DEFAULT_NUM_BUCKETS;
if(hashes) this.numHashes = hashes;
else this.numHashes = DEFAULT_NUM_HASHES;
this.bitVector = new BitArray(this.numBuckets);
}
/**
* Adds a value to the filter set.
* @param value The value to add to the set.
*/
BloomFilter.prototype.add = function(value)
{
this.hashify(String(value), function(index, bitVector) { bitVector.set(index, true); });
}
/**
* Tests whether a given value is a member of the filter set.
* @param value The value to test for.
* @return False if not in the set. True if likely to be in the set.
*/
BloomFilter.prototype.contains = function(value)
{
var result = true;
this.hashify(String(value), function(index, bitVector) { if(!bitVector.get(index)) result = false; });
return result;
}
/**
* Calculates hashes on the given value and involkes operator on each of the values.
* @param value The value to hashify.
* @param operator The function to call on all hash values individually.
*/
BloomFilter.prototype.hashify = function(value, operator)
{
// We can calculate many hash values from only a few actual hashes, using the method
// described here: http://www.eecs.harvard.edu/~kirsch/pubs/bbbf/esa06.pdf
var hash1 = hash(value, 0);
var hash2 = hash(value, hash1);
// Generate indexes using the function:
// h_i(x) = (h1(x) + i * h2(x)) % numBuckets
for(i = 0; i < this.numHashes; i++)
{
var index = Math.abs((hash1 + i * hash2) % this.numBuckets);
operator(index, this.bitVector);
}
}
/**
* Returns the filter set data for persistence or sharing.
* @return The filter data as a byte array.
*/
BloomFilter.prototype.getData = function()
{
return this.bitVector;
}
/**
* Loads the given filter data.
* @param data The filter data as a byte array.
* @return True if successful, false otherwise.
*/
BloomFilter.prototype.loadData = function(data)
{
// TODO: We should probably validate the data.
return this.bitVector = data;
}
/***** Hash Functions *********/
// Abstraction wrapper function to make it easier to swap in hash functions later.
function hash(value, seed)
{
return MurmurHash.murmurhash3_32_gc(value, seed);
}
module.exports = BloomFilter;
/**
* Estimate the false positive rate for a given set of usage parameters
* @param numValues The number of unique values in the set to be added to the filter.
* @param numBuckets The number of unique buckets (bits) in the filter
* @param numHashes The number of hashes to use.
* @return Estimated false positive percentage as a float.
*/
function estimateFalsePositiveRate(numValues, numBuckets, numHashes)
{
// Formula for false positives is (1-e^(-kn/m))^k
// k - number of hashes
// n - number of set entries
// m - number of buckets
var expectedFalsePositivesRate = Math.pow((1 - Math.exp(-numHashes * numValues / numBuckets)), numHashes);
return expectedFalsePositivesRate;
}
module.exports.estimateFalsePositiveRate = estimateFalsePositiveRate; | Fix broken url to "Building a Better Bloom Filter"
| bloom.js | Fix broken url to "Building a Better Bloom Filter" | <ide><path>loom.js
<ide> BloomFilter.prototype.hashify = function(value, operator)
<ide> {
<ide> // We can calculate many hash values from only a few actual hashes, using the method
<del> // described here: http://www.eecs.harvard.edu/~kirsch/pubs/bbbf/esa06.pdf
<add> // described here: https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf
<ide> var hash1 = hash(value, 0);
<ide> var hash2 = hash(value, hash1);
<ide> |
|
Java | apache-2.0 | f150fbfa29bfaac5a5b95b88062acceaf0a16a73 | 0 | zsoltk/overpasser,zsoltk/overpasser | package hu.supercluster.overpasser.library.query;
import java.util.Locale;
import java.util.Set;
class OverpassQueryBuilder {
private static final Locale LOCALE = Locale.US;
private StringBuilder builder;
public OverpassQueryBuilder() {
builder = new StringBuilder();
}
public OverpassQueryBuilder append(String statement) {
builder.append(statement);
return this;
}
public OverpassQueryBuilder boundingBox(double lat1, double lon1, double lat2, double lon2) {
builder.append(
String.format(
LOCALE,
"(%s,%s,%s,%s)",
lat1, lon1,
lat2, lon2
)
);
return this;
}
public OverpassQueryBuilder standaloneParam(String name) {
return paramRel(name, "", "");
}
public OverpassQueryBuilder clause(String name, String value) {
return paramRel(name, ":", value);
}
public OverpassQueryBuilder equals(String name, String value) {
return paramRel(name, "=", value);
}
public OverpassQueryBuilder multipleValues(String name, Set<String> values) {
StringBuilder joiner = new StringBuilder();
for (String value : values) {
joiner.append(value);
joiner.append("|");
}
joiner.setLength(joiner.length() - 1);
return paramRel(name, "~", joiner.toString());
}
public OverpassQueryBuilder notEquals(String name, String value) {
return paramRel(name, "!=", value);
}
public OverpassQueryBuilder regexMatches(String name, String value) {
return paramRel(name, "~", value);
}
public OverpassQueryBuilder regexDoesntMatch(String name, String value) {
return paramRel(name, "!~", value);
}
private OverpassQueryBuilder paramRel(String name, String rel, String value) {
String quotedValue = value.isEmpty() ? "" : String.format("\"%s\"", value);
builder.append(String.format(LOCALE, "[\"%s\"%s%s]", name, rel, quotedValue));
return this;
}
public String build() {
return builder.toString();
}
}
| library/src/main/java/hu/supercluster/overpasser/library/query/OverpassQueryBuilder.java | package hu.supercluster.overpasser.library.query;
import java.util.Set;
class OverpassQueryBuilder {
private StringBuilder builder;
public OverpassQueryBuilder() {
builder = new StringBuilder();
}
public OverpassQueryBuilder append(String statement) {
builder.append(statement);
return this;
}
public OverpassQueryBuilder boundingBox(double lat1, double lon1, double lat2, double lon2) {
builder.append(String.format("(%s,%s,%s,%s)",
lat1, lon1,
lat2, lon2
)
);
return this;
}
public OverpassQueryBuilder standaloneParam(String name) {
return paramRel(name, "", "");
}
public OverpassQueryBuilder clause(String name, String value) {
return paramRel(name, ":", value);
}
public OverpassQueryBuilder equals(String name, String value) {
return paramRel(name, "=", value);
}
public OverpassQueryBuilder multipleValues(String name, Set<String> values) {
StringBuilder joiner = new StringBuilder();
for (String value : values) {
joiner.append(value);
joiner.append("|");
}
joiner.setLength(joiner.length() - 1);
return paramRel(name, "~", joiner.toString());
}
public OverpassQueryBuilder notEquals(String name, String value) {
return paramRel(name, "!=", value);
}
public OverpassQueryBuilder regexMatches(String name, String value) {
return paramRel(name, "~", value);
}
public OverpassQueryBuilder regexDoesntMatch(String name, String value) {
return paramRel(name, "!~", value);
}
private OverpassQueryBuilder paramRel(String name, String rel, String value) {
String quotedValue = value.isEmpty() ? "" : String.format("\"%s\"", value);
builder.append(String.format("[\"%s\"%s%s]", name, rel, quotedValue));
return this;
}
public String build() {
return builder.toString();
}
}
| Use Locale.US in String.format()
| library/src/main/java/hu/supercluster/overpasser/library/query/OverpassQueryBuilder.java | Use Locale.US in String.format() | <ide><path>ibrary/src/main/java/hu/supercluster/overpasser/library/query/OverpassQueryBuilder.java
<ide> package hu.supercluster.overpasser.library.query;
<ide>
<add>import java.util.Locale;
<ide> import java.util.Set;
<ide>
<ide> class OverpassQueryBuilder {
<add> private static final Locale LOCALE = Locale.US;
<ide> private StringBuilder builder;
<ide>
<ide> public OverpassQueryBuilder() {
<ide> }
<ide>
<ide> public OverpassQueryBuilder boundingBox(double lat1, double lon1, double lat2, double lon2) {
<del> builder.append(String.format("(%s,%s,%s,%s)",
<add> builder.append(
<add> String.format(
<add> LOCALE,
<add> "(%s,%s,%s,%s)",
<ide> lat1, lon1,
<ide> lat2, lon2
<ide> )
<ide> private OverpassQueryBuilder paramRel(String name, String rel, String value) {
<ide> String quotedValue = value.isEmpty() ? "" : String.format("\"%s\"", value);
<ide>
<del> builder.append(String.format("[\"%s\"%s%s]", name, rel, quotedValue));
<add> builder.append(String.format(LOCALE, "[\"%s\"%s%s]", name, rel, quotedValue));
<ide>
<ide> return this;
<ide> } |
|
Java | mit | d02dbd0d5b64b8bae356c6b61f445b2842a47952 | 0 | freefair/gradle-plugins,freefair/gradle-plugins | package io.freefair.gradle.plugins.aspectj;
import lombok.Getter;
import lombok.Setter;
import org.gradle.api.Action;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.*;
import org.gradle.api.tasks.compile.AbstractOptions;
import org.gradle.process.CommandLineArgumentProvider;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
/**
* Compilation options to be passed to the AspectJ compiler.
*
* @author Lars Grefer
* @see org.gradle.api.tasks.compile.GroovyCompileOptions
* @see org.gradle.api.tasks.scala.ScalaCompileOptions
*/
@Getter
@Setter
public class AspectJCompileOptions extends AbstractOptions {
/**
* Accept as source bytecode any .class files in the .jar files or directories on Path.
* The output will include these classes, possibly as woven with any applicable aspects.
* Path is a single argument containing a list of paths to zip files or directories.
*/
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
@SkipWhenEmpty
private final ConfigurableFileCollection inpath;
/**
* Weave binary aspects from jar files and directories on path into all sources.
* The aspects should have been output by the same version of the compiler.
* When running the output classes, the run classpath should contain all aspectpath entries.
* Path, like classpath, is a single argument containing a list of paths to jar files.
*/
@Classpath
private final ConfigurableFileCollection aspectpath;
/**
* Put output classes in zip file output.jar.
*/
@OutputFile
@Optional
private final RegularFileProperty outjar;
/**
* Generate aop xml file for load-time weaving with default name (META-INF/aop-ajc.xml).
*/
@Input
private final Property<Boolean> outxml;
/**
* Generate aop.xml file for load-time weaving with custom name.
*/
@Input
@Optional
private final Property<String> outxmlfile;
/**
* Find and build all .java or .aj source files under any directory listed in DirPaths.
* DirPaths, like classpath, is a single argument containing a list of paths to directories.
*/
@SkipWhenEmpty
@PathSensitive(PathSensitivity.RELATIVE)
@InputFiles
private final ConfigurableFileCollection sourceroots;
/**
* Generate a build .ajsym file into the output directory.
* Used for viewing crosscutting references by tools like the AspectJ Browser.
*/
@Input
private final Property<Boolean> crossrefs;
/**
* Override location of VM's bootclasspath for purposes of evaluating types when compiling.
* Path is a single argument containing a list of paths to zip files or directories.
*/
@Classpath
private final ConfigurableFileCollection bootclasspath;
/**
* Override location of VM's extension directories for purposes of evaluating types when compiling.
* Path is a single argument containing a list of paths to directories.
*/
@Classpath
private final ConfigurableFileCollection extdirs;
/**
* @see <a href="https://stackoverflow.com/a/71120602/3574494">https://stackoverflow.com/a/71120602/3574494</a>
*/
@Input
@Optional
private final RegularFileProperty xmlConfigured;
/**
* Specify default source encoding format.
*/
@Input
@Optional
private final Property<String> encoding;
/**
* Emit messages about accessed/processed compilation units.
*/
@Console
private final Property<Boolean> verbose;
/**
* Any additional arguments to be passed to the compiler.
*/
@Input
private List<String> compilerArgs = new ArrayList<>();
@Input
private List<CommandLineArgumentProvider> compilerArgumentProviders = new ArrayList<>();
/**
* Options for running the compiler in a child process.
*/
@Internal
private final AjcForkOptions forkOptions = new AjcForkOptions();
public void forkOptions(Action<AjcForkOptions> action) {
action.execute(getForkOptions());
}
@Inject
public AspectJCompileOptions(ObjectFactory objectFactory) {
inpath = objectFactory.fileCollection();
aspectpath = objectFactory.fileCollection();
outjar = objectFactory.fileProperty();
outxml = objectFactory.property(Boolean.class).convention(false);
outxmlfile = objectFactory.property(String.class);
sourceroots = objectFactory.fileCollection();
crossrefs = objectFactory.property(Boolean.class).convention(false);
bootclasspath = objectFactory.fileCollection();
extdirs = objectFactory.fileCollection();
xmlConfigured = objectFactory.fileProperty();
encoding = objectFactory.property(String.class);
verbose = objectFactory.property(Boolean.class).convention(false);
}
}
| aspectj-plugin/src/main/java/io/freefair/gradle/plugins/aspectj/AspectJCompileOptions.java | package io.freefair.gradle.plugins.aspectj;
import lombok.Getter;
import lombok.Setter;
import org.gradle.api.Action;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.*;
import org.gradle.api.tasks.compile.AbstractOptions;
import org.gradle.process.CommandLineArgumentProvider;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
/**
* Compilation options to be passed to the AspectJ compiler.
*
* @author Lars Grefer
* @see org.gradle.api.tasks.compile.GroovyCompileOptions
* @see org.gradle.api.tasks.scala.ScalaCompileOptions
*/
@Getter
@Setter
public class AspectJCompileOptions extends AbstractOptions {
/**
* Accept as source bytecode any .class files in the .jar files or directories on Path.
* The output will include these classes, possibly as woven with any applicable aspects.
* Path is a single argument containing a list of paths to zip files or directories.
*/
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
@SkipWhenEmpty
private final ConfigurableFileCollection inpath;
/**
* Weave binary aspects from jar files and directories on path into all sources.
* The aspects should have been output by the same version of the compiler.
* When running the output classes, the run classpath should contain all aspectpath entries.
* Path, like classpath, is a single argument containing a list of paths to jar files.
*/
@Classpath
private final ConfigurableFileCollection aspectpath;
/**
* Put output classes in zip file output.jar.
*/
@OutputFile
@Optional
private final RegularFileProperty outjar;
/**
* Generate aop xml file for load-time weaving with default name (META-INF/aop-ajc.xml).
*/
@Input
private final Property<Boolean> outxml;
/**
* Generate aop.xml file for load-time weaving with custom name.
*/
@Input
@Optional
private final Property<String> outxmlfile;
/**
* Find and build all .java or .aj source files under any directory listed in DirPaths.
* DirPaths, like classpath, is a single argument containing a list of paths to directories.
*/
@SkipWhenEmpty
@PathSensitive(PathSensitivity.RELATIVE)
@InputFiles
private final ConfigurableFileCollection sourceroots;
/**
* Generate a build .ajsym file into the output directory.
* Used for viewing crosscutting references by tools like the AspectJ Browser.
*/
@Input
private final Property<Boolean> crossrefs;
/**
* Override location of VM's bootclasspath for purposes of evaluating types when compiling.
* Path is a single argument containing a list of paths to zip files or directories.
*/
@Classpath
private final ConfigurableFileCollection bootclasspath;
/**
* Override location of VM's extension directories for purposes of evaluating types when compiling.
* Path is a single argument containing a list of paths to directories.
*/
@Classpath
private final ConfigurableFileCollection extdirs;
/**
* @see <a href="https://stackoverflow.com/a/71120602/3574494">https://stackoverflow.com/a/71120602/3574494</a>
*/
@Input
private final RegularFileProperty xmlConfigured;
/**
* Specify default source encoding format.
*/
@Input
@Optional
private final Property<String> encoding;
/**
* Emit messages about accessed/processed compilation units.
*/
@Console
private final Property<Boolean> verbose;
/**
* Any additional arguments to be passed to the compiler.
*/
@Input
private List<String> compilerArgs = new ArrayList<>();
@Input
private List<CommandLineArgumentProvider> compilerArgumentProviders = new ArrayList<>();
/**
* Options for running the compiler in a child process.
*/
@Internal
private final AjcForkOptions forkOptions = new AjcForkOptions();
public void forkOptions(Action<AjcForkOptions> action) {
action.execute(getForkOptions());
}
@Inject
public AspectJCompileOptions(ObjectFactory objectFactory) {
inpath = objectFactory.fileCollection();
aspectpath = objectFactory.fileCollection();
outjar = objectFactory.fileProperty();
outxml = objectFactory.property(Boolean.class).convention(false);
outxmlfile = objectFactory.property(String.class);
sourceroots = objectFactory.fileCollection();
crossrefs = objectFactory.property(Boolean.class).convention(false);
bootclasspath = objectFactory.fileCollection();
extdirs = objectFactory.fileCollection();
xmlConfigured = objectFactory.fileProperty();
encoding = objectFactory.property(String.class);
verbose = objectFactory.property(Boolean.class).convention(false);
}
}
| Add support for the -xmlConfigured ajc option
| aspectj-plugin/src/main/java/io/freefair/gradle/plugins/aspectj/AspectJCompileOptions.java | Add support for the -xmlConfigured ajc option | <ide><path>spectj-plugin/src/main/java/io/freefair/gradle/plugins/aspectj/AspectJCompileOptions.java
<ide> * @see <a href="https://stackoverflow.com/a/71120602/3574494">https://stackoverflow.com/a/71120602/3574494</a>
<ide> */
<ide> @Input
<add> @Optional
<ide> private final RegularFileProperty xmlConfigured;
<ide>
<ide> /** |
|
Java | agpl-3.0 | 90685cbdd58f7dc6cf696ef9aeff0b7fbba3b11b | 0 | mvdstruijk/flamingo,B3Partners/flamingo,flamingo-geocms/flamingo,mvdstruijk/flamingo,mvdstruijk/flamingo,B3Partners/flamingo,B3Partners/flamingo,mvdstruijk/flamingo,flamingo-geocms/flamingo,flamingo-geocms/flamingo,B3Partners/flamingo,flamingo-geocms/flamingo | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.viewer.admin.stripes;
import java.util.List;
import net.sourceforge.stripes.action.ActionBeanContext;
import nl.b3p.viewer.config.app.Application;
import nl.b3p.viewer.config.app.StartLayer;
import nl.b3p.viewer.util.TestActionBeanContext;
import nl.b3p.viewer.util.TestUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
*
* @author Meine Toonen [email protected]
*/
public class ChooseApplicationActionBeanTest extends TestUtil {
private static final Log log = LogFactory.getLog(ChooseApplicationActionBeanTest.class);
@Test
public void testMakeWorkVersion() throws Exception {
try {
initData(true);
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
String version = "werkversie";
Application workVersion = caab.createWorkversion(app, entityManager,version);
Application prev = entityManager.merge(app);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
@Test
public void testMakeWorkVersionFromAppWithMashup() {
initData(true);
try {
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
Application mashup = app.createMashup("mashup", entityManager, true);
entityManager.persist(mashup);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
String version = "werkversie";
Application workVersion = caab.createWorkversion(app, entityManager, version);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
Application prev = entityManager.merge(app);
//objectsToRemove.add(entityManager.merge(mashup));
// objectsToRemove.add(prev);
// objectsToRemove.add(workVersion);
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
@Test
public void testMakeWorkVersionFromMashup() {
initData(true);
try {
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
Application mashup = app.createMashup("mashup", entityManager, true);
entityManager.persist(mashup);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
String version = "werkversie";
Application workVersion = caab.createWorkversion(mashup, entityManager, version);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
List origStartLayers = entityManager.createQuery("FROM StartLayer WHERE application = :app" , StartLayer.class).setParameter("app", app).getResultList();
List workversionStartLayers = entityManager.createQuery("FROM StartLayer WHERE application = :app" , StartLayer.class).setParameter("app", workVersion).getResultList();
assertEquals("Rootlevel should be the same ", app.getRoot().getId(),workVersion.getRoot().getId());
assertEquals(origStartLayers.size(), workversionStartLayers.size());
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
@Test
public void testDeleteApplication(){
initData(false);
try{
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
TestActionBeanContext context = new TestActionBeanContext();
caab.setApplicationToDelete(app);
caab.setContext(context);
caab.deleteApplication(entityManager);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
}catch(Exception e){
log.error("Fout", e);
assert (false);
}
}
@Test
public void testPublishWorkVersionFromMashup() {
initData(true);
try {
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
Long oldRootId = app.getRoot().getId();
List origAppStartLayers = entityManager.createQuery("FROM StartLayer WHERE application = :app" , StartLayer.class).setParameter("app", app).getResultList();
Application mashup = app.createMashup("mashup", entityManager, true);
entityManager.persist(mashup);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
String version = "werkversie";
Application workVersion = caab.createWorkversion(mashup, entityManager, version);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
workVersion.setVersion(null);
entityManager.persist(workVersion);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
ApplicationSettingsActionBean asab = new ApplicationSettingsActionBean();
asab.setContext(context);
asab.setApplication(workVersion);
asab.setMashupMustPointToPublishedVersion(true);
asab.publish(entityManager);
assertEquals("Rootlevel should be the same ", oldRootId, workVersion.getRoot().getId());
assertEquals("Rootlevel of original should remain the same", oldRootId, app.getRoot().getId());
List newAppStartLayers = entityManager.createQuery("FROM StartLayer WHERE application = :app" , StartLayer.class).setParameter("app", app).getResultList();
assertEquals(origAppStartLayers.size(), newAppStartLayers.size());
List workversionStartLayers = entityManager.createQuery("FROM StartLayer WHERE application = :app" , StartLayer.class).setParameter("app", workVersion).getResultList();
assertEquals(app.getRoot().getId(),workVersion.getRoot().getId());
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
@Test
public void testMakeMashupFromAppWithWorkversion() {
initData(true);
try {
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
String version = "werkversie";
Application workVersion = caab.createWorkversion(app, entityManager, version);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
Application mashup = app.createMashup("mashup", entityManager, true);
entityManager.persist(mashup);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
// Application prev = entityManager.merge(app);
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
}
| viewer-admin/src/test/java/nl/b3p/viewer/admin/stripes/ChooseApplicationActionBeanTest.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.viewer.admin.stripes;
import java.util.List;
import net.sourceforge.stripes.action.ActionBeanContext;
import nl.b3p.viewer.config.app.Application;
import nl.b3p.viewer.config.app.StartLayer;
import nl.b3p.viewer.util.TestActionBeanContext;
import nl.b3p.viewer.util.TestUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
*
* @author Meine Toonen [email protected]
*/
public class ChooseApplicationActionBeanTest extends TestUtil {
private static final Log log = LogFactory.getLog(ChooseApplicationActionBeanTest.class);
@Test
public void testMakeWorkVersion() throws Exception {
try {
initData(true);
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
String version = "werkversie";
Application workVersion = caab.createWorkversion(app, entityManager,version);
Application prev = entityManager.merge(app);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
@Test
public void testMakeWorkVersionFromAppWithMashup() {
initData(true);
try {
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
Application mashup = app.createMashup("mashup", entityManager, true);
entityManager.persist(mashup);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
String version = "werkversie";
Application workVersion = caab.createWorkversion(app, entityManager, version);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
Application prev = entityManager.merge(app);
//objectsToRemove.add(entityManager.merge(mashup));
// objectsToRemove.add(prev);
// objectsToRemove.add(workVersion);
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
@Test
public void testMakeWorkVersionFromMashup() {
initData(true);
try {
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
Application mashup = app.createMashup("mashup", entityManager, true);
entityManager.persist(mashup);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
String version = "werkversie";
Application workVersion = caab.createWorkversion(mashup, entityManager, version);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
List origStartLayers = entityManager.createQuery("FROM StartLayer WHERE application = :app" , StartLayer.class).setParameter("app", app).getResultList();
List workversionStartLayers = entityManager.createQuery("FROM StartLayer WHERE application = :app" , StartLayer.class).setParameter("app", workVersion).getResultList();
assertEquals("Rootlevel should be the same ", app.getRoot().getId(),workVersion.getRoot().getId());
assertEquals(origStartLayers.size(), workversionStartLayers.size());
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
@Test
public void testDeleteMashupWithWorkversion() {
initData(false);
try {
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
// Application a = entityManager.find(Application.class, applicationId);
Application mashup = app.createMashup("mashup", entityManager, true);
entityManager.persist(mashup);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
entityManager.flush();
String version = "werkversie";
Application workVersion = caab.createWorkversion(mashup, entityManager, version);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
entityManager.flush();
caab = new ChooseApplicationActionBean();
Application a = entityManager.find(Application.class, mashup.getId());
caab.setApplicationToDelete(a);
caab.setContext(context);
caab.deleteApplication(entityManager);
// entityManager.getTransaction().commit();
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
@Test
public void testDeleteApplication(){
initData(false);
try{
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
TestActionBeanContext context = new TestActionBeanContext();
caab.setApplicationToDelete(app);
caab.setContext(context);
caab.deleteApplication(entityManager);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
}catch(Exception e){
log.error("Fout", e);
assert (false);
}
}
@Test
public void testPublishWorkVersionFromMashup() {
initData(true);
try {
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
Long oldRootId = app.getRoot().getId();
List origAppStartLayers = entityManager.createQuery("FROM StartLayer WHERE application = :app" , StartLayer.class).setParameter("app", app).getResultList();
Application mashup = app.createMashup("mashup", entityManager, true);
entityManager.persist(mashup);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
String version = "werkversie";
Application workVersion = caab.createWorkversion(mashup, entityManager, version);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
workVersion.setVersion(null);
entityManager.persist(workVersion);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
ApplicationSettingsActionBean asab = new ApplicationSettingsActionBean();
asab.setContext(context);
asab.setApplication(workVersion);
asab.setMashupMustPointToPublishedVersion(true);
asab.publish(entityManager);
assertEquals("Rootlevel should be the same ", oldRootId, workVersion.getRoot().getId());
assertEquals("Rootlevel of original should remain the same", oldRootId, app.getRoot().getId());
List newAppStartLayers = entityManager.createQuery("FROM StartLayer WHERE application = :app" , StartLayer.class).setParameter("app", app).getResultList();
assertEquals(origAppStartLayers.size(), newAppStartLayers.size());
List workversionStartLayers = entityManager.createQuery("FROM StartLayer WHERE application = :app" , StartLayer.class).setParameter("app", workVersion).getResultList();
assertEquals(app.getRoot().getId(),workVersion.getRoot().getId());
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
@Test
public void testMakeMashupFromAppWithWorkversion() {
initData(true);
try {
ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
ActionBeanContext context = new ActionBeanContext();
caab.setContext(context);
String version = "werkversie";
Application workVersion = caab.createWorkversion(app, entityManager, version);
entityManager.getTransaction().begin();
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
Application mashup = app.createMashup("mashup", entityManager, true);
entityManager.persist(mashup);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
// Application prev = entityManager.merge(app);
} catch (Exception e) {
log.error("Fout", e);
assert (false);
}
}
}
| removed faulty test
| viewer-admin/src/test/java/nl/b3p/viewer/admin/stripes/ChooseApplicationActionBeanTest.java | removed faulty test | <ide><path>iewer-admin/src/test/java/nl/b3p/viewer/admin/stripes/ChooseApplicationActionBeanTest.java
<ide> }
<ide> }
<ide>
<del> @Test
<del> public void testDeleteMashupWithWorkversion() {
<del> initData(false);
<del> try {
<del> ChooseApplicationActionBean caab = new ChooseApplicationActionBean();
<del> ActionBeanContext context = new ActionBeanContext();
<del> caab.setContext(context);
<del>
<del> // Application a = entityManager.find(Application.class, applicationId);
<del> Application mashup = app.createMashup("mashup", entityManager, true);
<del> entityManager.persist(mashup);
<del> entityManager.getTransaction().commit();
<del> entityManager.getTransaction().begin();
<del> entityManager.flush();
<del> String version = "werkversie";
<del> Application workVersion = caab.createWorkversion(mashup, entityManager, version);
<del>
<del>
<del> entityManager.getTransaction().begin();
<del> entityManager.getTransaction().commit();
<del> entityManager.getTransaction().begin();
<del> entityManager.flush();
<del>
<del> caab = new ChooseApplicationActionBean();
<del> Application a = entityManager.find(Application.class, mashup.getId());
<del> caab.setApplicationToDelete(a);
<del> caab.setContext(context);
<del> caab.deleteApplication(entityManager);
<del> // entityManager.getTransaction().commit();
<del> } catch (Exception e) {
<del> log.error("Fout", e);
<del> assert (false);
<del> }
<del> }
<del>
<ide> @Test
<ide> public void testDeleteApplication(){
<ide> initData(false); |
|
JavaScript | mit | 045d4161bc0d97bf3e3fc5d340c3bc1e36978c17 | 0 | Joris-van-der-Wel/jsdom,sebmck/jsdom,fiftin/jsdom,AshCoolman/jsdom,jeffcarp/jsdom,Sebmaster/jsdom,zaucy/jsdom,fiftin/jsdom,darobin/jsdom,janusnic/jsdom,aduyng/jsdom,aduyng/jsdom,kesla/jsdom,janusnic/jsdom,susaing/jsdom,medikoo/jsdom,kittens/jsdom,sebmck/jsdom,Sebmaster/jsdom,susaing/jsdom,Sebmaster/jsdom,kevinold/jsdom,Zirro/jsdom,cpojer/jsdom,fiftin/jsdom,mbostock/jsdom,evdevgit/jsdom,kittens/jsdom,zaucy/jsdom,lcstore/jsdom,beni55/jsdom,kittens/jsdom,mzgol/jsdom,AVGP/jsdom,medikoo/jsdom,mbostock/jsdom,cpojer/jsdom,mzgol/jsdom,robertknight/jsdom,vestineo/jsdom,beni55/jsdom,selam/jsdom,snuggs/jsdom,crealogix/jsdom,jeffcarp/jsdom,szarouski/jsdom,nicolashenry/jsdom,Joris-van-der-Wel/jsdom,sirbrillig/jsdom,kevinold/jsdom,danieljoppi/jsdom,vestineo/jsdom,kevinold/jsdom,nicolashenry/jsdom,mbostock/jsdom,lcstore/jsdom,evanlucas/jsdom,Ye-Yong-Chi/jsdom,sirbrillig/jsdom,sirbrillig/jsdom,Ye-Yong-Chi/jsdom,selam/jsdom,evdevgit/jsdom,aduyng/jsdom,danieljoppi/jsdom,beni55/jsdom,sebmck/jsdom,crealogix/jsdom,jeffcarp/jsdom,nicolashenry/jsdom,darobin/jsdom,zaucy/jsdom,snuggs/jsdom,Zirro/jsdom,szarouski/jsdom,danieljoppi/jsdom,medikoo/jsdom,evanlucas/jsdom,mzgol/jsdom,tmpvar/jsdom,darobin/jsdom,AVGP/jsdom,AshCoolman/jsdom,susaing/jsdom,tmpvar/jsdom,Ye-Yong-Chi/jsdom,robertknight/jsdom,vestineo/jsdom,robertknight/jsdom,cpojer/jsdom,Joris-van-der-Wel/jsdom,AshCoolman/jsdom,lcstore/jsdom,evanlucas/jsdom,janusnic/jsdom,evdevgit/jsdom,selam/jsdom,szarouski/jsdom,kesla/jsdom,kesla/jsdom | "use strict";
var env = require("../..").env;
var path = require("path");
var http = require("http");
var fs = require("fs");
var toFileUrl = require("../util").toFileUrl(__dirname);
exports["with invalid arguments"] = function (t) {
t.throws(function () { jsdom.env(); });
t.throws(function () { jsdom.env({}); });
t.throws(function () { jsdom.env({ html: "abc123" }); });
t.throws(function () { jsdom.env({ done: function () {} }); });
t.done();
};
exports["explicit config.html, full document"] = function (t) {
env({
html: "<!DOCTYPE html><html><head><title>Hi</title></head><body>Hello</body></html>",
url: "http://example.com/",
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<!DOCTYPE html><html><head><title>Hi</title></head><body>Hello</body></html>");
t.equal(window.location.href, "http://example.com/");
t.equal(window.location.origin, "http://example.com");
t.done();
}
});
};
exports["explicit config.html, with overriden config.url"] = function (t) {
env({
html: "Hello",
url: "http://example.com/",
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<html><head></head><body>Hello</body></html>");
t.equal(window.location.href, "http://example.com/");
t.equal(window.location.origin, "http://example.com");
t.equal(window.location.search, "");
t.equal(window.location.hash, "");
t.done();
}
});
};
exports["explicit config.html, with overriden config.url including hash"] = function (t) {
env({
html: "Hello",
url: "http://example.com/#foo",
done: function (err, window) {
t.ifError(err);
t.equal(window.location.hash, "#foo");
t.done();
}
});
};
exports["explicit config.html, with overriden config.url including search and hash"] = function (t) {
env({
html: "Hello",
url: "http://example.com/?foo=bar#baz",
done: function (err, window) {
t.ifError(err);
t.equal(window.location.search, "?foo=bar");
t.equal(window.location.hash, "#baz");
t.done();
}
});
};
exports["explicit config.html, without a config.url"] = function (t) {
env({
html: "<html><head></head><body><p>hello world!</p></body></html>",
done: function (err, window) {
t.ifError(err);
t.notEqual(window.location.href, null);
t.done();
}
});
};
exports["explicit config.html, with poorly formatted HTML"] = function (t) {
env({
html: "some poorly<div>formed<b>html</div> fragment",
done: function (err, window) {
t.ifError(err);
t.notEqual(window.location.href, null);
t.done();
}
});
};
exports["explicit config.html, a string that is also a valid URL"] = function (t) {
env({
html: "http://example.com/",
url: "http://example.com/",
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<html><head></head><body>http://example.com/</body></html>");
t.equal(window.location.href, "http://example.com/");
t.done();
}
});
};
exports["explicit config.html, a string that is also a valid file"] = function (t) {
var body = path.resolve(__dirname, "files/env.html");
env({
html: body,
url: "http://example.com/",
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<html><head></head><body>" + body + "</body></html>");
t.equal(window.location.href, "http://example.com/");
t.done();
}
});
};
exports["explicit config.url, valid"] = function (t) {
var html = "<html><head><title>Example URL</title></head><body>Example!</body></html>";
var responseText = "<!DOCTYPE html>" + html;
var server = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Length": responseText.length });
res.end(responseText);
server.close();
}).listen(8976);
env({
url: "http://localhost:8976/",
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, responseText);
t.equal(window.location.href, "http://localhost:8976/");
t.equal(window.location.origin, "http://localhost:8976");
t.done();
}
});
};
exports["explicit config.url, invalid"] = function (t) {
env({
url: "http://localhost:8976",
done: function (err, window) {
t.ok(err, 'an error should exist');
t.strictEqual(window, undefined, 'window should not exist');
t.done();
}
});
};
exports["explicit config.file, valid"] = function (t) {
var fileName = path.resolve(__dirname, "files/env.html");
env({
file: fileName,
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, '<!DOCTYPE html><html><head>\n\
<title>hello, Node.js!</title>\n\
</head>\n\
<body>\n\
\n\
\n\
</body></html>');
t.equal(window.location.href, toFileUrl(fileName));
t.done();
}
});
};
exports["explicit config.file, invalid"] = function (t) {
env({
file: "__DOES_NOT_EXIST__",
done: function (err, window) {
t.ok(err, 'an error should exist');
t.strictEqual(window, undefined, 'window should not exist');
t.done();
}
});
};
exports["explicit config.file, with a script"] = function (t) {
env({
file: path.resolve(__dirname, "files/env.html"),
scripts: [path.resolve(__dirname, "../jquery-fixtures/jquery-1.6.2.js")],
done: function (err, window) {
t.ifError(err);
var $ = window.jQuery;
var text = "Let's Rock!";
$("body").text(text);
t.equal($("body").text(), text);
t.done();
}
});
};
exports["explicit config.file, with spaces in the file name"] = function (t) {
var fileName = path.resolve(__dirname, "files/folder space/space.html");
env({
file: fileName,
done: function (err, window) {
t.ifError(err);
t.done();
}
});
};
exports["string, parseable as a URL, valid"] = function (t) {
var html = "<html><head><title>Example URL</title></head><body>Example!</body></html>";
var responseText = "<!DOCTYPE html>" + html;
var server = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Length": responseText.length });
res.end(responseText);
server.close();
}).listen(8976);
env(
"http://localhost:8976/",
function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, responseText);
t.equal(window.location.href, "http://localhost:8976/");
t.equal(window.location.origin, "http://localhost:8976");
t.done();
}
);
};
exports["string, parseable as a URL, invalid"] = function (t) {
env(
"http://localhost:8976",
function (err, window) {
t.ok(err, 'an error should exist');
t.strictEqual(window, undefined, 'window should not exist');
t.done();
}
);
};
exports["string, for an existing filename"] = function (t) {
var fileName = path.resolve(__dirname, "files/env.html");
env(
fileName,
function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, '<!DOCTYPE html><html><head>\n\
<title>hello, Node.js!</title>\n\
</head>\n\
<body>\n\
\n\
\n\
</body></html>');
t.equal(window.location.href, toFileUrl(fileName));
t.done();
}
);
};
exports["string, does not exist as a file"] = function (t) {
var body = "__DOES_NOT_EXIST__";
env(
body,
function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<html><head></head><body>" + body + "</body></html>");
t.done();
}
);
};
exports["string, full HTML document"] = function (t) {
env(
"<!DOCTYPE html><html><head><title>Hi</title></head><body>Hello</body></html>",
function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<!DOCTYPE html><html><head><title>Hi</title></head><body>Hello</body></html>");
t.done();
}
);
};
exports["with a nonexistant script"] = function (t) {
env({
html: "<!DOCTYPE html><html><head></head><body><p>hello world!</p></body></html>",
scripts: ["path/to/invalid.js", "another/invalid.js"],
done: function (err, window) {
t.ok(err);
t.equal(err.length, 2);
t.ok(window.location.href);
t.done();
}
});
};
exports["with src"] = function (t) {
env({
html: "<!DOCTYPE html><html><head></head><body><p>hello world!</p></body></html>",
src: "window.attachedHere = 123;",
done: function (err, window) {
t.ifError(err);
t.ok(window.location.href);
t.equal(window.attachedHere, 123);
t.equal(window.document.getElementsByTagName("p").item(0).innerHTML, "hello world!");
t.done();
}
});
};
exports["with document referrer"] = function (t) {
env({
html: "<!DOCTYPE html><html><head></head><body><p>hello world!</p></body></html>",
document: { referrer: "https://github.com/tmpvar/jsdom" },
done: function (err, window) {
t.ifError(err);
t.equal(window.document.referrer, "https://github.com/tmpvar/jsdom");
t.done();
}
});
};
exports["with document cookie"] = function (t) {
var time = new Date(Date.now() + 24 * 60 * 60 * 1000);
var cookie = "key=value; expires=" + time.toGMTString() + "; path=/";
env({
html: "<!DOCTYPE html><html><head></head><body><p>hello world!</p></body></html>",
document: { cookie: cookie },
done: function (err, window) {
t.ifError(err);
t.equal(window.document.cookie, "key=value");
t.done();
}
});
};
exports["with scripts and content retrieved from URLs"] = function (t) {
var routes = {
"/js": "window.attachedHere = 123;",
"/html": "<a href='/path/to/hello'>World</a>"
};
var server = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Length": routes[req.url].length });
res.end(routes[req.url]);
});
server.listen(64000, "127.0.0.1", function () {
env({
url: "http://127.0.0.1:64000/html",
scripts: "http://127.0.0.1:64000/js",
done: function (err, window) {
server.close();
t.ifError(err);
t.equal(window.location.href, "http://127.0.0.1:64000/html");
t.equal(window.location.origin, "http://127.0.0.1:64000");
t.equal(window.attachedHere, 123);
t.equal(window.document.getElementsByTagName("a").item(0).innerHTML, "World");
t.done();
}
});
});
};
exports["should call callbacks correctly"] = function (t) {
t.expect(11);
env({
html: "<!DOCTYPE html><html><head><script>window.isExecuted = true;window.wasCreatedSet = window.isCreated;</script></head><body></body></html>",
features: {
FetchExternalResources: ["script"],
ProcessExternalResources: ["script"],
SkipExternalResources: false
},
created: function (err, window) {
t.ifError(err);
t.notEqual(window.isExecuted, true);
t.strictEqual(window.wasCreatedSet, undefined);
window.isCreated = true;
},
loaded: function (err, window) {
t.ifError(err);
t.strictEqual(window.isCreated, true);
t.strictEqual(window.isExecuted, true);
t.strictEqual(window.wasCreatedSet, true);
},
done: function (err, window) {
t.ifError(err);
t.strictEqual(window.isCreated, true);
t.strictEqual(window.isExecuted, true);
t.strictEqual(window.wasCreatedSet, true);
t.done();
}
});
};
| test/jsdom/env.js | "use strict";
var env = require("../..").env;
var path = require("path");
var http = require("http");
var fs = require("fs");
var toFileUrl = require("../util").toFileUrl(__dirname);
exports["with invalid arguments"] = function (t) {
t.throws(function () { jsdom.env(); });
t.throws(function () { jsdom.env({}); });
t.throws(function () { jsdom.env({ html: "abc123" }); });
t.throws(function () { jsdom.env({ done: function () {} }); });
t.done();
};
exports["explicit config.html, full document"] = function (t) {
env({
html: "<!DOCTYPE html><html><head><title>Hi</title></head><body>Hello</body></html>",
url: "http://example.com/",
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<!DOCTYPE html><html><head><title>Hi</title></head><body>Hello</body></html>");
t.equal(window.location.href, "http://example.com/");
t.equal(window.location.origin, "http://example.com");
t.done();
}
});
};
exports["explicit config.html, with overriden config.url"] = function (t) {
env({
html: "Hello",
url: "http://example.com/",
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<html><head></head><body>Hello</body></html>");
t.equal(window.location.href, "http://example.com/");
t.equal(window.location.origin, "http://example.com");
t.equal(window.location.search, "");
t.equal(window.location.hash, "");
t.done();
}
});
};
exports["explicit config.html, with overriden config.url including hash"] = function (t) {
env({
html: "Hello",
url: "http://example.com/#foo",
done: function (err, window) {
t.ifError(err);
t.equal(window.location.hash, "#foo");
t.done();
}
});
};
exports["explicit config.html, with overriden config.url including search and hash"] = function (t) {
env({
html: "Hello",
url: "http://example.com/?foo=bar#baz",
done: function (err, window) {
t.ifError(err);
t.equal(window.location.search, "?foo=bar");
t.equal(window.location.hash, "#baz");
t.done();
}
});
};
exports["explicit config.html, without a config.url"] = function (t) {
env({
html: "<html><head></head><body><p>hello world!</p></body></html>",
done: function (err, window) {
t.ifError(err);
t.notEqual(window.location.href, null);
t.done();
}
});
};
exports["explicit config.html, with poorly formatted HTML"] = function (t) {
env({
html: "some poorly<div>formed<b>html</div> fragment",
done: function (err, window) {
t.ifError(err);
t.notEqual(window.location.href, null);
t.done();
}
});
};
exports["explicit config.html, a string that is also a valid URL"] = function (t) {
env({
html: "http://example.com/",
url: "http://example.com/",
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<html><head></head><body>http://example.com/</body></html>");
t.equal(window.location.href, "http://example.com/");
t.done();
}
});
};
exports["explicit config.html, a string that is also a valid file"] = function (t) {
var body = path.resolve(__dirname, "files/env.html");
env({
html: body,
url: "http://example.com/",
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<html><head></head><body>" + body + "</body></html>");
t.equal(window.location.href, "http://example.com/");
t.done();
}
});
};
exports["explicit config.url, valid"] = function (t) {
var html = "<html><head><title>Example URL</title></head><body>Example!</body></html>";
var responseText = "<!DOCTYPE html>" + html;
var server = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Length": responseText.length });
res.end(responseText);
server.close();
}).listen(8976);
env({
url: "http://localhost:8976/",
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, responseText);
t.equal(window.location.href, "http://localhost:8976/");
t.equal(window.location.origin, "http://localhost:8976");
t.done();
}
});
};
exports["explicit config.url, invalid"] = function (t) {
env({
url: "http://localhost:8976",
done: function (err, window) {
t.ok(err, 'an error should exist');
t.strictEqual(window, undefined, 'window should not exist');
t.done();
}
});
};
exports["explicit config.file, valid"] = function (t) {
var fileName = path.resolve(__dirname, "files/env.html");
fs.readFile(fileName, 'utf-8', function (err, text) {
t.ifError(err);
env({
file: fileName,
done: function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, text.trim());
t.equal(window.location.href, toFileUrl(fileName));
t.done();
}
});
});
};
exports["explicit config.file, invalid"] = function (t) {
env({
file: "__DOES_NOT_EXIST__",
done: function (err, window) {
t.ok(err, 'an error should exist');
t.strictEqual(window, undefined, 'window should not exist');
t.done();
}
});
};
exports["explicit config.file, with a script"] = function (t) {
env({
file: path.resolve(__dirname, "files/env.html"),
scripts: [path.resolve(__dirname, "../jquery-fixtures/jquery-1.6.2.js")],
done: function (err, window) {
t.ifError(err);
var $ = window.jQuery;
var text = "Let's Rock!";
$("body").text(text);
t.equal($("body").text(), text);
t.done();
}
});
};
exports["explicit config.file, with spaces in the file name"] = function (t) {
var fileName = path.resolve(__dirname, "files/folder space/space.html");
env({
file: fileName,
done: function (err, window) {
t.ifError(err);
t.done();
}
});
};
exports["string, parseable as a URL, valid"] = function (t) {
var html = "<html><head><title>Example URL</title></head><body>Example!</body></html>";
var responseText = "<!DOCTYPE html>" + html;
var server = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Length": responseText.length });
res.end(responseText);
server.close();
}).listen(8976);
env(
"http://localhost:8976/",
function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, responseText);
t.equal(window.location.href, "http://localhost:8976/");
t.equal(window.location.origin, "http://localhost:8976");
t.done();
}
);
};
exports["string, parseable as a URL, invalid"] = function (t) {
env(
"http://localhost:8976",
function (err, window) {
t.ok(err, 'an error should exist');
t.strictEqual(window, undefined, 'window should not exist');
t.done();
}
);
};
exports["string, for an existing filename"] = function (t) {
var fileName = path.resolve(__dirname, "files/env.html");
fs.readFile(fileName, 'utf-8', function (err, text) {
t.ifError(err);
env(
fileName,
function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, text.trim());
t.equal(window.location.href, toFileUrl(fileName));
t.done();
}
);
});
};
exports["string, does not exist as a file"] = function (t) {
var body = "__DOES_NOT_EXIST__";
env(
body,
function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<html><head></head><body>" + body + "</body></html>");
t.done();
}
);
};
exports["string, full HTML document"] = function (t) {
env(
"<!DOCTYPE html><html><head><title>Hi</title></head><body>Hello</body></html>",
function (err, window) {
t.ifError(err);
t.equal(window.document.innerHTML, "<!DOCTYPE html><html><head><title>Hi</title></head><body>Hello</body></html>");
t.done();
}
);
};
exports["with a nonexistant script"] = function (t) {
env({
html: "<!DOCTYPE html><html><head></head><body><p>hello world!</p></body></html>",
scripts: ["path/to/invalid.js", "another/invalid.js"],
done: function (err, window) {
t.ok(err);
t.equal(err.length, 2);
t.ok(window.location.href);
t.done();
}
});
};
exports["with src"] = function (t) {
env({
html: "<!DOCTYPE html><html><head></head><body><p>hello world!</p></body></html>",
src: "window.attachedHere = 123;",
done: function (err, window) {
t.ifError(err);
t.ok(window.location.href);
t.equal(window.attachedHere, 123);
t.equal(window.document.getElementsByTagName("p").item(0).innerHTML, "hello world!");
t.done();
}
});
};
exports["with document referrer"] = function (t) {
env({
html: "<!DOCTYPE html><html><head></head><body><p>hello world!</p></body></html>",
document: { referrer: "https://github.com/tmpvar/jsdom" },
done: function (err, window) {
t.ifError(err);
t.equal(window.document.referrer, "https://github.com/tmpvar/jsdom");
t.done();
}
});
};
exports["with document cookie"] = function (t) {
var time = new Date(Date.now() + 24 * 60 * 60 * 1000);
var cookie = "key=value; expires=" + time.toGMTString() + "; path=/";
env({
html: "<!DOCTYPE html><html><head></head><body><p>hello world!</p></body></html>",
document: { cookie: cookie },
done: function (err, window) {
t.ifError(err);
t.equal(window.document.cookie, "key=value");
t.done();
}
});
};
exports["with scripts and content retrieved from URLs"] = function (t) {
var routes = {
"/js": "window.attachedHere = 123;",
"/html": "<a href='/path/to/hello'>World</a>"
};
var server = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Length": routes[req.url].length });
res.end(routes[req.url]);
});
server.listen(64000, "127.0.0.1", function () {
env({
url: "http://127.0.0.1:64000/html",
scripts: "http://127.0.0.1:64000/js",
done: function (err, window) {
server.close();
t.ifError(err);
t.equal(window.location.href, "http://127.0.0.1:64000/html");
t.equal(window.location.origin, "http://127.0.0.1:64000");
t.equal(window.attachedHere, 123);
t.equal(window.document.getElementsByTagName("a").item(0).innerHTML, "World");
t.done();
}
});
});
};
exports["should call callbacks correctly"] = function (t) {
t.expect(11);
env({
html: "<!DOCTYPE html><html><head><script>window.isExecuted = true;window.wasCreatedSet = window.isCreated;</script></head><body></body></html>",
features: {
FetchExternalResources: ["script"],
ProcessExternalResources: ["script"],
SkipExternalResources: false
},
created: function (err, window) {
t.ifError(err);
t.notEqual(window.isExecuted, true);
t.strictEqual(window.wasCreatedSet, undefined);
window.isCreated = true;
},
loaded: function (err, window) {
t.ifError(err);
t.strictEqual(window.isCreated, true);
t.strictEqual(window.isExecuted, true);
t.strictEqual(window.wasCreatedSet, true);
},
done: function (err, window) {
t.ifError(err);
t.strictEqual(window.isCreated, true);
t.strictEqual(window.isExecuted, true);
t.strictEqual(window.wasCreatedSet, true);
t.done();
}
});
};
| Fix whitespace in expected html
The expected html is actually not the same as what's in the file.
Checked with Chrome to match exactly.
| test/jsdom/env.js | Fix whitespace in expected html | <ide><path>est/jsdom/env.js
<ide> exports["explicit config.file, valid"] = function (t) {
<ide> var fileName = path.resolve(__dirname, "files/env.html");
<ide>
<del> fs.readFile(fileName, 'utf-8', function (err, text) {
<del> t.ifError(err);
<del> env({
<del> file: fileName,
<del> done: function (err, window) {
<del> t.ifError(err);
<del> t.equal(window.document.innerHTML, text.trim());
<del> t.equal(window.location.href, toFileUrl(fileName));
<del> t.done();
<del> }
<del> });
<add> env({
<add> file: fileName,
<add> done: function (err, window) {
<add> t.ifError(err);
<add> t.equal(window.document.innerHTML, '<!DOCTYPE html><html><head>\n\
<add> <title>hello, Node.js!</title>\n\
<add> </head>\n\
<add> <body>\n\
<add> \n\
<add>\n\
<add></body></html>');
<add> t.equal(window.location.href, toFileUrl(fileName));
<add> t.done();
<add> }
<ide> });
<ide> };
<ide>
<ide> exports["string, for an existing filename"] = function (t) {
<ide> var fileName = path.resolve(__dirname, "files/env.html");
<ide>
<del> fs.readFile(fileName, 'utf-8', function (err, text) {
<del> t.ifError(err);
<del> env(
<del> fileName,
<del> function (err, window) {
<del> t.ifError(err);
<del> t.equal(window.document.innerHTML, text.trim());
<del> t.equal(window.location.href, toFileUrl(fileName));
<del> t.done();
<del> }
<del> );
<del> });
<add> env(
<add> fileName,
<add> function (err, window) {
<add> t.ifError(err);
<add> t.equal(window.document.innerHTML, '<!DOCTYPE html><html><head>\n\
<add> <title>hello, Node.js!</title>\n\
<add> </head>\n\
<add> <body>\n\
<add> \n\
<add>\n\
<add></body></html>');
<add> t.equal(window.location.href, toFileUrl(fileName));
<add> t.done();
<add> }
<add> );
<ide> };
<ide>
<ide> exports["string, does not exist as a file"] = function (t) { |
|
JavaScript | bsd-3-clause | fec4be8b386c669df2536e362709908b4021992b | 0 | starshipfactory/membersys,starshipfactory/membersys,starshipfactory/membersys | // Loads the dialog for uploading the membership agreement.
function openUploadAgreement(id, approval_csrf_token, upload_csrf_token) {
var agreementIdField = $('#agreementId')[0];
var agreementCsrfTokenField = $('#agreementCsrfToken')[0];
var agreementUploadCsrfTokenField = $('#agreementUploadCsrfToken')[0];
var agreementForm = $('#agreementForm')[0];
var agreementFile = $('#agreementFile')[0];
$('#agreementUploadError').alert();
if (!$('#agreementUploadError').hasClass('hide'))
$('#agreementUploadError').addClass('hide');
$('#formUploadModal').modal('show');
agreementIdField.value = id;
agreementCsrfTokenField.value = approval_csrf_token;
agreementUploadCsrfTokenField.value = upload_csrf_token;
}
// Displays the size of the agreement file.
function agreementFileSelected() {
var agreementFile = $('#agreementFile')[0].files[0];
var indicator = $('#agreementUploadProgress')[0];
// Clear all child nodes of the upload indicator.
while (indicator.childNodes.length > 0)
indicator.removeChild(indicator.firstChild);
if (agreementFile) {
if (agreementFile.size > 1.5*1048576) {
indicator.appendChild(document.createTextNode(
(Math.round(agreementFile.size * 100 / 1048576) / 100).toString() + ' MB hochzuladen'));
} else {
indicator.appendChild(document.createTextNode(
(Math.round(agreementFile.size * 100 / 1024) / 100).toString() + ' KB hochzuladen'));
}
} else {
indicator.appendChild(document.createTextNode("Keine Datei ausgewählt"));
}
}
// Actually uploads the file.
function doUploadAgreement() {
var agreementForm = $('#agreementForm')[0];
var agreementProgress = $('#agreementUploadProgress')[0];
var agreementFile = $('#agreementFile')[0];
var agreementIdField = $('#agreementId')[0];
var agreementCsrfTokenField = $('#agreementCsrfToken')[0];
var agreementUploadCsrfTokenField = $('#agreementUploadCsrfToken')[0];
var agreementBtn = $('#agreementUploadBtn')[0];
agreementBtn.disabled = "disabled";
var data = new FormData();
$.each(agreementFile.files, function(key, value) {
data.append(key, value);
});
data.append('csrf_token', agreementUploadCsrfTokenField.value);
data.append('uuid', agreementIdField.value);
$.ajax({
url: '/admin/api/agreement-upload',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files.
contentType: false,
success: function(data, textStatus, jqXHR) {
if (typeof data.error === 'undefined') {
acceptMember(agreementIdField.value, agreementCsrfTokenField.value);
} else {
var errorText = $('#agreementErrorText')[0];
while (errorText.childNodes.length > 0)
errorText.removeChild(errorText.firstChild);
errorText.appendChild(document.createTextNode(data.error));
if ($('#agreementUploadError').hasClass('hide'))
$('#agreementUploadError').removeClass('hide');
}
agreementBtn.disabled = null;
},
error: function(jqXHR, textStatus, errorThrown) {
var errorText = $('#agreementErrorText')[0];
while (errorText.childNodes.length > 0)
errorText.removeChild(errorText.firstChild);
errorText.appendChild(document.createTextNode(textStatus + ': ' +
jqXHR.responseText));
if ($('#agreementUploadError').hasClass('hide'))
$('#agreementUploadError').removeClass('hide');
agreementBtn.disabled = null;
}
});
}
// Cancels a queued membership application entry.
function cancelQueued(id, csrf_token) {
new $.ajax({
url: '/admin/api/cancel-queued',
data: {
uuid: id,
csrf_token: csrf_token
},
type: 'POST',
success: function(response) {
var tr = $('#q-' + id);
var tbodies = tr.parent();
for (i = 0; i < tbodies.length; i++)
for (j = 0; j < tbodies[i].childNodes.length; j++)
if (tbodies[i].childNodes[j].id == 'q-' + id)
tbodies[i].removeChild(tbodies[i].childNodes[j]);
}
});
}
// Removes a member from the organization.
function goodbyeMember(id, csrf_token) {
$('#reasonUser')[0].value = id;
$('#reasonCsrfToken')[0].value = csrf_token;
$('#reasonText')[0].value = '';
$('#reasonEnterModal').modal('show');
}
function doGoodbyeMember() {
var id = $('#reasonUser')[0].value;
var csrf_token = $('#reasonCsrfToken')[0].value;
var reason = $('#reasonText')[0].value;
new $.ajax({
url: '/admin/api/goodbye-member',
data: {
id: id,
csrf_token: csrf_token,
reason: reason
},
type: 'POST',
success: function(response) {
var bid = id.replace('@', '_').replace('.', '_');
var tr = $('#mem-' + bid);
var tbodies = tr.parent();
for (i = 0; i < tbodies.length; i++) {
for (j = 0; j < tbodies[i].childNodes.length; j++) {
if (tbodies[i].childNodes[j].id == 'mem-' + bid)
tbodies[i].removeChild(tbodies[i].childNodes[j]);
}
}
$('#reasonUser')[0].value = '';
$('#reasonCsrfToken')[0].value = '';
$('#reasonText')[0].value = '';
$('#reasonEnterModal').modal('hide');
}
});
}
// Accepts the membership request from the member with the given ID.
function acceptMember(id, csrf_token) {
new $.ajax({
url: '/admin/api/accept',
data: {
uuid: id,
csrf_token: csrf_token
},
type: 'POST',
success: function(response) {
var tr = $('#' + id);
var tbodies = tr.parent();
for (i = 0; i < tbodies.length; i++)
for (j = 0; j < tbodies[i].childNodes.length; j++)
if (tbodies[i].childNodes[j].id == id)
tbodies[i].removeChild(tbodies[i].childNodes[j]);
$('#formUploadModal').modal('hide');
$('#agreementCsrfToken')[0].value = '';
$('#agreementUploadCsrfToken')[0].value = '';
$('#agreementForm')[0].reset();
}
});
return true;
}
// Deletes the request from the member with the given ID from the data
// store. This should only be done after the member has been notified
// directly already of the rejection.
function rejectMember(id, csrf_token) {
if (!confirm("Der Antragsteller wird hierdurch nicht von der Ablehnung " +
"informiert! Dies muss bereits im Voraus erfolgen!")) {
return true;
}
new $.ajax({
url: '/admin/api/reject',
data: {
uuid: id,
csrf_token: csrf_token
},
type: 'POST',
success: function(response) {
var tr = $('#' + id);
var tbodies = tr.parent();
for (i = 0; i < tbodies.length; i++)
for (j = 0; j < tbodies[i].childNodes.length; j++)
if (tbodies[i].childNodes[j].id == id)
tbodies[i].removeChild(tbodies[i].childNodes[j]);
}
});
return true;
}
// Use AJAX to load a list of all organization members and populate the
// corresponding table.
function loadMembers(start) {
new $.ajax({
url: '/admin/api/members',
data: {
start: start,
},
type: 'GET',
success: function(response) {
var body = $('#memberlist tbody')[0];
var members = response.members;
var token = response.csrf_token;
var i = 0;
while (body.childNodes.length > 0)
body.removeChild(body.firstChild);
if (members == null || members.length == 0) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.colspan = 7;
td.appendChild(document.createTextNode('Derzeit verfügen wir über keine Mitglieder.'));
tr.appendChild(td);
body.appendChild(tr);
return;
}
for (i = 0; i < members.length; i++) {
var id = members[i].email;
var bid = id.replace('@', '_').replace('.', '_');
var tr = document.createElement('tr');
var td;
var a;
tr.id = bid;
td = document.createElement('td');
td.appendChild(document.createTextNode(members[i].name));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(members[i].street));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(members[i].city));
tr.appendChild(td);
td = document.createElement('td');
if (members[i].username != null)
td.appendChild(document.createTextNode(members[i].username));
else
td.appendChild(document.createTextNode("none"));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(members[i].email));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(
members[i].fee + " CHF pro " +
(members[i].fee_yearly ? "Jahr" : "Monat")
));
tr.appendChild(td);
td = document.createElement('td');
a = document.createElement('a');
a.href = "#";
a.onclick = function(e) {
var tr = e.srcElement.parentNode.parentNode;
var email = tr.childNodes[4].firstChild.data;
goodbyeMember(email, token);
}
a.appendChild(document.createTextNode('Verabschieden'));
td.appendChild(a);
tr.appendChild(td);
body.appendChild(tr);
}
},
});
return true;
}
// Use AJAX to load a list of all membership applications and populate the
// corresponding table.
function loadApplicants(criterion, start) {
new $.ajax({
url: '/admin/api/applicants',
data: {
start: start,
criterion: criterion,
},
type: 'GET',
success: function(response) {
var body = $('#applicantlist tbody')[0];
var applicants = response.applicants;
var approval_token = response.approval_csrf_token;
var rejection_token = response.rejection_csrf_token;
var upload_token = response.agreement_upload_csrf_token;
var i = 0;
while (body.childNodes.length > 0)
body.removeChild(body.firstChild);
if (applicants == null || applicants.length == 0) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.colspan = 5;
td.appendChild(document.createTextNode('Derzeit sind keine Mitgliedsanträge hängig.'));
tr.appendChild(td);
body.appendChild(tr);
return;
}
for (i = 0; i < applicants.length; i++) {
var applicant = applicants[i];
var tr = document.createElement('tr');
var td;
var a;
tr.id = applicant.key;
td = document.createElement('td');
td.appendChild(document.createTextNode(applicant.name));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(applicant.street));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(applicant.city));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(
applicant.fee + " CHF pro " +
(applicant.fee_yearly ? "Jahr" : "Monat")
));
tr.appendChild(td);
td = document.createElement('td');
a = document.createElement('a');
a.href = "#";
a.onclick = function(e) {
var tr = e.srcElement.parentNode.parentNode;
var id = tr.id;
console.log(id + " upload commencing");
openUploadAgreement(id, approval_token, upload_token);
}
a.appendChild(document.createTextNode('Annehmen'));
td.appendChild(a);
td.appendChild(document.createTextNode(' '));
a = document.createElement('a');
a.href = "#";
a.onclick = function(e) {
var tr = e.srcElement.parentNode.parentNode;
var id = tr.id;
rejectMember(id, rejection_token);
}
a.appendChild(document.createTextNode('Ablehnen'));
td.appendChild(a);
tr.appendChild(td);
body.appendChild(tr);
}
},
});
return true;
}
// Register the required functions for switching between the different tabs.
function load() {
$('a[href="#members"]').on('show.bs.tab', function(e) {
loadMembers("");
});
$('a[href="#applicants"]').on('show.bs.tab', function(e) {
loadApplicants("", "");
});
loadMembers("");
return true;
} | html/js/memberlist.js | // Loads the dialog for uploading the membership agreement.
function openUploadAgreement(id, approval_csrf_token, upload_csrf_token) {
var agreementIdField = $('#agreementId')[0];
var agreementCsrfTokenField = $('#agreementCsrfToken')[0];
var agreementUploadCsrfTokenField = $('#agreementUploadCsrfToken')[0];
var agreementForm = $('#agreementForm')[0];
var agreementFile = $('#agreementFile')[0];
$('#agreementUploadError').alert();
if (!$('#agreementUploadError').hasClass('hide'))
$('#agreementUploadError').addClass('hide');
$('#formUploadModal').modal('show');
agreementIdField.value = id;
agreementCsrfTokenField.value = approval_csrf_token;
agreementUploadCsrfTokenField.value = upload_csrf_token;
}
// Displays the size of the agreement file.
function agreementFileSelected() {
var agreementFile = $('#agreementFile')[0].files[0];
var indicator = $('#agreementUploadProgress')[0];
// Clear all child nodes of the upload indicator.
while (indicator.childNodes.length > 0)
indicator.removeChild(indicator.firstChild);
if (agreementFile) {
if (agreementFile.size > 1.5*1048576) {
indicator.appendChild(document.createTextNode(
(Math.round(agreementFile.size * 100 / 1048576) / 100).toString() + ' MB hochzuladen'));
} else {
indicator.appendChild(document.createTextNode(
(Math.round(agreementFile.size * 100 / 1024) / 100).toString() + ' KB hochzuladen'));
}
} else {
indicator.appendChild(document.createTextNode("Keine Datei ausgewählt"));
}
}
// Actually uploads the file.
function doUploadAgreement() {
var agreementForm = $('#agreementForm')[0];
var agreementProgress = $('#agreementUploadProgress')[0];
var agreementFile = $('#agreementFile')[0];
var agreementIdField = $('#agreementId')[0];
var agreementCsrfTokenField = $('#agreementCsrfToken')[0];
var agreementUploadCsrfTokenField = $('#agreementUploadCsrfToken')[0];
var agreementBtn = $('#agreementUploadBtn')[0];
agreementBtn.disabled = "disabled";
var data = new FormData();
$.each(agreementFile.files, function(key, value) {
data.append(key, value);
});
data.append('csrf_token', agreementUploadCsrfTokenField.value);
data.append('uuid', agreementIdField.value);
$.ajax({
url: '/admin/api/agreement-upload',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files.
contentType: false,
success: function(data, textStatus, jqXHR) {
if (typeof data.error === 'undefined') {
acceptMember(agreementIdField.value, agreementCsrfTokenField.value);
} else {
var errorText = $('#agreementErrorText')[0];
while (errorText.childNodes.length > 0)
errorText.removeChild(errorText.firstChild);
errorText.appendChild(document.createTextNode(data.error));
if ($('#agreementUploadError').hasClass('hide'))
$('#agreementUploadError').removeClass('hide');
}
agreementBtn.disabled = null;
},
error: function(jqXHR, textStatus, errorThrown) {
var errorText = $('#agreementErrorText')[0];
while (errorText.childNodes.length > 0)
errorText.removeChild(errorText.firstChild);
errorText.appendChild(document.createTextNode(textStatus + ': ' +
jqXHR.responseText));
if ($('#agreementUploadError').hasClass('hide'))
$('#agreementUploadError').removeClass('hide');
agreementBtn.disabled = null;
}
});
}
// Cancels a queued membership application entry.
function cancelQueued(id, csrf_token) {
new $.ajax({
url: '/admin/api/cancel-queued',
data: {
uuid: id,
csrf_token: csrf_token
},
type: 'POST',
success: function(response) {
var tr = $('#q-' + id);
var tbodies = tr.parent();
for (i = 0; i < tbodies.length; i++)
for (j = 0; j < tbodies[i].childNodes.length; j++)
if (tbodies[i].childNodes[j].id == 'q-' + id)
tbodies[i].removeChild(tbodies[i].childNodes[j]);
}
});
}
// Removes a member from the organization.
function goodbyeMember(id, csrf_token) {
$('#reasonUser')[0].value = id;
$('#reasonCsrfToken')[0].value = csrf_token;
$('#reasonText')[0].value = '';
$('#reasonEnterModal').modal('show');
}
function doGoodbyeMember() {
var id = $('#reasonUser')[0].value;
var csrf_token = $('#reasonCsrfToken')[0].value;
var reason = $('#reasonText')[0].value;
new $.ajax({
url: '/admin/api/goodbye-member',
data: {
id: id,
csrf_token: csrf_token,
reason: reason
},
type: 'POST',
success: function(response) {
var bid = id.replace('@', '_').replace('.', '_');
var tr = $('#mem-' + bid);
var tbodies = tr.parent();
for (i = 0; i < tbodies.length; i++) {
for (j = 0; j < tbodies[i].childNodes.length; j++) {
if (tbodies[i].childNodes[j].id == 'mem-' + bid)
tbodies[i].removeChild(tbodies[i].childNodes[j]);
}
}
$('#reasonUser')[0].value = '';
$('#reasonCsrfToken')[0].value = '';
$('#reasonText')[0].value = '';
$('#reasonEnterModal').modal('hide');
}
});
}
// Accepts the membership request from the member with the given ID.
function acceptMember(id, csrf_token) {
new $.ajax({
url: '/admin/api/accept',
data: {
uuid: id,
csrf_token: csrf_token
},
type: 'POST',
success: function(response) {
var tr = $('#' + id);
var tbodies = tr.parent();
for (i = 0; i < tbodies.length; i++)
for (j = 0; j < tbodies[i].childNodes.length; j++)
if (tbodies[i].childNodes[j].id == id)
tbodies[i].removeChild(tbodies[i].childNodes[j]);
$('#formUploadModal').modal('hide');
$('#agreementCsrfToken')[0].value = '';
$('#agreementUploadCsrfToken')[0].value = '';
$('#agreementForm')[0].reset();
}
});
return true;
}
// Deletes the request from the member with the given ID from the data
// store. This should only be done after the member has been notified
// directly already of the rejection.
function rejectMember(id, csrf_token) {
if (!confirm("Der Antragsteller wird hierdurch nicht von der Ablehnung " +
"informiert! Dies muss bereits im Voraus erfolgen!")) {
return true;
}
new $.ajax({
url: '/admin/api/reject',
data: {
uuid: id,
csrf_token: csrf_token
},
type: 'POST',
success: function(response) {
var tr = $('#' + id);
var tbodies = tr.parent();
for (i = 0; i < tbodies.length; i++)
for (j = 0; j < tbodies[i].childNodes.length; j++)
if (tbodies[i].childNodes[j].id == id)
tbodies[i].removeChild(tbodies[i].childNodes[j]);
}
});
return true;
}
// Use AJAX to load a list of all organization members and populate the
// corresponding table.
function loadMembers(start) {
new $.ajax({
url: '/admin/api/members',
data: {
start: start,
},
type: 'GET',
success: function(response) {
var body = $('#memberlist tbody')[0];
var members = response.members;
var token = response.csrf_token;
var i = 0;
while (body.childNodes.length > 0)
body.removeChild(body.firstChild);
if (members == null || members.length == 0) {
var tr = document.createElement('tr');
tr.colspan = 7;
tr.appendChild(document.createTextNode('Derzeit verfügen wir über keine Mitglieder.'));
return;
}
for (i = 0; i < members.length; i++) {
var id = members[i].email;
var bid = id.replace('@', '_').replace('.', '_');
var tr = document.createElement('tr');
var td;
var a;
tr.id = bid;
td = document.createElement('td');
td.appendChild(document.createTextNode(members[i].name));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(members[i].street));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(members[i].city));
tr.appendChild(td);
td = document.createElement('td');
if (members[i].username != null)
td.appendChild(document.createTextNode(members[i].username));
else
td.appendChild(document.createTextNode("none"));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(members[i].email));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(
members[i].fee + " CHF pro " +
(members[i].fee_yearly ? "Jahr" : "Monat")
));
tr.appendChild(td);
td = document.createElement('td');
a = document.createElement('a');
a.href = "#";
a.onclick = function(e) {
var tr = e.srcElement.parentNode.parentNode;
var email = tr.childNodes[4].firstChild.data;
goodbyeMember(email, token);
}
a.appendChild(document.createTextNode('Verabschieden'));
td.appendChild(a);
tr.appendChild(td);
body.appendChild(tr);
}
},
});
return true;
}
// Use AJAX to load a list of all membership applications and populate the
// corresponding table.
function loadApplicants(criterion, start) {
new $.ajax({
url: '/admin/api/applicants',
data: {
start: start,
criterion: criterion,
},
type: 'GET',
success: function(response) {
var body = $('#applicantlist tbody')[0];
var applicants = response.applicants;
var approval_token = response.approval_csrf_token;
var rejection_token = response.rejection_csrf_token;
var upload_token = response.agreement_upload_csrf_token;
var i = 0;
while (body.childNodes.length > 0)
body.removeChild(body.firstChild);
if (applicants == null || applicants.length == 0) {
var tr = document.createElement('tr');
tr.colspan = 5;
tr.appendChild(document.createTextNode('Derzeit verfügen wir über keine Mitglieder.'));
return;
}
for (i = 0; i < applicants.length; i++) {
var applicant = applicants[i];
var tr = document.createElement('tr');
var td;
var a;
tr.id = applicant.key;
td = document.createElement('td');
td.appendChild(document.createTextNode(applicant.name));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(applicant.street));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(applicant.city));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(
applicant.fee + " CHF pro " +
(applicant.fee_yearly ? "Jahr" : "Monat")
));
tr.appendChild(td);
td = document.createElement('td');
a = document.createElement('a');
a.href = "#";
a.onclick = function(e) {
var tr = e.srcElement.parentNode.parentNode;
var id = tr.id;
console.log(id + " upload commencing");
openUploadAgreement(id, approval_token, upload_token);
}
a.appendChild(document.createTextNode('Annehmen'));
td.appendChild(a);
td.appendChild(document.createTextNode(' '));
a = document.createElement('a');
a.href = "#";
a.onclick = function(e) {
var tr = e.srcElement.parentNode.parentNode;
var id = tr.id;
rejectMember(id, rejection_token);
}
a.appendChild(document.createTextNode('Ablehnen'));
td.appendChild(a);
tr.appendChild(td);
body.appendChild(tr);
}
},
});
return true;
}
// Register the required functions for switching between the different tabs.
function load() {
$('a[href="#members"]').on('show.bs.tab', function(e) {
loadMembers("");
});
$('a[href="#applicants"]').on('show.bs.tab', function(e) {
loadApplicants("", "");
});
loadMembers("");
return true;
} | Fix the indications when there are no members or applicants.
| html/js/memberlist.js | Fix the indications when there are no members or applicants. | <ide><path>tml/js/memberlist.js
<ide>
<ide> if (members == null || members.length == 0) {
<ide> var tr = document.createElement('tr');
<del> tr.colspan = 7;
<del> tr.appendChild(document.createTextNode('Derzeit verfügen wir über keine Mitglieder.'));
<add> var td = document.createElement('td');
<add> td.colspan = 7;
<add> td.appendChild(document.createTextNode('Derzeit verfügen wir über keine Mitglieder.'));
<add> tr.appendChild(td);
<add> body.appendChild(tr);
<ide> return;
<ide> }
<ide>
<ide>
<ide> if (applicants == null || applicants.length == 0) {
<ide> var tr = document.createElement('tr');
<del> tr.colspan = 5;
<del> tr.appendChild(document.createTextNode('Derzeit verfügen wir über keine Mitglieder.'));
<add> var td = document.createElement('td');
<add> td.colspan = 5;
<add> td.appendChild(document.createTextNode('Derzeit sind keine Mitgliedsanträge hängig.'));
<add> tr.appendChild(td);
<add> body.appendChild(tr);
<ide> return;
<ide> }
<ide> |
|
Java | mit | error: pathspec 'EclipseProject/RobotCasserole2017/src/org/usfirst/frc/team1736/robot/VisionAlignAnglePID.java' did not match any file(s) known to git
| 58d9d3b5ecb781904db04a9679b49691f6beb4a9 | 1 | RobotCasserole1736/RobotCasserole2017,RobotCasserole1736/RobotCasserole2017,RobotCasserole1736/RobotCasserole2017,RobotCasserole1736/RobotCasserole2017,RobotCasserole1736/RobotCasserole2017,RobotCasserole1736/RobotCasserole2017 | package org.usfirst.frc.team1736.robot;
import org.usfirst.frc.team1736.lib.CasserolePID.CasserolePID;;
public class VisionAlignAnglePID extends CasserolePID {
VisionAlignAnglePID(double Kp_in, double Ki_in, double Kd_in) {
super(Kp_in, Ki_in, Kd_in);
// TODO Auto-generated constructor stub
}
public void setAngle(double angle){
if(angle == 0.0){
resetIntegrators();
}
setSetpoint(angle);
}
@Override
protected double returnPIDInput() {
// TODO Auto-generated method stub
return RobotState.visionTargetOffset_deg;
}
@Override
protected void usePIDOutput(double pidOutput) {
// TODO Auto-generated method stub
RobotState.visionDtRotateCmd = pidOutput;
}
}
| EclipseProject/RobotCasserole2017/src/org/usfirst/frc/team1736/robot/VisionAlignAnglePID.java | First Pass at vision alignment system
| EclipseProject/RobotCasserole2017/src/org/usfirst/frc/team1736/robot/VisionAlignAnglePID.java | First Pass at vision alignment system | <ide><path>clipseProject/RobotCasserole2017/src/org/usfirst/frc/team1736/robot/VisionAlignAnglePID.java
<add>package org.usfirst.frc.team1736.robot;
<add>
<add>import org.usfirst.frc.team1736.lib.CasserolePID.CasserolePID;;
<add>
<add>public class VisionAlignAnglePID extends CasserolePID {
<add>
<add> VisionAlignAnglePID(double Kp_in, double Ki_in, double Kd_in) {
<add> super(Kp_in, Ki_in, Kd_in);
<add> // TODO Auto-generated constructor stub
<add> }
<add>
<add> public void setAngle(double angle){
<add> if(angle == 0.0){
<add> resetIntegrators();
<add> }
<add>
<add> setSetpoint(angle);
<add> }
<add>
<add> @Override
<add> protected double returnPIDInput() {
<add> // TODO Auto-generated method stub
<add> return RobotState.visionTargetOffset_deg;
<add> }
<add>
<add> @Override
<add> protected void usePIDOutput(double pidOutput) {
<add> // TODO Auto-generated method stub
<add> RobotState.visionDtRotateCmd = pidOutput;
<add> }
<add>
<add>} |
|
Java | apache-2.0 | 46dbbdbcb8646999b35acce0942ca4afc1d8e422 | 0 | rasika/carbon-device-mgt,wso2/carbon-device-mgt,charithag/carbon-device-mgt,geethkokila/carbon-device-mgt,hasuniea/carbon-device-mgt,geethkokila/carbon-device-mgt,dilee/carbon-device-mgt,ruwany/carbon-device-mgt,rasika90/carbon-device-mgt,wso2/carbon-device-mgt,ruwany/carbon-device-mgt,dilee/carbon-device-mgt,dilee/carbon-device-mgt,charithag/carbon-device-mgt,madawas/carbon-device-mgt,madhawap/carbon-device-mgt,rasika90/carbon-device-mgt,madawas/carbon-device-mgt,ruwany/carbon-device-mgt,hasuniea/carbon-device-mgt,madhawap/carbon-device-mgt,rasika/carbon-device-mgt,hasuniea/carbon-device-mgt,rasika/carbon-device-mgt,charithag/carbon-device-mgt,madawas/carbon-device-mgt,rasika90/carbon-device-mgt,wso2/carbon-device-mgt,madhawap/carbon-device-mgt,geethkokila/carbon-device-mgt | /*
* Copyright (c) 2018, 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.device.mgt.common.geo.service;
/**
* Custom exception class for geo alert definition operations.
*/
public class AlertAlreadyExist extends Exception {
private static final long serialVersionUID = 4709355511911265093L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public AlertAlreadyExist(String msg) {
super(msg);
setErrorMessage(msg);
}
} | components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/AlertAlreadyExist.java | /*
* Copyright (c) 2017, 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.device.mgt.common.geo.service;
/**
* Custom exception class for geo alert definition operations.
*/
public class AlertAlreadyExist extends Exception {
private static final long serialVersionUID = 4709355511911265093L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public AlertAlreadyExist(String msg) {
super(msg);
setErrorMessage(msg);
}
} | Year change in license details
| components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/AlertAlreadyExist.java | Year change in license details | <ide><path>omponents/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/AlertAlreadyExist.java
<ide> /*
<del> * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
<add> * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
<ide> *
<ide> * WSO2 Inc. licenses this file to you under the Apache License,
<ide> * Version 2.0 (the "License"); you may not use this file except |
|
Java | apache-2.0 | b455cafb3d9c70a5ad8598a2f0e7a9d6eee5e83c | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.log;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
/**
* @author arnej
*
* This class takes care of saving meta-data about a log-file,
* ensuring that we can enact policies about log retention.
**/
public class LogFileDb {
static final String DBDIR = "var/db/vespa/logfiledb/";
private static long dayStamp() {
long s = System.currentTimeMillis() / 1000;
return s / 100000;
}
private static OutputStream metaFile() throws java.io.IOException {
String fn = getDefaults().underVespaHome(DBDIR + "logfiles." + dayStamp());
File dir = new File(fn).getParentFile();
try {
Files.createDirectories(dir.toPath());
} catch (IOException e) {
System.err.println("Failed creating logfiledb directory '" + dir.getPath() + "': " + e.getMessage());
}
Path path = Paths.get(fn);
return Files.newOutputStream(path, CREATE, APPEND);
}
public static boolean nowLoggingTo(String filename) {
if (filename.contains("\n")) {
throw new IllegalArgumentException("Cannot use filename with newline: "+filename);
}
long s = System.currentTimeMillis() / 1000;
String meta = "" + s + " " + filename + "\n";
byte[] data = meta.getBytes(UTF_8);
try (OutputStream out = metaFile()) {
out.write(data);
} catch (java.io.IOException e) {
System.err.println("Saving meta-data about logfile "+filename+" failed: "+e);
return false;
}
return true;
}
}
| vespalog/src/main/java/com/yahoo/log/LogFileDb.java | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.log;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
/**
* @author arnej
*
* This class takes care of saving meta-data about a log-file,
* ensuring that we can enact policies about log retention.
**/
public class LogFileDb {
static final String DBDIR = "var/db/vespa/logfiledb/";
private static long dayStamp() {
long s = System.currentTimeMillis() / 1000;
return s / 100000;
}
private static OutputStream metaFile() throws java.io.IOException {
String fn = getDefaults().underVespaHome(DBDIR + "logfiles." + dayStamp());
File dir = new File(fn).getParentFile();
if (!dir.exists()) {
if (!dir.mkdirs()) {
System.err.println("Failed creating logfiledb directory '" + dir.getPath() + "'.");
}
}
Path path = Paths.get(fn);
return Files.newOutputStream(path, CREATE, APPEND);
}
public static boolean nowLoggingTo(String filename) {
if (filename.contains("\n")) {
throw new IllegalArgumentException("Cannot use filename with newline: "+filename);
}
long s = System.currentTimeMillis() / 1000;
String meta = "" + s + " " + filename + "\n";
byte[] data = meta.getBytes(UTF_8);
try (OutputStream out = metaFile()) {
out.write(data);
} catch (java.io.IOException e) {
System.err.println("Saving meta-data about logfile "+filename+" failed: "+e);
return false;
}
return true;
}
}
| Try to avoid race when creating directory
If e.g. several containers try to create this directory at the same time
there will be unnecessary warnings in log
| vespalog/src/main/java/com/yahoo/log/LogFileDb.java | Try to avoid race when creating directory | <ide><path>espalog/src/main/java/com/yahoo/log/LogFileDb.java
<del>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
<add>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
<ide> package com.yahoo.log;
<ide>
<ide> import static java.nio.charset.StandardCharsets.UTF_8;
<ide> import static java.nio.file.StandardOpenOption.CREATE;
<ide>
<ide> import java.io.File;
<add>import java.io.IOException;
<ide> import java.io.OutputStream;
<ide> import java.nio.file.Files;
<ide> import java.nio.file.Path;
<ide> private static OutputStream metaFile() throws java.io.IOException {
<ide> String fn = getDefaults().underVespaHome(DBDIR + "logfiles." + dayStamp());
<ide> File dir = new File(fn).getParentFile();
<del> if (!dir.exists()) {
<del> if (!dir.mkdirs()) {
<del> System.err.println("Failed creating logfiledb directory '" + dir.getPath() + "'.");
<del> }
<add> try {
<add> Files.createDirectories(dir.toPath());
<add> } catch (IOException e) {
<add> System.err.println("Failed creating logfiledb directory '" + dir.getPath() + "': " + e.getMessage());
<ide> }
<ide> Path path = Paths.get(fn);
<ide> return Files.newOutputStream(path, CREATE, APPEND); |
|
Java | apache-2.0 | e5a04573728a53fce02ac90e8c3df5ae288fd79a | 0 | WANdisco/gerrit,MerritCR/merrit,qtproject/qtqa-gerrit,MerritCR/merrit,joshuawilson/merrit,gerrit-review/gerrit,joshuawilson/merrit,joshuawilson/merrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,MerritCR/merrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,joshuawilson/merrit,MerritCR/merrit,MerritCR/merrit,gerrit-review/gerrit,WANdisco/gerrit,gerrit-review/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,joshuawilson/merrit,qtproject/qtqa-gerrit,WANdisco/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,MerritCR/merrit,gerrit-review/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,MerritCR/merrit,MerritCR/merrit,joshuawilson/merrit,WANdisco/gerrit,joshuawilson/merrit,joshuawilson/merrit,GerritCodeReview/gerrit,gerrit-review/gerrit,WANdisco/gerrit | // Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.info;
import com.google.gerrit.client.rpc.NativeMap;
import com.google.gerrit.client.rpc.NativeString;
import com.google.gerrit.client.rpc.Natives;
import com.google.gerrit.common.data.LabelValue;
import com.google.gerrit.common.data.SubmitRecord;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwtjsonrpc.client.impl.ser.JavaSqlTimestamp_JsonSerializer;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public class ChangeInfo extends JavaScriptObject {
public final void init() {
if (allLabels() != null) {
allLabels().copyKeysIntoChildren("_name");
}
}
public final Project.NameKey projectNameKey() {
return new Project.NameKey(project());
}
public final Change.Id legacyId() {
return new Change.Id(_number());
}
public final Timestamp created() {
Timestamp ts = _getCts();
if (ts == null) {
ts = JavaSqlTimestamp_JsonSerializer.parseTimestamp(createdRaw());
_setCts(ts);
}
return ts;
}
public final boolean hasEditBasedOnCurrentPatchSet() {
JsArray<RevisionInfo> revList = revisions().values();
RevisionInfo.sortRevisionInfoByNumber(revList);
return revList.get(revList.length() - 1).isEdit();
}
private final native Timestamp _getCts() /*-{ return this._cts; }-*/;
private final native void _setCts(Timestamp ts) /*-{ this._cts = ts; }-*/;
public final Timestamp updated() {
return JavaSqlTimestamp_JsonSerializer.parseTimestamp(updatedRaw());
}
public final String idAbbreviated() {
return new Change.Key(changeId()).abbreviate();
}
public final Change.Status status() {
return Change.Status.valueOf(statusRaw());
}
public final Set<String> labels() {
return allLabels().keySet();
}
public final Set<Integer> removableReviewerIds() {
Set<Integer> removable = new HashSet<>();
if (removableReviewers() != null) {
for (AccountInfo a : Natives.asList(removableReviewers())) {
removable.add(a._accountId());
}
}
return removable;
}
public final native String id() /*-{ return this.id; }-*/;
public final native String project() /*-{ return this.project; }-*/;
public final native String branch() /*-{ return this.branch; }-*/;
public final native String topic() /*-{ return this.topic; }-*/;
public final native String changeId() /*-{ return this.change_id; }-*/;
public final native boolean mergeable() /*-{ return this.mergeable ? true : false; }-*/;
public final native int insertions() /*-{ return this.insertions; }-*/;
public final native int deletions() /*-{ return this.deletions; }-*/;
private final native String statusRaw() /*-{ return this.status; }-*/;
public final native String subject() /*-{ return this.subject; }-*/;
public final native AccountInfo owner() /*-{ return this.owner; }-*/;
private final native String createdRaw() /*-{ return this.created; }-*/;
private final native String updatedRaw() /*-{ return this.updated; }-*/;
public final native boolean starred() /*-{ return this.starred ? true : false; }-*/;
public final native boolean reviewed() /*-{ return this.reviewed ? true : false; }-*/;
public final native NativeMap<LabelInfo> allLabels() /*-{ return this.labels; }-*/;
public final native LabelInfo label(String n) /*-{ return this.labels[n]; }-*/;
public final native String currentRevision() /*-{ return this.current_revision; }-*/;
public final native void setCurrentRevision(String r) /*-{ this.current_revision = r; }-*/;
public final native NativeMap<RevisionInfo> revisions() /*-{ return this.revisions; }-*/;
public final native RevisionInfo revision(String n) /*-{ return this.revisions[n]; }-*/;
public final native JsArray<MessageInfo> messages() /*-{ return this.messages; }-*/;
public final native void setEdit(EditInfo edit) /*-{ this.edit = edit; }-*/;
public final native EditInfo edit() /*-{ return this.edit; }-*/;
public final native boolean hasEdit() /*-{ return this.hasOwnProperty('edit') }-*/;
public final native JsArrayString hashtags() /*-{ return this.hashtags; }-*/;
public final native boolean hasPermittedLabels()
/*-{ return this.hasOwnProperty('permitted_labels') }-*/;
public final native NativeMap<JsArrayString> permittedLabels()
/*-{ return this.permitted_labels; }-*/;
public final native JsArrayString permittedValues(String n)
/*-{ return this.permitted_labels[n]; }-*/;
public final native JsArray<AccountInfo> removableReviewers()
/*-{ return this.removable_reviewers; }-*/;
public final native boolean hasActions() /*-{ return this.hasOwnProperty('actions') }-*/;
public final native NativeMap<ActionInfo> actions() /*-{ return this.actions; }-*/;
public final native int _number() /*-{ return this._number; }-*/;
public final native boolean _more_changes()
/*-{ return this._more_changes ? true : false; }-*/;
public final boolean submittable() {
init();
return _submittable();
}
private final native boolean _submittable()
/*-{ return this.submittable ? true : false; }-*/;
/**
* @return the index of the missing label or -1
* if no label is missing, or if more than one label is missing.
*/
public final int getMissingLabelIndex() {
int i = -1;
int ret = -1;
List<LabelInfo> labels = Natives.asList(allLabels().values());
for (LabelInfo label : labels) {
i++;
if (!permittedLabels().containsKey(label.name())) {
continue;
}
JsArrayString values = permittedValues(label.name());
if (values.length() == 0) {
continue;
}
switch (label.status()) {
case NEED: // Label is required for submit.
if (ret != -1) {
// more than one label is missing, so it's unclear which to quick
// approve, return -1
return -1;
} else {
ret = i;
}
continue;
case OK: // Label already applied.
case MAY: // Label is not required.
continue;
case REJECT: // Submit cannot happen, do not quick approve.
case IMPOSSIBLE:
return -1;
}
}
return ret;
}
protected ChangeInfo() {
}
public static class LabelInfo extends JavaScriptObject {
public final SubmitRecord.Label.Status status() {
if (approved() != null) {
return SubmitRecord.Label.Status.OK;
} else if (rejected() != null) {
return SubmitRecord.Label.Status.REJECT;
} else if (optional()) {
return SubmitRecord.Label.Status.MAY;
} else {
return SubmitRecord.Label.Status.NEED;
}
}
public final native String name() /*-{ return this._name; }-*/;
public final native AccountInfo approved() /*-{ return this.approved; }-*/;
public final native AccountInfo rejected() /*-{ return this.rejected; }-*/;
public final native AccountInfo recommended() /*-{ return this.recommended; }-*/;
public final native AccountInfo disliked() /*-{ return this.disliked; }-*/;
public final native JsArray<ApprovalInfo> all() /*-{ return this.all; }-*/;
public final ApprovalInfo forUser(int user) {
JsArray<ApprovalInfo> all = all();
for (int i = 0; all != null && i < all.length(); i++) {
if (all.get(i)._accountId() == user) {
return all.get(i);
}
}
return null;
}
private final native NativeMap<NativeString> _values() /*-{ return this.values; }-*/;
public final Set<String> values() {
return Natives.keys(_values());
}
public final native String valueText(String n) /*-{ return this.values[n]; }-*/;
public final native boolean optional() /*-{ return this.optional ? true : false; }-*/;
public final native boolean blocking() /*-{ return this.blocking ? true : false; }-*/;
public final native short defaultValue() /*-{ return this.default_value; }-*/;
public final native short _value()
/*-{
if (this.value) return this.value;
if (this.disliked) return -1;
if (this.recommended) return 1;
return 0;
}-*/;
public final String maxValue() {
return LabelValue.formatValue(valueSet().last());
}
public final SortedSet<Short> valueSet() {
SortedSet<Short> values = new TreeSet<>();
for (String v : values()) {
values.add(parseValue(v));
}
return values;
}
public static final short parseValue(String formatted) {
if (formatted.startsWith("+")) {
formatted = formatted.substring(1);
} else if (formatted.startsWith(" ")) {
formatted = formatted.trim();
}
return Short.parseShort(formatted);
}
protected LabelInfo() {
}
}
public static class ApprovalInfo extends AccountInfo {
public final native boolean hasValue() /*-{ return this.hasOwnProperty('value'); }-*/;
public final native short value() /*-{ return this.value || 0; }-*/;
protected ApprovalInfo() {
}
}
public static class EditInfo extends JavaScriptObject {
public final native String name() /*-{ return this.name; }-*/;
public final native String setName(String n) /*-{ this.name = n; }-*/;
public final native String baseRevision() /*-{ return this.base_revision; }-*/;
public final native CommitInfo commit() /*-{ return this.commit; }-*/;
public final native boolean hasActions() /*-{ return this.hasOwnProperty('actions') }-*/;
public final native NativeMap<ActionInfo> actions() /*-{ return this.actions; }-*/;
public final native boolean hasFetch() /*-{ return this.hasOwnProperty('fetch') }-*/;
public final native NativeMap<FetchInfo> fetch() /*-{ return this.fetch; }-*/;
public final native boolean hasFiles() /*-{ return this.hasOwnProperty('files') }-*/;
public final native NativeMap<FileInfo> files() /*-{ return this.files; }-*/;
protected EditInfo() {
}
}
public static class RevisionInfo extends JavaScriptObject {
public static RevisionInfo fromEdit(EditInfo edit) {
RevisionInfo revisionInfo = createObject().cast();
revisionInfo.takeFromEdit(edit);
return revisionInfo;
}
private final native void takeFromEdit(EditInfo edit) /*-{
this._number = 0;
this.name = edit.name;
this.commit = edit.commit;
this.edit_base = edit.base_revision;
}-*/;
public final native int _number() /*-{ return this._number; }-*/;
public final native String name() /*-{ return this.name; }-*/;
public final native boolean draft() /*-{ return this.draft || false; }-*/;
public final native AccountInfo uploader() /*-{ return this.uploader; }-*/;
public final native boolean isEdit() /*-{ return this._number == 0; }-*/;
public final native CommitInfo commit() /*-{ return this.commit; }-*/;
public final native void setCommit(CommitInfo c) /*-{ this.commit = c; }-*/;
public final native String editBase() /*-{ return this.edit_base; }-*/;
public final native boolean hasFiles() /*-{ return this.hasOwnProperty('files') }-*/;
public final native NativeMap<FileInfo> files() /*-{ return this.files; }-*/;
public final native boolean hasActions() /*-{ return this.hasOwnProperty('actions') }-*/;
public final native NativeMap<ActionInfo> actions() /*-{ return this.actions; }-*/;
public final native boolean hasFetch() /*-{ return this.hasOwnProperty('fetch') }-*/;
public final native NativeMap<FetchInfo> fetch() /*-{ return this.fetch; }-*/;
public final native boolean hasPushCertificate() /*-{ return this.hasOwnProperty('push_certificate'); }-*/;
public final native PushCertificateInfo pushCertificate() /*-{ return this.push_certificate; }-*/;
public static void sortRevisionInfoByNumber(JsArray<RevisionInfo> list) {
final int editParent = findEditParent(list);
Collections.sort(Natives.asList(list), new Comparator<RevisionInfo>() {
@Override
public int compare(RevisionInfo a, RevisionInfo b) {
return num(a) - num(b);
}
private int num(RevisionInfo r) {
return !r.isEdit() ? 2 * (r._number() - 1) + 1 : 2 * editParent;
}
});
}
public static int findEditParent(JsArray<RevisionInfo> list) {
RevisionInfo r = findEditParentRevision(list);
return r == null ? -1 : r._number();
}
public static RevisionInfo findEditParentRevision(
JsArray<RevisionInfo> list) {
for (int i = 0; i < list.length(); i++) {
// edit under revisions?
RevisionInfo editInfo = list.get(i);
if (editInfo.isEdit()) {
String parentRevision = editInfo.editBase();
// find parent
for (int j = 0; j < list.length(); j++) {
RevisionInfo parentInfo = list.get(j);
String name = parentInfo.name();
if (name.equals(parentRevision)) {
// found parent pacth set number
return parentInfo;
}
}
}
}
return null;
}
public final String id() {
return PatchSet.Id.toId(_number());
}
protected RevisionInfo () {
}
}
public static class FetchInfo extends JavaScriptObject {
public final native String url() /*-{ return this.url }-*/;
public final native String ref() /*-{ return this.ref }-*/;
public final native NativeMap<NativeString> commands() /*-{ return this.commands }-*/;
public final native String command(String n) /*-{ return this.commands[n]; }-*/;
protected FetchInfo () {
}
}
public static class CommitInfo extends JavaScriptObject {
public final native String commit() /*-{ return this.commit; }-*/;
public final native JsArray<CommitInfo> parents() /*-{ return this.parents; }-*/;
public final native GitPerson author() /*-{ return this.author; }-*/;
public final native GitPerson committer() /*-{ return this.committer; }-*/;
public final native String subject() /*-{ return this.subject; }-*/;
public final native String message() /*-{ return this.message; }-*/;
public final native JsArray<WebLinkInfo> webLinks() /*-{ return this.web_links; }-*/;
protected CommitInfo() {
}
}
public static class GitPerson extends JavaScriptObject {
public final native String name() /*-{ return this.name; }-*/;
public final native String email() /*-{ return this.email; }-*/;
private final native String dateRaw() /*-{ return this.date; }-*/;
public final Timestamp date() {
return JavaSqlTimestamp_JsonSerializer.parseTimestamp(dateRaw());
}
protected GitPerson() {
}
}
public static class MessageInfo extends JavaScriptObject {
public final native AccountInfo author() /*-{ return this.author; }-*/;
public final native String message() /*-{ return this.message; }-*/;
public final native int _revisionNumber() /*-{ return this._revision_number || 0; }-*/;
private final native String dateRaw() /*-{ return this.date; }-*/;
public final Timestamp date() {
return JavaSqlTimestamp_JsonSerializer.parseTimestamp(dateRaw());
}
protected MessageInfo() {
}
}
public static class MergeableInfo extends JavaScriptObject {
public final native String submitType() /*-{ return this.submit_type }-*/;
public final native boolean mergeable() /*-{ return this.mergeable }-*/;
protected MergeableInfo() {
}
}
public static class IncludedInInfo extends JavaScriptObject {
public final Set<String> externalNames() {
return Natives.keys(external());
}
public final native JsArrayString branches() /*-{ return this.branches; }-*/;
public final native JsArrayString tags() /*-{ return this.tags; }-*/;
public final native JsArrayString external(String n) /*-{ return this.external[n]; }-*/;
private final native NativeMap<JsArrayString> external() /*-{ return this.external; }-*/;
protected IncludedInInfo() {
}
}
}
| gerrit-gwtui-common/src/main/java/com/google/gerrit/client/info/ChangeInfo.java | // Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.info;
import com.google.gerrit.client.rpc.NativeMap;
import com.google.gerrit.client.rpc.NativeString;
import com.google.gerrit.client.rpc.Natives;
import com.google.gerrit.common.data.LabelValue;
import com.google.gerrit.common.data.SubmitRecord;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwtjsonrpc.client.impl.ser.JavaSqlTimestamp_JsonSerializer;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public class ChangeInfo extends JavaScriptObject {
public final void init() {
if (allLabels() != null) {
allLabels().copyKeysIntoChildren("_name");
}
}
public final Project.NameKey projectNameKey() {
return new Project.NameKey(project());
}
public final Change.Id legacyId() {
return new Change.Id(_number());
}
public final Timestamp created() {
Timestamp ts = _getCts();
if (ts == null) {
ts = JavaSqlTimestamp_JsonSerializer.parseTimestamp(createdRaw());
_setCts(ts);
}
return ts;
}
public final boolean hasEditBasedOnCurrentPatchSet() {
JsArray<RevisionInfo> revList = revisions().values();
RevisionInfo.sortRevisionInfoByNumber(revList);
return revList.get(revList.length() - 1).isEdit();
}
private final native Timestamp _getCts() /*-{ return this._cts; }-*/;
private final native void _setCts(Timestamp ts) /*-{ this._cts = ts; }-*/;
public final Timestamp updated() {
return JavaSqlTimestamp_JsonSerializer.parseTimestamp(updatedRaw());
}
public final String idAbbreviated() {
return new Change.Key(changeId()).abbreviate();
}
public final Change.Status status() {
return Change.Status.valueOf(statusRaw());
}
public final Set<String> labels() {
return allLabels().keySet();
}
public final Set<Integer> removableReviewerIds() {
Set<Integer> removable = new HashSet<>();
if (removableReviewers() != null) {
for (AccountInfo a : Natives.asList(removableReviewers())) {
removable.add(a._accountId());
}
}
return removable;
}
public final native String id() /*-{ return this.id; }-*/;
public final native String project() /*-{ return this.project; }-*/;
public final native String branch() /*-{ return this.branch; }-*/;
public final native String topic() /*-{ return this.topic; }-*/;
public final native String changeId() /*-{ return this.change_id; }-*/;
public final native boolean mergeable() /*-{ return this.mergeable ? true : false; }-*/;
public final native int insertions() /*-{ return this.insertions; }-*/;
public final native int deletions() /*-{ return this.deletions; }-*/;
private final native String statusRaw() /*-{ return this.status; }-*/;
public final native String subject() /*-{ return this.subject; }-*/;
public final native AccountInfo owner() /*-{ return this.owner; }-*/;
private final native String createdRaw() /*-{ return this.created; }-*/;
private final native String updatedRaw() /*-{ return this.updated; }-*/;
public final native boolean starred() /*-{ return this.starred ? true : false; }-*/;
public final native boolean reviewed() /*-{ return this.reviewed ? true : false; }-*/;
public final native NativeMap<LabelInfo> allLabels() /*-{ return this.labels; }-*/;
public final native LabelInfo label(String n) /*-{ return this.labels[n]; }-*/;
public final native String currentRevision() /*-{ return this.current_revision; }-*/;
public final native void setCurrentRevision(String r) /*-{ this.current_revision = r; }-*/;
public final native NativeMap<RevisionInfo> revisions() /*-{ return this.revisions; }-*/;
public final native RevisionInfo revision(String n) /*-{ return this.revisions[n]; }-*/;
public final native JsArray<MessageInfo> messages() /*-{ return this.messages; }-*/;
public final native void setEdit(EditInfo edit) /*-{ this.edit = edit; }-*/;
public final native EditInfo edit() /*-{ return this.edit; }-*/;
public final native boolean hasEdit() /*-{ return this.hasOwnProperty('edit') }-*/;
public final native JsArrayString hashtags() /*-{ return this.hashtags; }-*/;
public final native boolean hasPermittedLabels()
/*-{ return this.hasOwnProperty('permitted_labels') }-*/;
public final native NativeMap<JsArrayString> permittedLabels()
/*-{ return this.permitted_labels; }-*/;
public final native JsArrayString permittedValues(String n)
/*-{ return this.permitted_labels[n]; }-*/;
public final native JsArray<AccountInfo> removableReviewers()
/*-{ return this.removable_reviewers; }-*/;
public final native boolean hasActions() /*-{ return this.hasOwnProperty('actions') }-*/;
public final native NativeMap<ActionInfo> actions() /*-{ return this.actions; }-*/;
public final native int _number() /*-{ return this._number; }-*/;
public final native boolean _more_changes()
/*-{ return this._more_changes ? true : false; }-*/;
public final boolean submittable() {
init();
return _submittable();
}
private final native boolean _submittable()
/*-{ return this.submittable ? true : false; }-*/;
/**
* @return the index of the missing label or -1
* if no label is missing, or if more than one label is missing.
*/
public final int getMissingLabelIndex() {
int i = -1;
int ret = -1;
List<LabelInfo> labels = Natives.asList(allLabels().values());
for (LabelInfo label : labels) {
i++;
if (!permittedLabels().containsKey(label.name())) {
continue;
}
JsArrayString values = permittedValues(label.name());
if (values.length() == 0) {
continue;
}
switch (label.status()) {
case NEED: // Label is required for submit.
if (ret != -1) {
// more than one label is missing, so it's unclear which to quick
// approve, return -1
return -1;
} else {
ret = i;
}
continue;
case OK: // Label already applied.
case MAY: // Label is not required.
continue;
case REJECT: // Submit cannot happen, do not quick approve.
case IMPOSSIBLE:
return -1;
}
}
return ret;
}
protected ChangeInfo() {
}
public static class LabelInfo extends JavaScriptObject {
public final SubmitRecord.Label.Status status() {
if (approved() != null) {
return SubmitRecord.Label.Status.OK;
} else if (rejected() != null) {
return SubmitRecord.Label.Status.REJECT;
} else if (optional()) {
return SubmitRecord.Label.Status.MAY;
} else {
return SubmitRecord.Label.Status.NEED;
}
}
public final native String name() /*-{ return this._name; }-*/;
public final native AccountInfo approved() /*-{ return this.approved; }-*/;
public final native AccountInfo rejected() /*-{ return this.rejected; }-*/;
public final native AccountInfo recommended() /*-{ return this.recommended; }-*/;
public final native AccountInfo disliked() /*-{ return this.disliked; }-*/;
public final native JsArray<ApprovalInfo> all() /*-{ return this.all; }-*/;
public final ApprovalInfo forUser(int user) {
JsArray<ApprovalInfo> all = all();
for (int i = 0; all != null && i < all.length(); i++) {
if (all.get(i)._accountId() == user) {
return all.get(i);
}
}
return null;
}
private final native NativeMap<NativeString> _values() /*-{ return this.values; }-*/;
public final Set<String> values() {
return Natives.keys(_values());
}
public final native String valueText(String n) /*-{ return this.values[n]; }-*/;
public final native boolean optional() /*-{ return this.optional ? true : false; }-*/;
public final native boolean blocking() /*-{ return this.blocking ? true : false; }-*/;
public final native short defaultValue() /*-{ return this.default_value; }-*/;
public final native short _value()
/*-{
if (this.value) return this.value;
if (this.disliked) return -1;
if (this.recommended) return 1;
return 0;
}-*/;
public final String maxValue() {
return LabelValue.formatValue(valueSet().last());
}
public final SortedSet<Short> valueSet() {
SortedSet<Short> values = new TreeSet<>();
for (String v : values()) {
values.add(parseValue(v));
}
return values;
}
public static final short parseValue(String formatted) {
if (formatted.startsWith("+")) {
formatted = formatted.substring(1);
} else if (formatted.startsWith(" ")) {
formatted = formatted.trim();
}
return Short.parseShort(formatted);
}
protected LabelInfo() {
}
}
public static class ApprovalInfo extends AccountInfo {
public final native boolean hasValue() /*-{ return this.hasOwnProperty('value'); }-*/;
public final native short value() /*-{ return this.value || 0; }-*/;
protected ApprovalInfo() {
}
}
public static class EditInfo extends JavaScriptObject {
public final native String name() /*-{ return this.name; }-*/;
public final native String setName(String n) /*-{ this.name = n; }-*/;
public final native String baseRevision() /*-{ return this.base_revision; }-*/;
public final native CommitInfo commit() /*-{ return this.commit; }-*/;
public final native boolean hasActions() /*-{ return this.hasOwnProperty('actions') }-*/;
public final native NativeMap<ActionInfo> actions() /*-{ return this.actions; }-*/;
public final native boolean hasFetch() /*-{ return this.hasOwnProperty('fetch') }-*/;
public final native NativeMap<FetchInfo> fetch() /*-{ return this.fetch; }-*/;
public final native boolean hasFiles() /*-{ return this.hasOwnProperty('files') }-*/;
public final native NativeMap<FileInfo> files() /*-{ return this.files; }-*/;
protected EditInfo() {
}
}
public static class RevisionInfo extends JavaScriptObject {
public static RevisionInfo fromEdit(EditInfo edit) {
RevisionInfo revisionInfo = createObject().cast();
revisionInfo.takeFromEdit(edit);
return revisionInfo;
}
private final native void takeFromEdit(EditInfo edit) /*-{
this._number = 0;
this.name = edit.name;
this.commit = edit.commit;
this.edit_base = edit.base_revision;
}-*/;
public final native int _number() /*-{ return this._number; }-*/;
public final native String name() /*-{ return this.name; }-*/;
public final native boolean draft() /*-{ return this.draft || false; }-*/;
public final native AccountInfo uploader() /*-{ return this.uploader; }-*/;
public final native boolean isEdit() /*-{ return this._number == 0; }-*/;
public final native CommitInfo commit() /*-{ return this.commit; }-*/;
public final native void setCommit(CommitInfo c) /*-{ this.commit = c; }-*/;
public final native String editBase() /*-{ return this.edit_base; }-*/;
public final native boolean hasFiles() /*-{ return this.hasOwnProperty('files') }-*/;
public final native NativeMap<FileInfo> files() /*-{ return this.files; }-*/;
public final native boolean hasActions() /*-{ return this.hasOwnProperty('actions') }-*/;
public final native NativeMap<ActionInfo> actions() /*-{ return this.actions; }-*/;
public final native boolean hasFetch() /*-{ return this.hasOwnProperty('fetch') }-*/;
public final native NativeMap<FetchInfo> fetch() /*-{ return this.fetch; }-*/;
public final native boolean hasPushCertificate() /*-{ return this.hasOwnProperty('push_certificate'); }-*/;
public final native PushCertificateInfo pushCertificate() /*-{ return this.push_certificate; }-*/;
public static void sortRevisionInfoByNumber(JsArray<RevisionInfo> list) {
final int editParent = findEditParent(list);
Collections.sort(Natives.asList(list), new Comparator<RevisionInfo>() {
@Override
public int compare(RevisionInfo a, RevisionInfo b) {
return num(a) - num(b);
}
private int num(RevisionInfo r) {
return !r.isEdit() ? 2 * (r._number() - 1) + 1 : 2 * editParent;
}
});
}
public static int findEditParent(JsArray<RevisionInfo> list) {
RevisionInfo r = findEditParentRevision(list);
return r == null ? -1 : r._number();
}
public static RevisionInfo findEditParentRevision(
JsArray<RevisionInfo> list) {
for (int i = 0; i < list.length(); i++) {
// edit under revisions?
RevisionInfo editInfo = list.get(i);
if (editInfo.isEdit()) {
String parentRevision = editInfo.editBase();
// find parent
for (int j = 0; j < list.length(); j++) {
RevisionInfo parentInfo = list.get(j);
String name = parentInfo.name();
if (name.equals(parentRevision)) {
// found parent pacth set number
return parentInfo;
}
}
}
}
return null;
}
public final String id() {
return PatchSet.Id.toId(_number());
}
protected RevisionInfo () {
}
}
public static class FetchInfo extends JavaScriptObject {
public final native String url() /*-{ return this.url }-*/;
public final native String ref() /*-{ return this.ref }-*/;
public final native NativeMap<NativeString> commands() /*-{ return this.commands }-*/;
public final native String command(String n) /*-{ return this.commands[n]; }-*/;
protected FetchInfo () {
}
}
public static class CommitInfo extends JavaScriptObject {
public final native String commit() /*-{ return this.commit; }-*/;
public final native JsArray<CommitInfo> parents() /*-{ return this.parents; }-*/;
public final native GitPerson author() /*-{ return this.author; }-*/;
public final native GitPerson committer() /*-{ return this.committer; }-*/;
public final native String subject() /*-{ return this.subject; }-*/;
public final native String message() /*-{ return this.message; }-*/;
public final native JsArray<WebLinkInfo> webLinks() /*-{ return this.web_links; }-*/;
protected CommitInfo() {
}
}
public static class GitPerson extends JavaScriptObject {
public final native String name() /*-{ return this.name; }-*/;
public final native String email() /*-{ return this.email; }-*/;
private final native String dateRaw() /*-{ return this.date; }-*/;
public final Timestamp date() {
return JavaSqlTimestamp_JsonSerializer.parseTimestamp(dateRaw());
}
protected GitPerson() {
}
}
public static class MessageInfo extends JavaScriptObject {
public final native AccountInfo author() /*-{ return this.author; }-*/;
public final native String message() /*-{ return this.message; }-*/;
public final native int _revisionNumber() /*-{ return this._revision_number || 0; }-*/;
private final native String dateRaw() /*-{ return this.date; }-*/;
public final Timestamp date() {
return JavaSqlTimestamp_JsonSerializer.parseTimestamp(dateRaw());
}
protected MessageInfo() {
}
}
public static class MergeableInfo extends JavaScriptObject {
public final native String submitType() /*-{ return this.submit_type }-*/;
public final native boolean mergeable() /*-{ return this.mergeable }-*/;
protected MergeableInfo() {
}
}
public static class IncludedInInfo extends JavaScriptObject {
public final Set<String> externalNames() {
return Natives.keys(external());
}
public final native JsArrayString branches() /*-{ return this.branches; }-*/;
public final native JsArrayString tags() /*-{ return this.tags; }-*/;
public final native JsArrayString external(String n) /*-{ return this.external[n]; }-*/;
private final native NativeMap<JsArrayString> external() /*-{ return this.external; }-*/;
protected IncludedInInfo() {
}
}
}
| Organize imports
Change-Id: I6936181a5d5f55828ddc959d7b59b1645fa6f870
| gerrit-gwtui-common/src/main/java/com/google/gerrit/client/info/ChangeInfo.java | Organize imports | <ide><path>errit-gwtui-common/src/main/java/com/google/gerrit/client/info/ChangeInfo.java
<ide> import java.sql.Timestamp;
<ide> import java.util.Collections;
<ide> import java.util.Comparator;
<add>import java.util.HashSet;
<ide> import java.util.List;
<del>import java.util.HashSet;
<ide> import java.util.Set;
<ide> import java.util.SortedSet;
<ide> import java.util.TreeSet; |
|
JavaScript | mit | 0f6fe660fd82e0f688d92452db4d7981f95b9ec5 | 0 | pepebecker/find-hanzi | 'use strict'
const cangjie2radicals = require('./cangjie.json')
const cangjie2hanzi = require('./data/cangjie2hanzi.json')
const hanzi2cangjie = require('./data/hanzi2cangjie.json')
const hanzi2definition = require('./data/hanzi2definition.json')
const hanzi2frequency = require('./data/hanzi2frequency.json')
const hanzi2pinyin = require('./data/hanzi2pinyin.json')
const hanzi2strokes = require('./data/hanzi2strokes.json')
const pinyin2hanzi = require('./data/pinyin2hanzi.json')
const utils = require('pinyin-utils')
const find = (query, options = {}) => new Promise((yay, nay) => {
let cangjie = hanzi2cangjie[query] // Input type: hanzi
let hanzi = cangjie2hanzi[query] // Input type: cangjie
let hanzies = pinyin2hanzi[utils.numberToMark(query)] // Input type: pinyin
// Input is hanzi
if (cangjie) {
const hanzi = query
const pinyin = hanzi2pinyin[hanzi]
const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
const strokes = hanzi2strokes[hanzi]
const frequency = hanzi2frequency[hanzi]
const definition = hanzi2definition[hanzi]
yay([{hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition}])
return
}
// Input is cangjie
if (hanzi) {
cangjie = query
const pinyin = hanzi2pinyin[hanzi]
const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
const strokes = hanzi2strokes[hanzi]
const frequency = hanzi2frequency[hanzi]
const definition = hanzi2definition[hanzi]
yay([{hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition}])
return
}
// Input is pinyin
if (hanzies) {
const list = []
for (hanzi of hanzies) {
cangjie = hanzi2cangjie[hanzi]
if (!cangjie) continue
const pinyin = hanzi2pinyin[hanzi] || utils.numberToMark(query)
const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
const strokes = hanzi2strokes[hanzi]
const frequency = hanzi2frequency[hanzi] || 9
const definition = hanzi2definition[hanzi]
list.push({hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition})
}
yay(list.sort((a, b) => a.frequency - b.frequency))
return
}
yay([])
})
module.exports = find
| index.js | 'use strict'
const cangjie2radicals = require('./cangjie.json')
const cangjie2hanzi = require('./data/cangjie2hanzi.json')
const hanzi2cangjie = require('./data/hanzi2cangjie.json')
const hanzi2definition = require('./data/hanzi2definition.json')
const hanzi2frequency = require('./data/hanzi2frequency.json')
const hanzi2pinyin = require('./data/hanzi2pinyin.json')
const hanzi2strokes = require('./data/hanzi2strokes.json')
const pinyin2hanzi = require('./data/pinyin2hanzi.json')
const utils = require('pinyin-utils')
const find = (query, options = {}) => new Promise((yay, nay) => {
let cangjie = hanzi2cangjie[query] // Input type: hanzi
let hanzi = cangjie2hanzi[query] // Input type: cangjie
let hanzies = pinyin2hanzi[utils.numberToMark(query)] // Input type: pinyin
// Input is hanzi
if (cangjie) {
const hanzi = query
const pinyin = hanzi2pinyin[hanzi]
const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
const strokes = hanzi2strokes[hanzi]
const frequency = hanzi2frequency[hanzi]
const definition = hanzi2definition[hanzi]
yay([{hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition}])
return
}
// Input is cangjie
if (hanzi) {
cangjie = query
const pinyin = hanzi2pinyin[hanzi]
const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
const strokes = hanzi2strokes[hanzi]
const frequency = hanzi2frequency[hanzi]
const definition = hanzi2definition[hanzi]
yay([{hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition}])
return
}
// Input is pinyin
if (hanzies) {
const list = []
for (hanzi of hanzies) {
cangjie = hanzi2cangjie[hanzi]
if (!cangjie) continue
const pinyin = hanzi2pinyin[hanzi] || utils.numberToMark(query)
const cangjie2 = cangjie.split('').map((c) => cangjie2radicals[c]).join('')
const strokes = hanzi2strokes[hanzi]
const frequency = hanzi2frequency[hanzi] || 9
const definition = hanzi2definition[hanzi]
list.push({hanzi, pinyin, cangjie, cangjie2, strokes, frequency, definition})
}
yay(list.sort((a, b) => a.frequency - b.frequency))
return
}
nay('Unrecognized input type')
})
module.exports = find
| Remove rejection from promise
| index.js | Remove rejection from promise | <ide><path>ndex.js
<ide> return
<ide> }
<ide>
<del> nay('Unrecognized input type')
<add> yay([])
<ide> })
<ide>
<ide> module.exports = find |
|
Java | bsd-3-clause | e65221407114a0aa123a3143604db7a01a72f257 | 0 | BlueAnanas/BungeeCord,TCPR/BungeeCord,btilm305/BungeeCord,xxyy/BungeeCord,PrisonPvP/BungeeCord,starlis/BungeeCord,mariolars/BungeeCord,GamesConMCGames/Bungeecord,xxyy/BungeeCord,PrisonPvP/BungeeCord,LetsPlayOnline/BungeeJumper,Yive/BungeeCord,GamesConMCGames/Bungeecord,Xetius/BungeeCord,GingerGeek/BungeeCord,LinEvil/BungeeCord,LinEvil/BungeeCord,ConnorLinfoot/BungeeCord,mariolars/BungeeCord,starlis/BungeeCord,mariolars/BungeeCord,TCPR/BungeeCord,BlueAnanas/BungeeCord,ewized/BungeeCord,LinEvil/BungeeCord,XMeowTW/BungeeCord,LetsPlayOnline/BungeeJumper,LolnetModPack/BungeeCord,dentmaged/BungeeCord,Yive/BungeeCord,XMeowTW/BungeeCord,ConnorLinfoot/BungeeCord,Xetius/BungeeCord,ewized/BungeeCord,dentmaged/BungeeCord,BlueAnanas/BungeeCord,LolnetModPack/BungeeCord,Xetius/BungeeCord,LetsPlayOnline/BungeeJumper,LolnetModPack/BungeeCord,TCPR/BungeeCord,btilm305/BungeeCord,GingerGeek/BungeeCord,dentmaged/BungeeCord,Yive/BungeeCord,btilm305/BungeeCord,ewized/BungeeCord,GingerGeek/BungeeCord,ConnorLinfoot/BungeeCord,starlis/BungeeCord,XMeowTW/BungeeCord,GamesConMCGames/Bungeecord,xxyy/BungeeCord,PrisonPvP/BungeeCord | package net.md_5.bungee.connection;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.EntityMap;
import net.md_5.bungee.UserConnection;
import net.md_5.bungee.Util;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.TexturePackInfo;
import net.md_5.bungee.api.event.ChatEvent;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.PacketHandler;
import net.md_5.bungee.protocol.packet.Packet0KeepAlive;
import net.md_5.bungee.protocol.packet.Packet3Chat;
import net.md_5.bungee.protocol.packet.PacketCCSettings;
import net.md_5.bungee.protocol.packet.PacketFAPluginMessage;
public class UpstreamBridge extends PacketHandler
{
private final ProxyServer bungee;
private final UserConnection con;
public UpstreamBridge(ProxyServer bungee, UserConnection con)
{
this.bungee = bungee;
this.con = con;
BungeeCord.getInstance().addConnection( con );
bungee.getTabListHandler().onConnect( con );
con.unsafe().sendPacket( BungeeCord.getInstance().registerChannels() );
TexturePackInfo texture = con.getPendingConnection().getListener().getTexturePack();
if ( texture != null )
{
con.setTexturePack( texture );
}
}
@Override
public void exception(Throwable t) throws Exception
{
con.disconnect( Util.exception( t ) );
}
@Override
public void disconnected(ChannelWrapper channel) throws Exception
{
// We lost connection to the client
PlayerDisconnectEvent event = new PlayerDisconnectEvent( con );
bungee.getPluginManager().callEvent( event );
bungee.getTabListHandler().onDisconnect( con );
BungeeCord.getInstance().removeConnection( con );
if ( con.getServer() != null )
{
con.getServer().disconnect( "Quitting" );
}
}
@Override
public void handle(byte[] buf) throws Exception
{
EntityMap.rewrite( buf, con.getClientEntityId(), con.getServerEntityId() );
if ( con.getServer() != null )
{
con.getServer().getCh().write( buf );
}
}
@Override
public void handle(Packet0KeepAlive alive) throws Exception
{
if ( alive.getRandomId() == con.getSentPingId() )
{
int newPing = (int) ( System.currentTimeMillis() - con.getSentPingTime() );
bungee.getTabListHandler().onPingChange( con, newPing );
con.setPing( newPing );
}
}
@Override
public void handle(Packet3Chat chat) throws Exception
{
ChatEvent chatEvent = new ChatEvent( con, con.getServer(), chat.getMessage() );
if ( bungee.getPluginManager().callEvent( chatEvent ).isCancelled() )
{
throw new CancelSendSignal();
}
if ( chatEvent.isCommand() )
{
if ( bungee.getPluginManager().dispatchCommand( con, chat.getMessage().substring( 1 ) ) )
{
throw new CancelSendSignal();
}
}
}
@Override
public void handle(PacketCCSettings settings) throws Exception
{
con.setSettings( settings );
}
@Override
public void handle(PacketFAPluginMessage pluginMessage) throws Exception
{
if ( pluginMessage.getTag().equals( "BungeeCord" ) )
{
throw new CancelSendSignal();
}
PluginMessageEvent event = new PluginMessageEvent( con, con.getServer(), pluginMessage.getTag(), pluginMessage.getData().clone() );
if ( bungee.getPluginManager().callEvent( event ).isCancelled() )
{
throw new CancelSendSignal();
}
}
@Override
public String toString()
{
return "[" + con.getName() + "] -> UpstreamBridge";
}
}
| proxy/src/main/java/net/md_5/bungee/connection/UpstreamBridge.java | package net.md_5.bungee.connection;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.EntityMap;
import net.md_5.bungee.UserConnection;
import net.md_5.bungee.Util;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.TexturePackInfo;
import net.md_5.bungee.api.event.ChatEvent;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.PacketHandler;
import net.md_5.bungee.protocol.packet.Packet0KeepAlive;
import net.md_5.bungee.protocol.packet.Packet3Chat;
import net.md_5.bungee.protocol.packet.PacketCCSettings;
import net.md_5.bungee.protocol.packet.PacketFAPluginMessage;
public class UpstreamBridge extends PacketHandler
{
private final ProxyServer bungee;
private final UserConnection con;
public UpstreamBridge(ProxyServer bungee, UserConnection con)
{
this.bungee = bungee;
this.con = con;
bungee.getTabListHandler().onConnect( con );
BungeeCord.getInstance().addConnection( con );
con.unsafe().sendPacket( BungeeCord.getInstance().registerChannels() );
TexturePackInfo texture = con.getPendingConnection().getListener().getTexturePack();
if ( texture != null )
{
con.setTexturePack( texture );
}
}
@Override
public void exception(Throwable t) throws Exception
{
con.disconnect( Util.exception( t ) );
}
@Override
public void disconnected(ChannelWrapper channel) throws Exception
{
// We lost connection to the client
PlayerDisconnectEvent event = new PlayerDisconnectEvent( con );
bungee.getPluginManager().callEvent( event );
bungee.getTabListHandler().onDisconnect( con );
BungeeCord.getInstance().removeConnection( con );
if ( con.getServer() != null )
{
con.getServer().disconnect( "Quitting" );
}
}
@Override
public void handle(byte[] buf) throws Exception
{
EntityMap.rewrite( buf, con.getClientEntityId(), con.getServerEntityId() );
if ( con.getServer() != null )
{
con.getServer().getCh().write( buf );
}
}
@Override
public void handle(Packet0KeepAlive alive) throws Exception
{
if ( alive.getRandomId() == con.getSentPingId() )
{
int newPing = (int) ( System.currentTimeMillis() - con.getSentPingTime() );
bungee.getTabListHandler().onPingChange( con, newPing );
con.setPing( newPing );
}
}
@Override
public void handle(Packet3Chat chat) throws Exception
{
ChatEvent chatEvent = new ChatEvent( con, con.getServer(), chat.getMessage() );
if ( bungee.getPluginManager().callEvent( chatEvent ).isCancelled() )
{
throw new CancelSendSignal();
}
if ( chatEvent.isCommand() )
{
if ( bungee.getPluginManager().dispatchCommand( con, chat.getMessage().substring( 1 ) ) )
{
throw new CancelSendSignal();
}
}
}
@Override
public void handle(PacketCCSettings settings) throws Exception
{
con.setSettings( settings );
}
@Override
public void handle(PacketFAPluginMessage pluginMessage) throws Exception
{
if ( pluginMessage.getTag().equals( "BungeeCord" ) )
{
throw new CancelSendSignal();
}
PluginMessageEvent event = new PluginMessageEvent( con, con.getServer(), pluginMessage.getTag(), pluginMessage.getData().clone() );
if ( bungee.getPluginManager().callEvent( event ).isCancelled() )
{
throw new CancelSendSignal();
}
}
@Override
public String toString()
{
return "[" + con.getName() + "] -> UpstreamBridge";
}
}
| Close issue #406 - tab list
| proxy/src/main/java/net/md_5/bungee/connection/UpstreamBridge.java | Close issue #406 - tab list | <ide><path>roxy/src/main/java/net/md_5/bungee/connection/UpstreamBridge.java
<ide> this.bungee = bungee;
<ide> this.con = con;
<ide>
<add> BungeeCord.getInstance().addConnection( con );
<ide> bungee.getTabListHandler().onConnect( con );
<del> BungeeCord.getInstance().addConnection( con );
<ide> con.unsafe().sendPacket( BungeeCord.getInstance().registerChannels() );
<ide>
<ide> TexturePackInfo texture = con.getPendingConnection().getListener().getTexturePack(); |
|
Java | apache-2.0 | 6088d60b3c84987ddd943b2e2a148fc73c2ff196 | 0 | MatthewTamlin/Mixtape | /*
* Copyright 2017 Matthew Tamlin
*
* 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.matthewtamlin.mixtape.library.caching;
import android.graphics.Bitmap;
import android.util.LruCache;
import com.matthewtamlin.java_utilities.checkers.IntChecker;
import com.matthewtamlin.mixtape.library.data.LibraryItem;
import com.matthewtamlin.mixtape.library.data.LibraryReadException;
import timber.log.Timber;
/**
* An in-memory LibraryItemCache which operates using the least-recently-used (LRU) principle. When
* the cache is filled to capacity, new caching requests result in objects being evicted until there
* is sufficient room. This allows a finite cache to accept new data indefinitely without running
* out of memory. Titles, subtitles and artwork are stored independently, so that eviction of one
* data type does not affect the others.
*/
public class LruLibraryItemCache implements LibraryItemCache {
/**
* Used to identify this class during debugging.
*/
private static final String TAG = "LruLibraryItemCache";
/**
* Contains the cached titles. Each title is mapped to the LibraryItem object it was sourced
* from.
*/
private final LruCache<LibraryItem, CharSequence> titleCache;
/**
* Contains the cached subtitles. Each subtitle is mapped to the LibraryItem object it was
* sourced from.
*/
private final LruCache<LibraryItem, CharSequence> subtitleCache;
/**
* Contains the cached artwork. Each item of artwork is mapped to the LibraryItem object it was
* sourced from.
*/
private final LruCache<LibraryItem, Bitmap> artworkCache;
/**
* Constructs a new LruLibraryItemCache. The supplied capacities determine when to evict items
* to free up space.
*
* @param titleSizeBytes
* the capacity of the title cache, measured in bytes, greater than zero
* @param subtitleSizeBytes
* the capacity of the subtitle cache, measured in bytes, greater than zero
* @param artworkSizeBytes
* the capacity of the artwork cache, measured in bytes, greater than zero
* @throws IllegalArgumentException
* if titleSizeBytes is not greater than zero
* @throws IllegalArgumentException
* if subtitleSizeBytes is not greater than zero
* @throws IllegalArgumentException
* if artworkSizeBytes is not greater than zero
*/
public LruLibraryItemCache(final int titleSizeBytes, final int subtitleSizeBytes,
final int artworkSizeBytes) {
IntChecker.checkGreaterThan(titleSizeBytes, 0, "titleSizeBytes is less than one");
IntChecker.checkGreaterThan(subtitleSizeBytes, 0, "subtitleSizeBytes is less than one");
IntChecker.checkGreaterThan(artworkSizeBytes, 0, "artworkSizeBytes is less than one");
titleCache = new LruCache<LibraryItem, CharSequence>(titleSizeBytes) {
@Override
protected int sizeOf(final LibraryItem key, final CharSequence value) {
return value.toString().getBytes().length;
}
};
subtitleCache = new LruCache<LibraryItem, CharSequence>(subtitleSizeBytes) {
@Override
protected int sizeOf(final LibraryItem key, final CharSequence value) {
return value.toString().getBytes().length;
}
};
artworkCache = new LruCache<LibraryItem, Bitmap>(artworkSizeBytes) {
@Override
protected int sizeOf(final LibraryItem key, final Bitmap value) {
return value.getByteCount();
}
};
}
@Override
public final void cacheTitle(final LibraryItem item, final boolean onlyIfNotCached) {
// If the title is already cached and 'onlyIfNotCached' is true, don't re-cache
if ((item != null) && !(onlyIfNotCached && containsTitle(item))) {
try {
final CharSequence title = item.getTitle(); // May throw access exception
// Execution will only reach here if a read exception was not thrown
if (title != null) {
titleCache.put(item, title);
}
} catch (final LibraryReadException e) {
// Log the error and perform no caching
Timber.w("Title for item \"" + item + "\" could not be accessed.", e);
}
}
}
@Override
public final void cacheSubtitle(final LibraryItem item, final boolean onlyIfNotCached) {
// If the subtitle is already cached and 'onlyIfNotCached' is true, don't re-cache
if ((item != null) && !(onlyIfNotCached && containsSubtitle(item))) {
try {
final CharSequence subtitle = item.getSubtitle(); // May throw access exception
// Execution will only reach here if an exception was not thrown
if (subtitle != null) {
subtitleCache.put(item, subtitle);
}
} catch (final LibraryReadException e) {
// Log the error and perform no caching
Timber.w("Subtitle for item \"" + item + "\" could not be accessed.", e);
}
}
}
@Override
public final void cacheArtwork(final LibraryItem item, final boolean onlyIfNotCached,
final int preferredWidth, final int preferredHeight) {
// If the artwork is already cached and 'onlyIfNotCached' is true, don't re-cache
if ((item != null) && !(onlyIfNotCached && containsArtwork(item))) {
try {
// May throw access exception
final Bitmap artwork = item.getArtwork(preferredWidth, preferredHeight);
// Execution will only reach here if an exception was not thrown
if (artwork != null) {
artworkCache.put(item, artwork);
}
} catch (final LibraryReadException e) {
// Log the error and perform no caching
Timber.w("Artwork for item \"" + item + "\" could not be accessed.", e);
}
}
}
@Override
public final CharSequence getTitle(final LibraryItem item) {
return (item == null) ? null : titleCache.get(item);
}
@Override
public final CharSequence getSubtitle(final LibraryItem item) {
return (item == null) ? null : subtitleCache.get(item);
}
@Override
public final Bitmap getArtwork(final LibraryItem item) {
return (item == null) ? null : artworkCache.get(item);
}
@Override
public final void clearTitles() {
titleCache.evictAll();
}
@Override
public final void clearSubtitles() {
subtitleCache.evictAll();
}
@Override
public final void clearArtwork() {
artworkCache.evictAll();
}
@Override
public final void removeTitle(final LibraryItem item) {
titleCache.remove(item);
}
@Override
public final void removeSubtitle(final LibraryItem item) {
subtitleCache.remove(item);
}
@Override
public final void removeArtwork(final LibraryItem item) {
artworkCache.remove(item);
}
@Override
public final boolean containsTitle(final LibraryItem item) {
return getTitle(item) != null;
}
@Override
public final boolean containsSubtitle(final LibraryItem item) {
return getSubtitle(item) != null;
}
@Override
public final boolean containsArtwork(final LibraryItem item) {
return getArtwork(item) != null;
}
} | library/src/main/java/com/matthewtamlin/mixtape/library/caching/LruLibraryItemCache.java | /*
* Copyright 2017 Matthew Tamlin
*
* 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.matthewtamlin.mixtape.library.caching;
import android.graphics.Bitmap;
import android.util.Log;
import android.util.LruCache;
import com.matthewtamlin.java_utilities.checkers.IntChecker;
import com.matthewtamlin.mixtape.library.data.LibraryItem;
import com.matthewtamlin.mixtape.library.data.LibraryReadException;
/**
* An in-memory LibraryItemCache which operates using the least-recently-used (LRU) principle. When
* the cache is filled to capacity, new caching requests result in objects being evicted until there
* is sufficient room. This allows a finite cache to accept new data indefinitely without running
* out of memory. Titles, subtitles and artwork are stored independently, so that eviction of one
* data type does not affect the others.
*/
public class LruLibraryItemCache implements LibraryItemCache {
/**
* Used to identify this class during debugging.
*/
private static final String TAG = "LruLibraryItemCache";
/**
* Contains the cached titles. Each title is mapped to the LibraryItem object it was sourced
* from.
*/
private final LruCache<LibraryItem, CharSequence> titleCache;
/**
* Contains the cached subtitles. Each subtitle is mapped to the LibraryItem object it was
* sourced from.
*/
private final LruCache<LibraryItem, CharSequence> subtitleCache;
/**
* Contains the cached artwork. Each item of artwork is mapped to the LibraryItem object it was
* sourced from.
*/
private final LruCache<LibraryItem, Bitmap> artworkCache;
/**
* Constructs a new LruLibraryItemCache. The supplied capacities determine when to evict items
* to free up space.
*
* @param titleSizeBytes
* the capacity of the title cache, measured in bytes, greater than zero
* @param subtitleSizeBytes
* the capacity of the subtitle cache, measured in bytes, greater than zero
* @param artworkSizeBytes
* the capacity of the artwork cache, measured in bytes, greater than zero
* @throws IllegalArgumentException
* if titleSizeBytes is not greater than zero
* @throws IllegalArgumentException
* if subtitleSizeBytes is not greater than zero
* @throws IllegalArgumentException
* if artworkSizeBytes is not greater than zero
*/
public LruLibraryItemCache(final int titleSizeBytes, final int subtitleSizeBytes,
final int artworkSizeBytes) {
IntChecker.checkGreaterThan(titleSizeBytes, 0, "titleSizeBytes is less than one");
IntChecker.checkGreaterThan(subtitleSizeBytes, 0, "subtitleSizeBytes is less than one");
IntChecker.checkGreaterThan(artworkSizeBytes, 0, "artworkSizeBytes is less than one");
titleCache = new LruCache<LibraryItem, CharSequence>(titleSizeBytes) {
@Override
protected int sizeOf(final LibraryItem key, final CharSequence value) {
return value.toString().getBytes().length;
}
};
subtitleCache = new LruCache<LibraryItem, CharSequence>(subtitleSizeBytes) {
@Override
protected int sizeOf(final LibraryItem key, final CharSequence value) {
return value.toString().getBytes().length;
}
};
artworkCache = new LruCache<LibraryItem, Bitmap>(artworkSizeBytes) {
@Override
protected int sizeOf(final LibraryItem key, final Bitmap value) {
return value.getByteCount();
}
};
}
@Override
public final void cacheTitle(final LibraryItem item, final boolean onlyIfNotCached) {
// If the title is already cached and 'onlyIfNotCached' is true, don't re-cache
if ((item != null) && !(onlyIfNotCached && containsTitle(item))) {
try {
final CharSequence title = item.getTitle(); // May throw access exception
// Execution will only reach here if a read exception was not thrown
if (title != null) {
titleCache.put(item, title);
}
} catch (final LibraryReadException e) {
// Log the error and perform no caching
Log.e(TAG, "Title for item \"" + item + "\" could not be accessed.", e);
}
}
}
@Override
public final void cacheSubtitle(final LibraryItem item, final boolean onlyIfNotCached) {
// If the subtitle is already cached and 'onlyIfNotCached' is true, don't re-cache
if ((item != null) && !(onlyIfNotCached && containsSubtitle(item))) {
try {
final CharSequence subtitle = item.getSubtitle(); // May throw access exception
// Execution will only reach here if an exception was not thrown
if (subtitle != null) {
subtitleCache.put(item, subtitle);
}
} catch (final LibraryReadException e) {
// Log the error and perform no caching
Log.e(TAG, "Subtitle for item \"" + item + "\" could not be accessed.", e);
}
}
}
@Override
public final void cacheArtwork(final LibraryItem item, final boolean onlyIfNotCached,
final int preferredWidth, final int preferredHeight) {
// If the artwork is already cached and 'onlyIfNotCached' is true, don't re-cache
if ((item != null) && !(onlyIfNotCached && containsArtwork(item))) {
try {
// May throw access exception
final Bitmap artwork = item.getArtwork(preferredWidth, preferredHeight);
// Execution will only reach here if an exception was not thrown
if (artwork != null) {
artworkCache.put(item, artwork);
}
} catch (final LibraryReadException e) {
// Log the error and perform no caching
Log.e(TAG, "Artwork for item \"" + item + "\" could not be accessed.", e);
}
}
}
@Override
public final CharSequence getTitle(final LibraryItem item) {
return (item == null) ? null : titleCache.get(item);
}
@Override
public final CharSequence getSubtitle(final LibraryItem item) {
return (item == null) ? null : subtitleCache.get(item);
}
@Override
public final Bitmap getArtwork(final LibraryItem item) {
return (item == null) ? null : artworkCache.get(item);
}
@Override
public final void clearTitles() {
titleCache.evictAll();
}
@Override
public final void clearSubtitles() {
subtitleCache.evictAll();
}
@Override
public final void clearArtwork() {
artworkCache.evictAll();
}
@Override
public final void removeTitle(final LibraryItem item) {
titleCache.remove(item);
}
@Override
public final void removeSubtitle(final LibraryItem item) {
subtitleCache.remove(item);
}
@Override
public final void removeArtwork(final LibraryItem item) {
artworkCache.remove(item);
}
@Override
public final boolean containsTitle(final LibraryItem item) {
return getTitle(item) != null;
}
@Override
public final boolean containsSubtitle(final LibraryItem item) {
return getSubtitle(item) != null;
}
@Override
public final boolean containsArtwork(final LibraryItem item) {
return getArtwork(item) != null;
}
} | Switched to Timber logging framework
| library/src/main/java/com/matthewtamlin/mixtape/library/caching/LruLibraryItemCache.java | Switched to Timber logging framework | <ide><path>ibrary/src/main/java/com/matthewtamlin/mixtape/library/caching/LruLibraryItemCache.java
<ide> package com.matthewtamlin.mixtape.library.caching;
<ide>
<ide> import android.graphics.Bitmap;
<del>import android.util.Log;
<ide> import android.util.LruCache;
<ide>
<ide> import com.matthewtamlin.java_utilities.checkers.IntChecker;
<ide> import com.matthewtamlin.mixtape.library.data.LibraryItem;
<ide> import com.matthewtamlin.mixtape.library.data.LibraryReadException;
<add>
<add>import timber.log.Timber;
<ide>
<ide> /**
<ide> * An in-memory LibraryItemCache which operates using the least-recently-used (LRU) principle. When
<ide> }
<ide> } catch (final LibraryReadException e) {
<ide> // Log the error and perform no caching
<del> Log.e(TAG, "Title for item \"" + item + "\" could not be accessed.", e);
<add> Timber.w("Title for item \"" + item + "\" could not be accessed.", e);
<ide> }
<ide> }
<ide> }
<ide> }
<ide> } catch (final LibraryReadException e) {
<ide> // Log the error and perform no caching
<del> Log.e(TAG, "Subtitle for item \"" + item + "\" could not be accessed.", e);
<add> Timber.w("Subtitle for item \"" + item + "\" could not be accessed.", e);
<ide> }
<ide> }
<ide> }
<ide> }
<ide> } catch (final LibraryReadException e) {
<ide> // Log the error and perform no caching
<del> Log.e(TAG, "Artwork for item \"" + item + "\" could not be accessed.", e);
<add> Timber.w("Artwork for item \"" + item + "\" could not be accessed.", e);
<ide> }
<ide> }
<ide> } |
|
Java | lgpl-2.1 | cc0d238dd446fc23e9f88ed4529c9741762fb9b6 | 0 | Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,drhee/toxoMine,elsiklab/intermine,zebrafishmine/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,justincc/intermine,tomck/intermine,justincc/intermine,tomck/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,elsiklab/intermine,zebrafishmine/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,kimrutherford/intermine,justincc/intermine,JoeCarlson/intermine,justincc/intermine,elsiklab/intermine,joshkh/intermine,joshkh/intermine,elsiklab/intermine,zebrafishmine/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,JoeCarlson/intermine,drhee/toxoMine,kimrutherford/intermine,elsiklab/intermine,joshkh/intermine,elsiklab/intermine,tomck/intermine,drhee/toxoMine,zebrafishmine/intermine,JoeCarlson/intermine,JoeCarlson/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,zebrafishmine/intermine,drhee/toxoMine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,elsiklab/intermine,tomck/intermine,JoeCarlson/intermine,drhee/toxoMine,JoeCarlson/intermine,kimrutherford/intermine,tomck/intermine,joshkh/intermine,zebrafishmine/intermine,joshkh/intermine,drhee/toxoMine,justincc/intermine,JoeCarlson/intermine,zebrafishmine/intermine,justincc/intermine,JoeCarlson/intermine,tomck/intermine,zebrafishmine/intermine,drhee/toxoMine,justincc/intermine,tomck/intermine,joshkh/intermine,kimrutherford/intermine,joshkh/intermine,joshkh/intermine,justincc/intermine | package org.flymine.postprocess;
/*
* Copyright (C) 2002-2005 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.HashMap;
import org.intermine.objectstore.query.*;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStore;
import org.intermine.sql.Database;
import org.intermine.metadata.Model;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.model.InterMineObject;
import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.util.DatabaseUtil;
import org.intermine.util.TypeUtil;
import org.flymine.model.genomic.*;
import org.apache.log4j.Logger;
/**
* Fill in additional references/collections in genomic model
*
* @author Richard Smith
* @author Kim Rutherford
*/
public class CreateReferences
{
private static final Logger LOG = Logger.getLogger(CreateReferences.class);
protected ObjectStoreWriter osw;
private Model model;
/**
* Construct with an ObjectStoreWriter, read and write from same ObjectStore
* @param osw an ObjectStore to write to
*/
public CreateReferences(ObjectStoreWriter osw) {
this.osw = osw;
this.model = Model.getInstanceByName("genomic");
}
/**
* Fill in missing references/collections in model by querying relations
* @throws Exception if anything goes wrong
*/
public void insertReferences() throws Exception {
// LOG.info("insertReferences stage 1");
// Transcript.exons / Exon.transcripts
insertCollectionField(Transcript.class, "subjects", RankedRelation.class, "subject",
Exon.class, "transcripts", false);
insertCollectionField(Transcript.class, "subjects", SimpleRelation.class, "subject",
Exon.class, "transcripts", false);
// Intron.MRNAs / MRNA.introns
insertCollectionField(Transcript.class, "subjects", SimpleRelation.class, "subject",
Intron.class, "introns", true);
insertCollectionField(Transcript.class, "subjects", SimpleRelation.class, "subject",
Exon.class, "exons", true);
LOG.info("insertReferences stage 2");
// Gene.transcript / Transcript.gene
insertReferenceField(Gene.class, "subjects", SimpleRelation.class, "subject",
Transcript.class, "gene");
LOG.info("insertReferences stage 3");
insertReferenceField(Chromosome.class, "subjects", Location.class, "subject",
LocatedSequenceFeature.class, "chromosome");
LOG.info("insertReferences stage 4");
// fill in collections on Chromosome
insertCollectionField(Gene.class, "objects", Location.class, "object",
Chromosome.class, "genes", false);
insertCollectionField(Transcript.class, "objects", Location.class, "object",
Chromosome.class, "transcripts", false);
insertCollectionField(Exon.class, "objects", Location.class, "object",
Chromosome.class, "exons", false);
insertCollectionField(ChromosomeBand.class, "subjects", Location.class, "subject",
Chromosome.class, "chromosomeBands", false);
LOG.info("insertReferences stage 5");
// Exon.gene / Gene.exons
insertReferenceField(Gene.class, "transcripts", Transcript.class, "exons",
Exon.class, "gene");
LOG.info("insertReferences stage 6");
// UTR.gene / Gene.UTRs
insertReferenceField(Gene.class, "transcripts", MRNA.class, "UTRs",
UTR.class, "gene");
LOG.info("insertReferences stage 7");
// Gene.chromosome / Chromosome.genes
insertReferenceField(Chromosome.class, "exons", Exon.class, "gene",
Gene.class, "chromosome");
LOG.info("insertReferences stage 8");
// Transcript.chromosome / Chromosome.transcripts
insertReferenceField(Chromosome.class, "exons", Exon.class, "transcripts",
Transcript.class, "chromosome");
LOG.info("insertReferences stage 9");
// Protein.genes / Gene.proteins
insertCollectionField(Gene.class, "transcripts", Transcript.class, "protein",
Protein.class, "genes", false);
// CDS.gene / Gene.CDSs
insertReferenceField(Gene.class, "transcripts", MRNA.class, "CDSs",
CDS.class, "gene");
LOG.info("insertReferences stage 10");
insertReferenceField(Gene.class, "CDSs", CDS.class, "polypeptides",
Translation.class, "gene");
LOG.info("insertReferences stage 11");
insertReferenceField(Translation.class, "CDSs", CDS.class, "MRNAs",
MRNA.class, "translation");
LOG.info("insertReferences stage 12");
// Gene.CDSs.polypeptides
insertReferenceField(MRNA.class, "CDSs", CDS.class, "polypeptides",
Translation.class, "transcript");
ObjectStore os = osw.getObjectStore();
if (os instanceof ObjectStoreInterMineImpl) {
Database db = ((ObjectStoreInterMineImpl) os).getDatabase();
DatabaseUtil.analyse(db, false);
}
LOG.info("insertReferences stage 13");
insertGeneAnnotationReferences();
if (os instanceof ObjectStoreInterMineImpl) {
Database db = ((ObjectStoreInterMineImpl) os).getDatabase();
DatabaseUtil.analyse(db, false);
}
LOG.info("insertReferences stage 14");
// Gene.phenotypes
insertReferences(Gene.class, Phenotype.class, "phenotypes");
LOG.info("insertReferences stage 15");
// CDNAClone.results (MicroArrayResult)
createCDNACloneResultsCollection();
// CompositeSequence.results (MicroArrayResult)
createCompositeSeqResultsCollection();
// Gene.microArrayResults
createMicroArrayResultsCollection();
LOG.info("insertReferences stage 16");
createUtrRefs();
if (os instanceof ObjectStoreInterMineImpl) {
Database db = ((ObjectStoreInterMineImpl) os).getDatabase();
DatabaseUtil.analyse(db, false);
}
}
/**
* Fill in missing references/collections in model by querying SymmetricalRelations
* @throws Exception if anything goes wrong
*/
public void insertSymmetricalRelationReferences() throws Exception {
LOG.info("insertReferences stage 1");
// Transcript.exons / Exon.transcripts
insertSymmetricalRelationReferences(
LocatedSequenceFeature.class, OverlapRelation.class, "overlappingFeatures"
);
}
/**
* Fill in the "orthologues" collection of Gene. Needs to be run after
* UpdateOrthologues which in turn relies on CreateReferences -> so has
* become a separate method.
* @throws Exception if anything goes wrong
*/
public void populateOrthologuesCollection() throws Exception {
insertReferences(Gene.class, Orthologue.class, "subjects", "orthologues");
}
/**
* Add a reference to and object of type X in objects of type Y by using a connecting class.
* Eg. Add a reference to Gene objects in Exon by examining the Transcript objects in the
* transcripts collection of the Gene, which would use a query like:
* SELECT DISTINCT gene FROM Gene AS gene, Transcript AS transcript, Exon AS exon WHERE
* (gene.transcripts CONTAINS transcript AND transcript.exons CONTAINS exon) ORDER BY gene
* and then set exon.gene
*
* in overview we are doing:
* BioEntity1 -> BioEntity2 -> BioEntity3 ==> BioEntitiy1 -> BioEntity3
* @param sourceClass the first class in the query
* @param sourceClassFieldName the field in the sourceClass which should contain the
* connectingClass
* @param connectingClass the class referred to by sourceClass.sourceFieldName
* @param connectingClassFieldName the field in connectingClass which should contain
* destinationClass
* @param destinationClass the class referred to by
* connectingClass.connectingClassFieldName
* @param createFieldName the reference field in the destinationClass - the
* collection to create/set
* @throws Exception if anything goes wrong
*/
protected void insertReferenceField(Class sourceClass, String sourceClassFieldName,
Class connectingClass, String connectingClassFieldName,
Class destinationClass, String createFieldName)
throws Exception {
LOG.info("Beginning insertReferences("
+ sourceClass.getName() + ", "
+ sourceClassFieldName + ", "
+ connectingClass.getName() + ", "
+ connectingClassFieldName + ","
+ destinationClass.getName() + ", "
+ createFieldName + ")");
Iterator resIter =
PostProcessUtil.findConnectingClasses(osw.getObjectStore(),
sourceClass, sourceClassFieldName,
connectingClass, connectingClassFieldName,
destinationClass, true);
// results will be sourceClass ; destClass (ordered by sourceClass)
osw.beginTransaction();
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
InterMineObject thisSourceObject = (InterMineObject) rr.get(0);
InterMineObject thisDestObject = (InterMineObject) rr.get(1);
try {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(thisDestObject);
TypeUtil.setFieldValue(tempObject, createFieldName, thisSourceObject);
count++;
if (count % 10000 == 0) {
LOG.info("Created " + count + " references in " + destinationClass.getName()
+ " to " + sourceClass.getName()
+ " via " + connectingClass.getName());
}
osw.store(tempObject);
} catch (IllegalAccessException e) {
LOG.error("Object with ID: " + thisDestObject.getId()
+ " has no " + createFieldName + " field");
}
}
LOG.info("Finished: created " + count + " references in " + destinationClass.getName()
+ " to " + sourceClass.getName() + " via " + connectingClass.getName());
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(destinationClass.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Add a collection of objects of type X to objects of type Y by using a connecting class.
* Eg. Add a collection of Protein objects to Gene by examining the Transcript objects in the
* transcripts collection of the Gene, which would use a query like:
* SELECT DISTINCT gene FROM Gene AS gene, Transcript AS transcript, Protein AS protein WHERE
* (gene.transcripts CONTAINS transcript AND transcript.protein CONTAINS protein)
* ORDER BY gene
* and then set protected gene.protein (if created
* BioEntity1 -> BioEntity2 -> BioEntity3 ==> BioEntity1 -> BioEntity3
* @param firstClass the first class in the query
* @param firstClassFieldName the field in the firstClass which should contain the
* connectingClass
* @param connectingClass the class referred to by firstClass.sourceFieldName
* @param connectingClassFieldName the field in connectingClass which should contain
* secondClass
* @param secondClass the class referred to by
* connectingClass.connectingClassFieldName
* @param createFieldName the collection field in the secondClass - the
* collection to create/set
* @param createInFirstClass if true create the new collection field in firstClass, otherwise
* create in secondClass
* @throws Exception if anything goes wrong
*/
protected void insertCollectionField(Class firstClass, String firstClassFieldName,
Class connectingClass, String connectingClassFieldName,
Class secondClass, String createFieldName,
boolean createInFirstClass)
throws Exception {
InterMineObject lastDestObject = null;
Set newCollection = new HashSet();
LOG.info("Beginning insertReferences("
+ firstClass.getName() + ", "
+ firstClassFieldName + ", "
+ connectingClass.getName() + ", "
+ connectingClassFieldName + ","
+ secondClass.getName() + ", "
+ createFieldName + ", "
+ createInFirstClass + ")");
Iterator resIter =
PostProcessUtil.findConnectingClasses(osw.getObjectStore(),
firstClass, firstClassFieldName,
connectingClass, connectingClassFieldName,
secondClass, createInFirstClass);
// results will be firstClass ; destClass (ordered by firstClass)
osw.beginTransaction();
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
InterMineObject thisSourceObject;
InterMineObject thisDestObject;
if (createInFirstClass) {
thisDestObject = (InterMineObject) rr.get(0);
thisSourceObject = (InterMineObject) rr.get(1);
} else {
thisDestObject = (InterMineObject) rr.get(1);
thisSourceObject = (InterMineObject) rr.get(0);;
}
if (lastDestObject == null
|| !thisDestObject.getId().equals(lastDestObject.getId())) {
if (lastDestObject != null) {
try {
InterMineObject tempObject =
PostProcessUtil.cloneInterMineObject(lastDestObject);
Set oldCollection = (Set) TypeUtil.getFieldValue(tempObject,
createFieldName);
newCollection.addAll(oldCollection);
TypeUtil.setFieldValue(tempObject, createFieldName, newCollection);
count += newCollection.size();
osw.store(tempObject);
} catch (IllegalAccessException e) {
LOG.error("Object with ID: " + thisDestObject.getId()
+ " has no " + createFieldName + " field");
}
}
newCollection = new HashSet();
}
newCollection.add(thisSourceObject);
lastDestObject = thisDestObject;
}
if (lastDestObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastDestObject);
TypeUtil.setFieldValue(tempObject, createFieldName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
LOG.info("Created " + count + " references in " + secondClass.getName() + " to "
+ firstClass.getName() + " via " + connectingClass.getName());
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(secondClass.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Create specific named collection of a particular Relation type.
* For example Gene.subjects contains Orthologues and other Relations, create collection
* called Gene.orthologues with just Orthologues in (but remain duplicated in Gene.subjects.
* BioEntity.collection1 -> Relation ==> BioEntity.collection2 -> subclass of Relation
* @param thisClass the class of the objects to fill in a collection for
* @param collectionClass the type of Relation in the collection
* @param oldCollectionName the name of the collection to find objects in
* @param newCollectionName the name of the collection to add objects to
* @throws Exception if anything goes wrong
*/
protected void insertReferences(Class thisClass, Class collectionClass,
String oldCollectionName, String newCollectionName)
throws Exception {
LOG.info("Beginning insertReferences(" + thisClass.getName() + ", "
+ collectionClass.getName() + ", " + oldCollectionName + ", "
+ newCollectionName + ")");
InterMineObject lastObject = null;
Set newCollection = new HashSet();
Iterator resIter = PostProcessUtil.findConnectedClasses(osw.getObjectStore(), thisClass,
collectionClass, oldCollectionName);
// results will be: thisClass ; collectionClass (ordered by thisClass)
osw.beginTransaction();
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
InterMineObject thisObject = (InterMineObject) rr.get(0);
InterMineObject collectionObject = (InterMineObject) rr.get(1);
if (lastObject == null || !thisObject.getId().equals(lastObject.getId())) {
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, newCollectionName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
newCollection = new HashSet();
}
newCollection.add(collectionObject);
lastObject = thisObject;
}
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, newCollectionName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
LOG.info("Created " + count + " " + newCollectionName + " collections in "
+ thisClass.getName() + " of " + collectionClass.getName());
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(thisClass.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Fill in missing references/collections in model by querying relations
* BioEntity -> Annotation -> BioProperty ==> BioEntity -> BioProperty
* @param entityClass the class of the objects to which the collection will be added
* @param propertyClass the class of the BioProperty to transkfer
* @param newCollectionName the collection in entityClass to add objects to
* @throws Exception if anything goes wrong
*/
protected void insertReferences(Class entityClass, Class propertyClass,
String newCollectionName)
throws Exception {
LOG.info("Beginning insertReferences(" + entityClass.getName() + ", "
+ propertyClass.getName() + ", " + newCollectionName + ")");
InterMineObject lastObject = null;
Set newCollection = new HashSet();
Iterator resIter = PostProcessUtil.findProperties(osw.getObjectStore(), entityClass,
propertyClass);
// results will be: entityClass ; properyClass (ordered by entityClass)
osw.beginTransaction();
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
InterMineObject thisObject = (InterMineObject) rr.get(0);
InterMineObject thisProperty = (InterMineObject) rr.get(1);
if (lastObject == null || !thisObject.getId().equals(lastObject.getId())) {
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, newCollectionName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
newCollection = new HashSet();
}
newCollection.add(thisProperty);
lastObject = thisObject;
}
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, newCollectionName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
LOG.info("Created " + count + " " + newCollectionName + " collections in "
+ entityClass.getName() + " of " + propertyClass.getName());
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(entityClass.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Set the collection in objectClass by the name of collectionFieldName by querying for pairs of
* objects in the bioEntities collection of relationClass (which should be a
* SymmetricalRelation).
* @param objectClass the class of the objects to which the collection will be added and which
* should be in the bioEntities collection of the relationClass
* @param relationClass the class that relates objectClass objects togeather
* @param collectionFieldName if there is a collection other than bioEntities which is available
* @throws Exception if anything goes wrong
*/
protected void insertSymmetricalRelationReferences(
Class objectClass, Class relationClass, String collectionFieldName)
throws Exception {
LOG.info("Beginning insertSymmetricalReferences(" + objectClass.getName() + ", "
+ relationClass.getName() + ", "
+ collectionFieldName + ")");
InterMineObject lastObject = null;
Set newCollection = new HashSet();
// results will be: object1, relation, object2 (ordered by object1)
Iterator resIter =
PostProcessUtil.findSymmetricalRelation(
osw.getObjectStore(), objectClass, relationClass);
osw.beginTransaction();
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
BioEntity object1 = (BioEntity) rr.get(0);
SymmetricalRelation relation = (SymmetricalRelation) rr.get(1);
BioEntity object2 = (BioEntity) rr.get(2);
if (lastObject == null || !object1.getId().equals(lastObject.getId())) {
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, collectionFieldName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
newCollection = new HashSet();
}
if (!object1.getId().equals(object2.getId())) {
// don't add the object to its own collection
newCollection.add(object2);
}
lastObject = object1;
}
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, collectionFieldName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
LOG.info("Created " + count + " references in " + objectClass.getName() + " to "
+ objectClass.getName() + " via the " + collectionFieldName + " field");
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(objectClass.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Copy all GO annotations from the Protein objects to the corresponding Gene(s)
* @throws Exception if anything goes wrong
*/
protected void insertGeneAnnotationReferences()
throws Exception {
LOG.debug("Beginning insertGeneAnnotationReferences()");
osw.beginTransaction();
Iterator resIter = findProteinProperties(true);
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Gene thisGene = (Gene) rr.get(0);
Annotation thisAnnotation = (Annotation) rr.get(1);
Annotation tempAnnotation =
(Annotation) PostProcessUtil.cloneInterMineObject(thisAnnotation);
// generate a new ID
tempAnnotation.setId(null);
tempAnnotation.setSubject(thisGene);
osw.store(tempAnnotation);
count++;
}
LOG.debug("Created " + count + " new Annotations on Genes");
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(Annotation.class.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Creates a collection of MicroArrayResult objects on Genes.
* @throws Exception if anything goes wrong
*/
protected void createMicroArrayResultsCollection() throws Exception {
Query q = new Query();
q.setDistinct(false);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryClass qcGene = new QueryClass(Gene.class);
q.addFrom(qcGene);
q.addToSelect(qcGene);
q.addToOrderBy(qcGene);
QueryClass qcCDNAClone = new QueryClass(CDNAClone.class);
q.addFrom(qcCDNAClone);
q.addToSelect(qcCDNAClone);
q.addToOrderBy(qcCDNAClone);
QueryCollectionReference geneClones =
new QueryCollectionReference(qcGene, "clones");
ContainsConstraint ccGeneClones =
new ContainsConstraint(geneClones, ConstraintOp.CONTAINS, qcCDNAClone);
cs.addConstraint(ccGeneClones);
QueryClass qcResult = new QueryClass(MicroArrayResult.class);
q.addFrom(qcResult);
q.addToSelect(qcResult);
q.addToOrderBy(qcResult);
QueryCollectionReference cloneResults =
new QueryCollectionReference(qcCDNAClone, "results");
ContainsConstraint ccCloneResults =
new ContainsConstraint(cloneResults, ConstraintOp.CONTAINS, qcResult);
cs.addConstraint(ccCloneResults);
q.setConstraint(cs);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
int count = 0;
Gene lastGene = null;
Set newCollection = new HashSet();
osw.beginTransaction();
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Gene thisGene = (Gene) rr.get(0);
MicroArrayResult maResult = (MicroArrayResult) rr.get(2);
if (lastGene == null || !thisGene.getId().equals(lastGene.getId())) {
if (lastGene != null) {
// clone so we don't change the ObjectStore cache
Gene tempGene = (Gene) PostProcessUtil.cloneInterMineObject(lastGene);
TypeUtil.setFieldValue(tempGene, "microArrayResults", newCollection);
osw.store(tempGene);
count++;
}
newCollection = new HashSet();
}
newCollection.add(maResult);
lastGene = thisGene;
}
if (lastGene != null) {
// clone so we don't change the ObjectStore cache
Gene tempGene = (Gene) PostProcessUtil.cloneInterMineObject(lastGene);
TypeUtil.setFieldValue(tempGene, "microArrayResults", newCollection);
osw.store(tempGene);
count++;
}
LOG.info("Created " + count + " Gene.microArrayResults collections");
osw.commitTransaction();
// now ANALYSE tables relating to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(Gene.class.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Creates a collection of MicroArrayResult objects on CDNAClone.
* @throws Exception if anything goes wrong
*/
protected void createCDNACloneResultsCollection() throws Exception {
Query q = new Query();
q.setDistinct(false);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryClass qcCDNAClone = new QueryClass(CDNAClone.class);
q.addFrom(qcCDNAClone);
q.addToSelect(qcCDNAClone);
q.addToOrderBy(qcCDNAClone);
QueryClass qcReporter = new QueryClass(Reporter.class);
q.addFrom(qcReporter);
q.addToSelect(qcReporter);
q.addToOrderBy(qcReporter);
QueryObjectReference reporterMaterial =
new QueryObjectReference(qcReporter, "material");
ContainsConstraint ccReporterMaterial =
new ContainsConstraint(reporterMaterial, ConstraintOp.CONTAINS, qcCDNAClone);
cs.addConstraint(ccReporterMaterial);
QueryClass qcResult = new QueryClass(MicroArrayResult.class);
q.addFrom(qcResult);
q.addToSelect(qcResult);
q.addToOrderBy(qcResult);
QueryCollectionReference reporterResults =
new QueryCollectionReference(qcReporter, "results");
ContainsConstraint ccReporterResults =
new ContainsConstraint(reporterResults, ConstraintOp.CONTAINS, qcResult);
cs.addConstraint(ccReporterResults);
q.setConstraint(cs);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
int count = 0;
CDNAClone lastClone = null;
Set newCollection = new HashSet();
osw.beginTransaction();
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
CDNAClone thisClone = (CDNAClone) rr.get(0);
MicroArrayResult maResult = (MicroArrayResult) rr.get(2);
if (lastClone == null || !thisClone.getId().equals(lastClone.getId())) {
if (lastClone != null) {
// clone so we don't change the ObjectStore cache
CDNAClone tempClone = (CDNAClone) PostProcessUtil
.cloneInterMineObject(lastClone);
TypeUtil.setFieldValue(tempClone, "results", newCollection);
osw.store(tempClone);
count++;
}
newCollection = new HashSet();
}
newCollection.add(maResult);
lastClone = thisClone;
}
if (lastClone != null) {
// clone so we don't change the ObjectStore cache
CDNAClone tempClone = (CDNAClone) PostProcessUtil.cloneInterMineObject(lastClone);
TypeUtil.setFieldValue(tempClone, "results", newCollection);
osw.store(tempClone);
count++;
}
LOG.info("Created " + count + " CDNAClone.results collections");
osw.commitTransaction();
// now ANALYSE tables relating to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(CDNAClone.class.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Creates a collection of MicroArrayResult objects on CompositeSequence.
* @throws Exception if anything goes wrong
*/
protected void createCompositeSeqResultsCollection() throws Exception {
Query q = new Query();
q.setDistinct(false);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryClass qcCompositeSeq = new QueryClass(CompositeSequence.class);
q.addFrom(qcCompositeSeq);
q.addToSelect(qcCompositeSeq);
q.addToOrderBy(qcCompositeSeq);
QueryClass qcReporter = new QueryClass(Reporter.class);
q.addFrom(qcReporter);
q.addToSelect(qcReporter);
q.addToOrderBy(qcReporter);
QueryObjectReference reporterMaterial =
new QueryObjectReference(qcReporter, "material");
ContainsConstraint ccReporterMaterial =
new ContainsConstraint(reporterMaterial, ConstraintOp.CONTAINS, qcCompositeSeq);
cs.addConstraint(ccReporterMaterial);
QueryClass qcResult = new QueryClass(MicroArrayResult.class);
q.addFrom(qcResult);
q.addToSelect(qcResult);
q.addToOrderBy(qcResult);
QueryCollectionReference reporterResults =
new QueryCollectionReference(qcReporter, "results");
ContainsConstraint ccReporterResults =
new ContainsConstraint(reporterResults, ConstraintOp.CONTAINS, qcResult);
cs.addConstraint(ccReporterResults);
q.setConstraint(cs);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
int count = 0;
CompositeSequence lastComSeq = null;
Set newCollection = new HashSet();
osw.beginTransaction();
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
CompositeSequence thisComSeq = (CompositeSequence) rr.get(0);
MicroArrayResult maResult = (MicroArrayResult) rr.get(2);
if (lastComSeq == null || !thisComSeq.getId().equals(lastComSeq.getId())) {
if (lastComSeq != null) {
// clone so we don't change the ObjectStore cache
CompositeSequence tempComSeq = (CompositeSequence) PostProcessUtil
.cloneInterMineObject(lastComSeq);
TypeUtil.setFieldValue(tempComSeq, "results", newCollection);
osw.store(tempComSeq);
count++;
}
newCollection = new HashSet();
}
newCollection.add(maResult);
lastComSeq = thisComSeq;
}
if (lastComSeq != null) {
// clone so we don't change the ObjectStore cache
CompositeSequence tempComSeq = (CompositeSequence) PostProcessUtil.cloneInterMineObject(lastComSeq);
TypeUtil.setFieldValue(tempComSeq, "results", newCollection);
osw.store(tempComSeq);
count++;
}
LOG.info("Created " + count + " CompositeSequence.results collections");
osw.commitTransaction();
// now ANALYSE tables relating to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(CompositeSequence.class.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Read the UTRs collection of MRNA then set the fivePrimeUTR and threePrimeUTR fields with the
* corresponding UTRs.
* @throws Exception if anything goes wrong
*/
protected void createUtrRefs() throws Exception {
Query q = new Query();
q.setDistinct(false);
QueryClass qcMRNA = new QueryClass(MRNA.class);
q.addFrom(qcMRNA);
q.addToSelect(qcMRNA);
q.addToOrderBy(qcMRNA);
QueryClass qcUTR = new QueryClass(UTR.class);
q.addFrom(qcUTR);
q.addToSelect(qcUTR);
q.addToOrderBy(qcUTR);
QueryCollectionReference mrnaUtrsRef =
new QueryCollectionReference(qcMRNA, "UTRs");
ContainsConstraint mrnaUtrsConstraint =
new ContainsConstraint(mrnaUtrsRef, ConstraintOp.CONTAINS, qcUTR);
q.setConstraint(mrnaUtrsConstraint);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
int count = 0;
MRNA lastMRNA = null;
FivePrimeUTR fivePrimeUTR = null;
ThreePrimeUTR threePrimeUTR = null;
osw.beginTransaction();
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
MRNA mrna = (MRNA) rr.get(0);
UTR utr = (UTR) rr.get(1);
if (lastMRNA != null && !mrna.getId().equals(lastMRNA.getId())) {
// clone so we don't change the ObjectStore cache
MRNA tempMRNA = (MRNA) PostProcessUtil.cloneInterMineObject(lastMRNA);
if (fivePrimeUTR != null) {
TypeUtil.setFieldValue(tempMRNA, "fivePrimeUTR", fivePrimeUTR);
fivePrimeUTR = null;
}
if (threePrimeUTR != null) {
TypeUtil.setFieldValue(tempMRNA, "threePrimeUTR", threePrimeUTR);
threePrimeUTR = null;
}
osw.store(tempMRNA);
count++;
}
if (utr instanceof FivePrimeUTR) {
fivePrimeUTR = (FivePrimeUTR) utr;
} else {
threePrimeUTR = (ThreePrimeUTR) utr;
}
lastMRNA = mrna;
}
if (lastMRNA != null) {
// clone so we don't change the ObjectStore cache
MRNA tempMRNA = (MRNA) PostProcessUtil.cloneInterMineObject(lastMRNA);
TypeUtil.setFieldValue(tempMRNA, "fivePrimeUTR", fivePrimeUTR);
TypeUtil.setFieldValue(tempMRNA, "threePrimeUTR", threePrimeUTR);
osw.store(tempMRNA);
count++;
}
LOG.info("Stored MRNA " + count + " times (" + count * 2 + " fields set)");
osw.commitTransaction();
// now ANALYSE tables relating to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(MRNA.class.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Query Gene->Protein->Annotation->GOTerm and return an iterator over the Gene,
* Protein and GOTerm.
*
* @param restrictToPrimaryGoTermsOnly Only get primary Annotation items linking the gene
* and the go term.
*/
private Iterator findProteinProperties(boolean restrictToPrimaryGoTermsOnly) throws Exception {
Query q = new Query();
q.setDistinct(false);
QueryClass qcGene = new QueryClass(Gene.class);
q.addFrom(qcGene);
q.addToSelect(qcGene);
q.addToOrderBy(qcGene);
QueryClass qcProtein = new QueryClass(Protein.class);
q.addFrom(qcProtein);
QueryClass qcAnnotation = null;
if (restrictToPrimaryGoTermsOnly) {
qcAnnotation = new QueryClass(GOAnnotation.class);
q.addFrom(qcAnnotation);
q.addToSelect(qcAnnotation);
} else {
qcAnnotation = new QueryClass(Annotation.class);
q.addFrom(qcAnnotation);
q.addToSelect(qcAnnotation);
}
QueryClass qcGOTerm = new QueryClass(GOTerm.class);
q.addFrom(qcGOTerm);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference geneProtRef = new QueryCollectionReference(qcProtein, "genes");
ContainsConstraint geneProtConstraint =
new ContainsConstraint(geneProtRef, ConstraintOp.CONTAINS, qcGene);
cs.addConstraint(geneProtConstraint);
QueryCollectionReference protAnnRef =
new QueryCollectionReference(qcProtein, "annotations");
ContainsConstraint protAnnConstraint =
new ContainsConstraint(protAnnRef, ConstraintOp.CONTAINS, qcAnnotation);
cs.addConstraint(protAnnConstraint);
QueryObjectReference annPropertyRef =
new QueryObjectReference(qcAnnotation, "property");
ContainsConstraint annPropertyConstraint =
new ContainsConstraint(annPropertyRef, ConstraintOp.CONTAINS, qcGOTerm);
cs.addConstraint(annPropertyConstraint);
if (restrictToPrimaryGoTermsOnly) {
QueryField isPrimaryTermQueryField =
new QueryField(qcAnnotation, "isPrimaryAssignment");
QueryValue trueValue = new QueryValue(Boolean.TRUE);
SimpleConstraint primeConst =
new SimpleConstraint(isPrimaryTermQueryField, ConstraintOp.EQUALS, trueValue);
cs.addConstraint(primeConst);
}
q.setConstraint(cs);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
return res.iterator();
}
/**
* Performs the business of linking Proteins to ProteinInteractions as well as other proteins
* that are related back to the protein via the interaction object.
*
* @throws Exception - if there is a problem...
* */
public void linkProteinToProtenInteractionAndRelatedProteins() throws Exception {
Query q = new Query();
q.setDistinct(false);
QueryClass proteinQC = new QueryClass(Protein.class);
q.addToSelect(proteinQC);
q.addFrom(proteinQC);
q.addToOrderBy(proteinQC);
QueryClass interactorQC = new QueryClass(ProteinInteractor.class);
q.addFrom(interactorQC);
QueryClass interactionQC = new QueryClass(ProteinInteraction.class);
q.addToSelect(interactionQC);
q.addFrom(interactionQC);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference proteinToInteractorRef =
new QueryCollectionReference(proteinQC, "interactionRoles");
ContainsConstraint proteinInteractorConstraint =
new ContainsConstraint(proteinToInteractorRef, ConstraintOp.CONTAINS, interactorQC);
cs.addConstraint(proteinInteractorConstraint);
QueryCollectionReference interactionToInteractorRef =
new QueryCollectionReference(interactionQC, "interactors");
ContainsConstraint interactionInteractorConstraint =
new ContainsConstraint(interactionToInteractorRef,
ConstraintOp.CONTAINS, interactorQC);
cs.addConstraint(interactionInteractorConstraint);
q.setConstraint(cs);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
HashMap proteinToInteractionsMap = new HashMap();
HashMap interactionToProteinsMap = new HashMap();
LOG.debug("CHECKING linkProteinToProtenInteractionAndRelatedProteins RESULTS");
for (Iterator resIter = res.iterator(); resIter.hasNext();) {
ResultsRow rr = (ResultsRow) resIter.next();
Protein protein = (Protein) rr.get(0);
ProteinInteraction interaction = (ProteinInteraction) rr.get(1);
addProteinAndInterationPairToMap(protein, interaction, proteinToInteractionsMap, true);
addProteinAndInterationPairToMap(protein, interaction, interactionToProteinsMap, false);
LOG.debug("PROTEIN:" + protein.getPrimaryAccession()
+ " -> INTERACTION:" + interaction.getShortName());
}
osw.beginTransaction();
LOG.debug("Setting values for interaction.proteins");
for (Iterator i2pIt = interactionToProteinsMap.keySet().iterator(); i2pIt.hasNext();) {
ProteinInteraction nextInteraction = (ProteinInteraction) i2pIt.next();
Set nextProteinSet = (Set) interactionToProteinsMap.get(nextInteraction);
nextInteraction.setProteins(nextProteinSet);
osw.store(nextInteraction);
LOG.debug("INTERACTION:" + nextInteraction.getShortName()
+ " HAS THIS MANY PROTEINS:" + nextProteinSet.size());
}
LOG.debug("Setting values for protein.proteinInteractions");
for (Iterator p2iIt = proteinToInteractionsMap.keySet().iterator(); p2iIt.hasNext();) {
Protein nextProtein = (Protein) p2iIt.next();
Set nextInteractionSet = (Set) proteinToInteractionsMap.get(nextProtein);
nextProtein.setProteinInteractions(nextInteractionSet);
//Don't store the proteins here as we still have work to do on them
LOG.debug("PROTEIN:" + nextProtein.getPrimaryAccession()
+ " HAS THIS MANY INTERACTIONS:" + nextInteractionSet.size());
}
LOG.debug("Setting values for protein.interactingProteins");
for (Iterator p2iIt2 = proteinToInteractionsMap.keySet().iterator(); p2iIt2.hasNext();) {
Protein nextProtein = (Protein) p2iIt2.next();
Set interactingProteinSet = new HashSet();
//Explicitly add the starting protein so we can remove it blindly later.
interactingProteinSet.add(nextProtein);
Set nextInteractionSet = (Set) proteinToInteractionsMap.get(nextProtein);
for (Iterator iIt = nextInteractionSet.iterator(); iIt.hasNext(); ) {
ProteinInteraction nextInteraction = (ProteinInteraction) iIt.next();
Set nextInteractingProteinSet = (Set) interactionToProteinsMap.get(nextInteraction);
interactingProteinSet.addAll(nextInteractingProteinSet);
}
//TODO: DO WE WANT TO ADD/REMOVE SELF REFS ? I.E. WHERE A PROTEIN INTERACTS WITH ITSELF
//Explictly remove the starting protein so it wont refer to itself - for the moment!.
interactingProteinSet.remove(nextProtein);
nextProtein.setInteractingProteins(interactingProteinSet);
osw.store(nextProtein);
LOG.debug("PROTEIN:" + nextProtein.getPrimaryAccession()
+ " HAS THIS MANY RELATED PROTEINS:" + interactingProteinSet.size());
}
osw.commitTransaction();
}
/**
* Little helper method for the linkProteinToProtenInteractionAndRelatedProteins method.
*
* @param protein - a protein
* @param interaction - an interaction the protein appeared in
* @param map - either a protein-interactions map or vice versa
* @param useProteinAsTheKey - a boolean indicating which sort of map we have to deal with
* */
private void addProteinAndInterationPairToMap(Protein protein, ProteinInteraction interaction,
HashMap map, boolean useProteinAsTheKey) {
//Treat the protein as the key
if (useProteinAsTheKey) {
if (map.containsKey(protein)) {
Set interactionSet = (Set) map.get(protein);
interactionSet.add(interaction);
} else {
Set newInteractionSet = new HashSet();
newInteractionSet.add(interaction);
map.put(protein, newInteractionSet);
}
//Treat the interaction as the key
} else {
if (map.containsKey(interaction)) {
Set proteinSet = (Set) map.get(interaction);
proteinSet.add(protein);
} else {
Set newProteinSet = new HashSet();
newProteinSet.add(protein);
map.put(interaction, newProteinSet);
}
}
}
}
| flymine/model/genomic/src/java/org/flymine/postprocess/CreateReferences.java | package org.flymine.postprocess;
/*
* Copyright (C) 2002-2005 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.HashMap;
import org.intermine.objectstore.query.*;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStore;
import org.intermine.sql.Database;
import org.intermine.metadata.Model;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.model.InterMineObject;
import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.util.DatabaseUtil;
import org.intermine.util.TypeUtil;
import org.flymine.model.genomic.*;
import org.apache.log4j.Logger;
/**
* Fill in additional references/collections in genomic model
*
* @author Richard Smith
* @author Kim Rutherford
*/
public class CreateReferences
{
private static final Logger LOG = Logger.getLogger(CreateReferences.class);
protected ObjectStoreWriter osw;
private Model model;
/**
* Construct with an ObjectStoreWriter, read and write from same ObjectStore
* @param osw an ObjectStore to write to
*/
public CreateReferences(ObjectStoreWriter osw) {
this.osw = osw;
this.model = Model.getInstanceByName("genomic");
}
/**
* Fill in missing references/collections in model by querying relations
* @throws Exception if anything goes wrong
*/
public void insertReferences() throws Exception {
LOG.info("insertReferences stage 1");
// Transcript.exons / Exon.transcripts
insertCollectionField(Transcript.class, "subjects", RankedRelation.class, "subject",
Exon.class, "transcripts", false);
insertCollectionField(Transcript.class, "subjects", SimpleRelation.class, "subject",
Exon.class, "transcripts", false);
// Intron.MRNAs / MRNA.introns
insertCollectionField(Transcript.class, "subjects", SimpleRelation.class, "subject",
Intron.class, "introns", true);
insertCollectionField(Transcript.class, "subjects", SimpleRelation.class, "subject",
Exon.class, "exons", true);
LOG.info("insertReferences stage 2");
// Gene.transcript / Transcript.gene
insertReferenceField(Gene.class, "subjects", SimpleRelation.class, "subject",
Transcript.class, "gene");
LOG.info("insertReferences stage 3");
insertReferenceField(Chromosome.class, "subjects", Location.class, "subject",
LocatedSequenceFeature.class, "chromosome");
LOG.info("insertReferences stage 4");
// fill in collections on Chromosome
insertCollectionField(Gene.class, "objects", Location.class, "object",
Chromosome.class, "genes", false);
insertCollectionField(Transcript.class, "objects", Location.class, "object",
Chromosome.class, "transcripts", false);
insertCollectionField(Exon.class, "objects", Location.class, "object",
Chromosome.class, "exons", false);
insertCollectionField(ChromosomeBand.class, "subjects", Location.class, "subject",
Chromosome.class, "chromosomeBands", false);
LOG.info("insertReferences stage 5");
// Exon.gene / Gene.exons
insertReferenceField(Gene.class, "transcripts", Transcript.class, "exons",
Exon.class, "gene");
LOG.info("insertReferences stage 6");
// UTR.gene / Gene.UTRs
insertReferenceField(Gene.class, "transcripts", MRNA.class, "UTRs",
UTR.class, "gene");
LOG.info("insertReferences stage 7");
// Gene.chromosome / Chromosome.genes
insertReferenceField(Chromosome.class, "exons", Exon.class, "gene",
Gene.class, "chromosome");
LOG.info("insertReferences stage 8");
// Transcript.chromosome / Chromosome.transcripts
insertReferenceField(Chromosome.class, "exons", Exon.class, "transcripts",
Transcript.class, "chromosome");
LOG.info("insertReferences stage 9");
// Protein.genes / Gene.proteins
insertCollectionField(Gene.class, "transcripts", Transcript.class, "protein",
Protein.class, "genes", false);
// CDS.gene / Gene.CDSs
insertReferenceField(Gene.class, "transcripts", MRNA.class, "CDSs",
CDS.class, "gene");
LOG.info("insertReferences stage 10");
insertReferenceField(Gene.class, "CDSs", CDS.class, "polypeptides",
Translation.class, "gene");
LOG.info("insertReferences stage 11");
insertReferenceField(Translation.class, "CDSs", CDS.class, "MRNAs",
MRNA.class, "translation");
LOG.info("insertReferences stage 12");
// Gene.CDSs.polypeptides
insertReferenceField(MRNA.class, "CDSs", CDS.class, "polypeptides",
Translation.class, "transcript");
ObjectStore os = osw.getObjectStore();
if (os instanceof ObjectStoreInterMineImpl) {
Database db = ((ObjectStoreInterMineImpl) os).getDatabase();
DatabaseUtil.analyse(db, false);
}
LOG.info("insertReferences stage 13");
insertGeneAnnotationReferences();
if (os instanceof ObjectStoreInterMineImpl) {
Database db = ((ObjectStoreInterMineImpl) os).getDatabase();
DatabaseUtil.analyse(db, false);
}
LOG.info("insertReferences stage 14");
// Gene.phenotypes
insertReferences(Gene.class, Phenotype.class, "phenotypes");
// CDNAClone.results (MicroArrayResult)
createCDNACloneResultsCollection();
LOG.info("insertReferences stage 15");
// Gene.microArrayResults
createMicroArrayResultsCollection();
LOG.info("insertReferences stage 16");
createUtrRefs();
if (os instanceof ObjectStoreInterMineImpl) {
Database db = ((ObjectStoreInterMineImpl) os).getDatabase();
DatabaseUtil.analyse(db, false);
}
}
/**
* Fill in missing references/collections in model by querying SymmetricalRelations
* @throws Exception if anything goes wrong
*/
public void insertSymmetricalRelationReferences() throws Exception {
LOG.info("insertReferences stage 1");
// Transcript.exons / Exon.transcripts
insertSymmetricalRelationReferences(
LocatedSequenceFeature.class, OverlapRelation.class, "overlappingFeatures"
);
}
/**
* Fill in the "orthologues" collection of Gene. Needs to be run after
* UpdateOrthologues which in turn relies on CreateReferences -> so has
* become a separate method.
* @throws Exception if anything goes wrong
*/
public void populateOrthologuesCollection() throws Exception {
insertReferences(Gene.class, Orthologue.class, "subjects", "orthologues");
}
/**
* Add a reference to and object of type X in objects of type Y by using a connecting class.
* Eg. Add a reference to Gene objects in Exon by examining the Transcript objects in the
* transcripts collection of the Gene, which would use a query like:
* SELECT DISTINCT gene FROM Gene AS gene, Transcript AS transcript, Exon AS exon WHERE
* (gene.transcripts CONTAINS transcript AND transcript.exons CONTAINS exon) ORDER BY gene
* and then set exon.gene
*
* in overview we are doing:
* BioEntity1 -> BioEntity2 -> BioEntity3 ==> BioEntitiy1 -> BioEntity3
* @param sourceClass the first class in the query
* @param sourceClassFieldName the field in the sourceClass which should contain the
* connectingClass
* @param connectingClass the class referred to by sourceClass.sourceFieldName
* @param connectingClassFieldName the field in connectingClass which should contain
* destinationClass
* @param destinationClass the class referred to by
* connectingClass.connectingClassFieldName
* @param createFieldName the reference field in the destinationClass - the
* collection to create/set
* @throws Exception if anything goes wrong
*/
protected void insertReferenceField(Class sourceClass, String sourceClassFieldName,
Class connectingClass, String connectingClassFieldName,
Class destinationClass, String createFieldName)
throws Exception {
LOG.info("Beginning insertReferences("
+ sourceClass.getName() + ", "
+ sourceClassFieldName + ", "
+ connectingClass.getName() + ", "
+ connectingClassFieldName + ","
+ destinationClass.getName() + ", "
+ createFieldName + ")");
Iterator resIter =
PostProcessUtil.findConnectingClasses(osw.getObjectStore(),
sourceClass, sourceClassFieldName,
connectingClass, connectingClassFieldName,
destinationClass, true);
// results will be sourceClass ; destClass (ordered by sourceClass)
osw.beginTransaction();
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
InterMineObject thisSourceObject = (InterMineObject) rr.get(0);
InterMineObject thisDestObject = (InterMineObject) rr.get(1);
try {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(thisDestObject);
TypeUtil.setFieldValue(tempObject, createFieldName, thisSourceObject);
count++;
if (count % 10000 == 0) {
LOG.info("Created " + count + " references in " + destinationClass.getName()
+ " to " + sourceClass.getName()
+ " via " + connectingClass.getName());
}
osw.store(tempObject);
} catch (IllegalAccessException e) {
LOG.error("Object with ID: " + thisDestObject.getId()
+ " has no " + createFieldName + " field");
}
}
LOG.info("Finished: created " + count + " references in " + destinationClass.getName()
+ " to " + sourceClass.getName() + " via " + connectingClass.getName());
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(destinationClass.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Add a collection of objects of type X to objects of type Y by using a connecting class.
* Eg. Add a collection of Protein objects to Gene by examining the Transcript objects in the
* transcripts collection of the Gene, which would use a query like:
* SELECT DISTINCT gene FROM Gene AS gene, Transcript AS transcript, Protein AS protein WHERE
* (gene.transcripts CONTAINS transcript AND transcript.protein CONTAINS protein)
* ORDER BY gene
* and then set protected gene.protein (if created
* BioEntity1 -> BioEntity2 -> BioEntity3 ==> BioEntity1 -> BioEntity3
* @param firstClass the first class in the query
* @param firstClassFieldName the field in the firstClass which should contain the
* connectingClass
* @param connectingClass the class referred to by firstClass.sourceFieldName
* @param connectingClassFieldName the field in connectingClass which should contain
* secondClass
* @param secondClass the class referred to by
* connectingClass.connectingClassFieldName
* @param createFieldName the collection field in the secondClass - the
* collection to create/set
* @param createInFirstClass if true create the new collection field in firstClass, otherwise
* create in secondClass
* @throws Exception if anything goes wrong
*/
protected void insertCollectionField(Class firstClass, String firstClassFieldName,
Class connectingClass, String connectingClassFieldName,
Class secondClass, String createFieldName,
boolean createInFirstClass)
throws Exception {
InterMineObject lastDestObject = null;
Set newCollection = new HashSet();
LOG.info("Beginning insertReferences("
+ firstClass.getName() + ", "
+ firstClassFieldName + ", "
+ connectingClass.getName() + ", "
+ connectingClassFieldName + ","
+ secondClass.getName() + ", "
+ createFieldName + ", "
+ createInFirstClass + ")");
Iterator resIter =
PostProcessUtil.findConnectingClasses(osw.getObjectStore(),
firstClass, firstClassFieldName,
connectingClass, connectingClassFieldName,
secondClass, createInFirstClass);
// results will be firstClass ; destClass (ordered by firstClass)
osw.beginTransaction();
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
InterMineObject thisSourceObject;
InterMineObject thisDestObject;
if (createInFirstClass) {
thisDestObject = (InterMineObject) rr.get(0);
thisSourceObject = (InterMineObject) rr.get(1);
} else {
thisDestObject = (InterMineObject) rr.get(1);
thisSourceObject = (InterMineObject) rr.get(0);;
}
if (lastDestObject == null
|| !thisDestObject.getId().equals(lastDestObject.getId())) {
if (lastDestObject != null) {
try {
InterMineObject tempObject =
PostProcessUtil.cloneInterMineObject(lastDestObject);
Set oldCollection = (Set) TypeUtil.getFieldValue(tempObject,
createFieldName);
newCollection.addAll(oldCollection);
TypeUtil.setFieldValue(tempObject, createFieldName, newCollection);
count += newCollection.size();
osw.store(tempObject);
} catch (IllegalAccessException e) {
LOG.error("Object with ID: " + thisDestObject.getId()
+ " has no " + createFieldName + " field");
}
}
newCollection = new HashSet();
}
newCollection.add(thisSourceObject);
lastDestObject = thisDestObject;
}
if (lastDestObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastDestObject);
TypeUtil.setFieldValue(tempObject, createFieldName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
LOG.info("Created " + count + " references in " + secondClass.getName() + " to "
+ firstClass.getName() + " via " + connectingClass.getName());
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(secondClass.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Create specific named collection of a particular Relation type.
* For example Gene.subjects contains Orthologues and other Relations, create collection
* called Gene.orthologues with just Orthologues in (but remain duplicated in Gene.subjects.
* BioEntity.collection1 -> Relation ==> BioEntity.collection2 -> subclass of Relation
* @param thisClass the class of the objects to fill in a collection for
* @param collectionClass the type of Relation in the collection
* @param oldCollectionName the name of the collection to find objects in
* @param newCollectionName the name of the collection to add objects to
* @throws Exception if anything goes wrong
*/
protected void insertReferences(Class thisClass, Class collectionClass,
String oldCollectionName, String newCollectionName)
throws Exception {
LOG.info("Beginning insertReferences(" + thisClass.getName() + ", "
+ collectionClass.getName() + ", " + oldCollectionName + ", "
+ newCollectionName + ")");
InterMineObject lastObject = null;
Set newCollection = new HashSet();
Iterator resIter = PostProcessUtil.findConnectedClasses(osw.getObjectStore(), thisClass,
collectionClass, oldCollectionName);
// results will be: thisClass ; collectionClass (ordered by thisClass)
osw.beginTransaction();
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
InterMineObject thisObject = (InterMineObject) rr.get(0);
InterMineObject collectionObject = (InterMineObject) rr.get(1);
if (lastObject == null || !thisObject.getId().equals(lastObject.getId())) {
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, newCollectionName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
newCollection = new HashSet();
}
newCollection.add(collectionObject);
lastObject = thisObject;
}
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, newCollectionName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
LOG.info("Created " + count + " " + newCollectionName + " collections in "
+ thisClass.getName() + " of " + collectionClass.getName());
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(thisClass.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Fill in missing references/collections in model by querying relations
* BioEntity -> Annotation -> BioProperty ==> BioEntity -> BioProperty
* @param entityClass the class of the objects to which the collection will be added
* @param propertyClass the class of the BioProperty to transkfer
* @param newCollectionName the collection in entityClass to add objects to
* @throws Exception if anything goes wrong
*/
protected void insertReferences(Class entityClass, Class propertyClass,
String newCollectionName)
throws Exception {
LOG.info("Beginning insertReferences(" + entityClass.getName() + ", "
+ propertyClass.getName() + ", " + newCollectionName + ")");
InterMineObject lastObject = null;
Set newCollection = new HashSet();
Iterator resIter = PostProcessUtil.findProperties(osw.getObjectStore(), entityClass,
propertyClass);
// results will be: entityClass ; properyClass (ordered by entityClass)
osw.beginTransaction();
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
InterMineObject thisObject = (InterMineObject) rr.get(0);
InterMineObject thisProperty = (InterMineObject) rr.get(1);
if (lastObject == null || !thisObject.getId().equals(lastObject.getId())) {
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, newCollectionName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
newCollection = new HashSet();
}
newCollection.add(thisProperty);
lastObject = thisObject;
}
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, newCollectionName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
LOG.info("Created " + count + " " + newCollectionName + " collections in "
+ entityClass.getName() + " of " + propertyClass.getName());
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(entityClass.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Set the collection in objectClass by the name of collectionFieldName by querying for pairs of
* objects in the bioEntities collection of relationClass (which should be a
* SymmetricalRelation).
* @param objectClass the class of the objects to which the collection will be added and which
* should be in the bioEntities collection of the relationClass
* @param relationClass the class that relates objectClass objects togeather
* @param collectionFieldName if there is a collection other than bioEntities which is available
* @throws Exception if anything goes wrong
*/
protected void insertSymmetricalRelationReferences(
Class objectClass, Class relationClass, String collectionFieldName)
throws Exception {
LOG.info("Beginning insertSymmetricalReferences(" + objectClass.getName() + ", "
+ relationClass.getName() + ", "
+ collectionFieldName + ")");
InterMineObject lastObject = null;
Set newCollection = new HashSet();
// results will be: object1, relation, object2 (ordered by object1)
Iterator resIter =
PostProcessUtil.findSymmetricalRelation(
osw.getObjectStore(), objectClass, relationClass);
osw.beginTransaction();
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
BioEntity object1 = (BioEntity) rr.get(0);
SymmetricalRelation relation = (SymmetricalRelation) rr.get(1);
BioEntity object2 = (BioEntity) rr.get(2);
if (lastObject == null || !object1.getId().equals(lastObject.getId())) {
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, collectionFieldName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
newCollection = new HashSet();
}
if (!object1.getId().equals(object2.getId())) {
// don't add the object to its own collection
newCollection.add(object2);
}
lastObject = object1;
}
if (lastObject != null) {
// clone so we don't change the ObjectStore cache
InterMineObject tempObject = PostProcessUtil.cloneInterMineObject(lastObject);
TypeUtil.setFieldValue(tempObject, collectionFieldName, newCollection);
count += newCollection.size();
osw.store(tempObject);
}
LOG.info("Created " + count + " references in " + objectClass.getName() + " to "
+ objectClass.getName() + " via the " + collectionFieldName + " field");
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(objectClass.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Copy all GO annotations from the Protein objects to the corresponding Gene(s)
* @throws Exception if anything goes wrong
*/
protected void insertGeneAnnotationReferences()
throws Exception {
LOG.debug("Beginning insertGeneAnnotationReferences()");
osw.beginTransaction();
Iterator resIter = findProteinProperties(true);
int count = 0;
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Gene thisGene = (Gene) rr.get(0);
Annotation thisAnnotation = (Annotation) rr.get(1);
Annotation tempAnnotation =
(Annotation) PostProcessUtil.cloneInterMineObject(thisAnnotation);
// generate a new ID
tempAnnotation.setId(null);
tempAnnotation.setSubject(thisGene);
osw.store(tempAnnotation);
count++;
}
LOG.debug("Created " + count + " new Annotations on Genes");
osw.commitTransaction();
// now ANALYSE tables relation to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(Annotation.class.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Creates a collection of MicroArrayResult objects on Genes.
* @throws Exception if anything goes wrong
*/
protected void createMicroArrayResultsCollection() throws Exception {
Query q = new Query();
q.setDistinct(false);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryClass qcGene = new QueryClass(Gene.class);
q.addFrom(qcGene);
q.addToSelect(qcGene);
q.addToOrderBy(qcGene);
QueryClass qcCDNAClone = new QueryClass(CDNAClone.class);
q.addFrom(qcCDNAClone);
q.addToSelect(qcCDNAClone);
q.addToOrderBy(qcCDNAClone);
QueryCollectionReference geneClones =
new QueryCollectionReference(qcGene, "clones");
ContainsConstraint ccGeneClones =
new ContainsConstraint(geneClones, ConstraintOp.CONTAINS, qcCDNAClone);
cs.addConstraint(ccGeneClones);
QueryClass qcResult = new QueryClass(MicroArrayResult.class);
q.addFrom(qcResult);
q.addToSelect(qcResult);
q.addToOrderBy(qcResult);
QueryCollectionReference cloneResults =
new QueryCollectionReference(qcCDNAClone, "results");
ContainsConstraint ccCloneResults =
new ContainsConstraint(cloneResults, ConstraintOp.CONTAINS, qcResult);
cs.addConstraint(ccCloneResults);
q.setConstraint(cs);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
int count = 0;
Gene lastGene = null;
Set newCollection = new HashSet();
osw.beginTransaction();
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
Gene thisGene = (Gene) rr.get(0);
MicroArrayResult maResult = (MicroArrayResult) rr.get(2);
if (lastGene == null || !thisGene.getId().equals(lastGene.getId())) {
if (lastGene != null) {
// clone so we don't change the ObjectStore cache
Gene tempGene = (Gene) PostProcessUtil.cloneInterMineObject(lastGene);
TypeUtil.setFieldValue(tempGene, "microArrayResults", newCollection);
osw.store(tempGene);
count++;
}
newCollection = new HashSet();
}
newCollection.add(maResult);
lastGene = thisGene;
}
if (lastGene != null) {
// clone so we don't change the ObjectStore cache
Gene tempGene = (Gene) PostProcessUtil.cloneInterMineObject(lastGene);
TypeUtil.setFieldValue(tempGene, "microArrayResults", newCollection);
osw.store(tempGene);
count++;
}
LOG.info("Created " + count + " Gene.microArrayResults collections");
osw.commitTransaction();
// now ANALYSE tables relating to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(Gene.class.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Creates a collection of MicroArrayResult objects on Genes.
* @throws Exception if anything goes wrong
*/
protected void createCDNACloneResultsCollection() throws Exception {
Query q = new Query();
q.setDistinct(false);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryClass qcCDNAClone = new QueryClass(CDNAClone.class);
q.addFrom(qcCDNAClone);
q.addToSelect(qcCDNAClone);
q.addToOrderBy(qcCDNAClone);
QueryClass qcReporter = new QueryClass(Reporter.class);
q.addFrom(qcReporter);
q.addToSelect(qcReporter);
q.addToOrderBy(qcReporter);
QueryObjectReference reporterMaterial =
new QueryObjectReference(qcReporter, "material");
ContainsConstraint ccReporterMaterial =
new ContainsConstraint(reporterMaterial, ConstraintOp.CONTAINS, qcCDNAClone);
cs.addConstraint(ccReporterMaterial);
QueryClass qcResult = new QueryClass(MicroArrayResult.class);
q.addFrom(qcResult);
q.addToSelect(qcResult);
q.addToOrderBy(qcResult);
QueryCollectionReference reporterResults =
new QueryCollectionReference(qcReporter, "results");
ContainsConstraint ccReporterResults =
new ContainsConstraint(reporterResults, ConstraintOp.CONTAINS, qcResult);
cs.addConstraint(ccReporterResults);
q.setConstraint(cs);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
int count = 0;
CDNAClone lastClone = null;
Set newCollection = new HashSet();
osw.beginTransaction();
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
CDNAClone thisClone = (CDNAClone) rr.get(0);
MicroArrayResult maResult = (MicroArrayResult) rr.get(2);
if (lastClone == null || !thisClone.getId().equals(lastClone.getId())) {
if (lastClone != null) {
// clone so we don't change the ObjectStore cache
CDNAClone tempClone = (CDNAClone) PostProcessUtil
.cloneInterMineObject(lastClone);
TypeUtil.setFieldValue(tempClone, "results", newCollection);
osw.store(tempClone);
count++;
}
newCollection = new HashSet();
}
newCollection.add(maResult);
lastClone = thisClone;
}
if (lastClone != null) {
// clone so we don't change the ObjectStore cache
CDNAClone tempClone = (CDNAClone) PostProcessUtil.cloneInterMineObject(lastClone);
TypeUtil.setFieldValue(tempClone, "results", newCollection);
osw.store(tempClone);
count++;
}
LOG.info("Created " + count + " CDNAClone.results collections");
osw.commitTransaction();
// now ANALYSE tables relating to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(CDNAClone.class.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Read the UTRs collection of MRNA then set the fivePrimeUTR and threePrimeUTR fields with the
* corresponding UTRs.
* @throws Exception if anything goes wrong
*/
protected void createUtrRefs() throws Exception {
Query q = new Query();
q.setDistinct(false);
QueryClass qcMRNA = new QueryClass(MRNA.class);
q.addFrom(qcMRNA);
q.addToSelect(qcMRNA);
q.addToOrderBy(qcMRNA);
QueryClass qcUTR = new QueryClass(UTR.class);
q.addFrom(qcUTR);
q.addToSelect(qcUTR);
q.addToOrderBy(qcUTR);
QueryCollectionReference mrnaUtrsRef =
new QueryCollectionReference(qcMRNA, "UTRs");
ContainsConstraint mrnaUtrsConstraint =
new ContainsConstraint(mrnaUtrsRef, ConstraintOp.CONTAINS, qcUTR);
q.setConstraint(mrnaUtrsConstraint);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
int count = 0;
MRNA lastMRNA = null;
FivePrimeUTR fivePrimeUTR = null;
ThreePrimeUTR threePrimeUTR = null;
osw.beginTransaction();
Iterator resIter = res.iterator();
while (resIter.hasNext()) {
ResultsRow rr = (ResultsRow) resIter.next();
MRNA mrna = (MRNA) rr.get(0);
UTR utr = (UTR) rr.get(1);
if (lastMRNA != null && !mrna.getId().equals(lastMRNA.getId())) {
// clone so we don't change the ObjectStore cache
MRNA tempMRNA = (MRNA) PostProcessUtil.cloneInterMineObject(lastMRNA);
if (fivePrimeUTR != null) {
TypeUtil.setFieldValue(tempMRNA, "fivePrimeUTR", fivePrimeUTR);
fivePrimeUTR = null;
}
if (threePrimeUTR != null) {
TypeUtil.setFieldValue(tempMRNA, "threePrimeUTR", threePrimeUTR);
threePrimeUTR = null;
}
osw.store(tempMRNA);
count++;
}
if (utr instanceof FivePrimeUTR) {
fivePrimeUTR = (FivePrimeUTR) utr;
} else {
threePrimeUTR = (ThreePrimeUTR) utr;
}
lastMRNA = mrna;
}
if (lastMRNA != null) {
// clone so we don't change the ObjectStore cache
MRNA tempMRNA = (MRNA) PostProcessUtil.cloneInterMineObject(lastMRNA);
TypeUtil.setFieldValue(tempMRNA, "fivePrimeUTR", fivePrimeUTR);
TypeUtil.setFieldValue(tempMRNA, "threePrimeUTR", threePrimeUTR);
osw.store(tempMRNA);
count++;
}
LOG.info("Stored MRNA " + count + " times (" + count * 2 + " fields set)");
osw.commitTransaction();
// now ANALYSE tables relating to class that has been altered - may be rows added
// to indirection tables
if (osw instanceof ObjectStoreWriterInterMineImpl) {
ClassDescriptor cld = model.getClassDescriptorByName(MRNA.class.getName());
DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
}
}
/**
* Query Gene->Protein->Annotation->GOTerm and return an iterator over the Gene,
* Protein and GOTerm.
*
* @param restrictToPrimaryGoTermsOnly Only get primary Annotation items linking the gene
* and the go term.
*/
private Iterator findProteinProperties(boolean restrictToPrimaryGoTermsOnly) throws Exception {
Query q = new Query();
q.setDistinct(false);
QueryClass qcGene = new QueryClass(Gene.class);
q.addFrom(qcGene);
q.addToSelect(qcGene);
q.addToOrderBy(qcGene);
QueryClass qcProtein = new QueryClass(Protein.class);
q.addFrom(qcProtein);
QueryClass qcAnnotation = null;
if (restrictToPrimaryGoTermsOnly) {
qcAnnotation = new QueryClass(GOAnnotation.class);
q.addFrom(qcAnnotation);
q.addToSelect(qcAnnotation);
} else {
qcAnnotation = new QueryClass(Annotation.class);
q.addFrom(qcAnnotation);
q.addToSelect(qcAnnotation);
}
QueryClass qcGOTerm = new QueryClass(GOTerm.class);
q.addFrom(qcGOTerm);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference geneProtRef = new QueryCollectionReference(qcProtein, "genes");
ContainsConstraint geneProtConstraint =
new ContainsConstraint(geneProtRef, ConstraintOp.CONTAINS, qcGene);
cs.addConstraint(geneProtConstraint);
QueryCollectionReference protAnnRef =
new QueryCollectionReference(qcProtein, "annotations");
ContainsConstraint protAnnConstraint =
new ContainsConstraint(protAnnRef, ConstraintOp.CONTAINS, qcAnnotation);
cs.addConstraint(protAnnConstraint);
QueryObjectReference annPropertyRef =
new QueryObjectReference(qcAnnotation, "property");
ContainsConstraint annPropertyConstraint =
new ContainsConstraint(annPropertyRef, ConstraintOp.CONTAINS, qcGOTerm);
cs.addConstraint(annPropertyConstraint);
if (restrictToPrimaryGoTermsOnly) {
QueryField isPrimaryTermQueryField =
new QueryField(qcAnnotation, "isPrimaryAssignment");
QueryValue trueValue = new QueryValue(Boolean.TRUE);
SimpleConstraint primeConst =
new SimpleConstraint(isPrimaryTermQueryField, ConstraintOp.EQUALS, trueValue);
cs.addConstraint(primeConst);
}
q.setConstraint(cs);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
return res.iterator();
}
/**
* Performs the business of linking Proteins to ProteinInteractions as well as other proteins
* that are related back to the protein via the interaction object.
*
* @throws Exception - if there is a problem...
* */
public void linkProteinToProtenInteractionAndRelatedProteins() throws Exception {
Query q = new Query();
q.setDistinct(false);
QueryClass proteinQC = new QueryClass(Protein.class);
q.addToSelect(proteinQC);
q.addFrom(proteinQC);
q.addToOrderBy(proteinQC);
QueryClass interactorQC = new QueryClass(ProteinInteractor.class);
q.addFrom(interactorQC);
QueryClass interactionQC = new QueryClass(ProteinInteraction.class);
q.addToSelect(interactionQC);
q.addFrom(interactionQC);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference proteinToInteractorRef =
new QueryCollectionReference(proteinQC, "interactionRoles");
ContainsConstraint proteinInteractorConstraint =
new ContainsConstraint(proteinToInteractorRef, ConstraintOp.CONTAINS, interactorQC);
cs.addConstraint(proteinInteractorConstraint);
QueryCollectionReference interactionToInteractorRef =
new QueryCollectionReference(interactionQC, "interactors");
ContainsConstraint interactionInteractorConstraint =
new ContainsConstraint(interactionToInteractorRef,
ConstraintOp.CONTAINS, interactorQC);
cs.addConstraint(interactionInteractorConstraint);
q.setConstraint(cs);
ObjectStore os = osw.getObjectStore();
((ObjectStoreInterMineImpl) os).precompute(q);
Results res = new Results(q, os, os.getSequence());
res.setBatchSize(500);
HashMap proteinToInteractionsMap = new HashMap();
HashMap interactionToProteinsMap = new HashMap();
LOG.debug("CHECKING linkProteinToProtenInteractionAndRelatedProteins RESULTS");
for (Iterator resIter = res.iterator(); resIter.hasNext();) {
ResultsRow rr = (ResultsRow) resIter.next();
Protein protein = (Protein) rr.get(0);
ProteinInteraction interaction = (ProteinInteraction) rr.get(1);
addProteinAndInterationPairToMap(protein, interaction, proteinToInteractionsMap, true);
addProteinAndInterationPairToMap(protein, interaction, interactionToProteinsMap, false);
LOG.debug("PROTEIN:" + protein.getPrimaryAccession()
+ " -> INTERACTION:" + interaction.getShortName());
}
osw.beginTransaction();
LOG.debug("Setting values for interaction.proteins");
for (Iterator i2pIt = interactionToProteinsMap.keySet().iterator(); i2pIt.hasNext();) {
ProteinInteraction nextInteraction = (ProteinInteraction) i2pIt.next();
Set nextProteinSet = (Set) interactionToProteinsMap.get(nextInteraction);
nextInteraction.setProteins(nextProteinSet);
osw.store(nextInteraction);
LOG.debug("INTERACTION:" + nextInteraction.getShortName()
+ " HAS THIS MANY PROTEINS:" + nextProteinSet.size());
}
LOG.debug("Setting values for protein.proteinInteractions");
for (Iterator p2iIt = proteinToInteractionsMap.keySet().iterator(); p2iIt.hasNext();) {
Protein nextProtein = (Protein) p2iIt.next();
Set nextInteractionSet = (Set) proteinToInteractionsMap.get(nextProtein);
nextProtein.setProteinInteractions(nextInteractionSet);
//Don't store the proteins here as we still have work to do on them
LOG.debug("PROTEIN:" + nextProtein.getPrimaryAccession()
+ " HAS THIS MANY INTERACTIONS:" + nextInteractionSet.size());
}
LOG.debug("Setting values for protein.interactingProteins");
for (Iterator p2iIt2 = proteinToInteractionsMap.keySet().iterator(); p2iIt2.hasNext();) {
Protein nextProtein = (Protein) p2iIt2.next();
Set interactingProteinSet = new HashSet();
//Explicitly add the starting protein so we can remove it blindly later.
interactingProteinSet.add(nextProtein);
Set nextInteractionSet = (Set) proteinToInteractionsMap.get(nextProtein);
for (Iterator iIt = nextInteractionSet.iterator(); iIt.hasNext(); ) {
ProteinInteraction nextInteraction = (ProteinInteraction) iIt.next();
Set nextInteractingProteinSet = (Set) interactionToProteinsMap.get(nextInteraction);
interactingProteinSet.addAll(nextInteractingProteinSet);
}
//TODO: DO WE WANT TO ADD/REMOVE SELF REFS ? I.E. WHERE A PROTEIN INTERACTS WITH ITSELF
//Explictly remove the starting protein so it wont refer to itself - for the moment!.
interactingProteinSet.remove(nextProtein);
nextProtein.setInteractingProteins(interactingProteinSet);
osw.store(nextProtein);
LOG.debug("PROTEIN:" + nextProtein.getPrimaryAccession()
+ " HAS THIS MANY RELATED PROTEINS:" + interactingProteinSet.size());
}
osw.commitTransaction();
}
/**
* Little helper method for the linkProteinToProtenInteractionAndRelatedProteins method.
*
* @param protein - a protein
* @param interaction - an interaction the protein appeared in
* @param map - either a protein-interactions map or vice versa
* @param useProteinAsTheKey - a boolean indicating which sort of map we have to deal with
* */
private void addProteinAndInterationPairToMap(Protein protein, ProteinInteraction interaction,
HashMap map, boolean useProteinAsTheKey) {
//Treat the protein as the key
if (useProteinAsTheKey) {
if (map.containsKey(protein)) {
Set interactionSet = (Set) map.get(protein);
interactionSet.add(interaction);
} else {
Set newInteractionSet = new HashSet();
newInteractionSet.add(interaction);
map.put(protein, newInteractionSet);
}
//Treat the interaction as the key
} else {
if (map.containsKey(interaction)) {
Set proteinSet = (Set) map.get(interaction);
proteinSet.add(protein);
} else {
Set newProteinSet = new HashSet();
newProteinSet.add(protein);
map.put(interaction, newProteinSet);
}
}
}
}
| added create microArrayResults collection for CompositeSequence
| flymine/model/genomic/src/java/org/flymine/postprocess/CreateReferences.java | added create microArrayResults collection for CompositeSequence | <ide><path>lymine/model/genomic/src/java/org/flymine/postprocess/CreateReferences.java
<ide> * @throws Exception if anything goes wrong
<ide> */
<ide> public void insertReferences() throws Exception {
<del> LOG.info("insertReferences stage 1");
<add> // LOG.info("insertReferences stage 1");
<ide>
<ide> // Transcript.exons / Exon.transcripts
<ide> insertCollectionField(Transcript.class, "subjects", RankedRelation.class, "subject",
<ide> // Gene.phenotypes
<ide> insertReferences(Gene.class, Phenotype.class, "phenotypes");
<ide>
<add> LOG.info("insertReferences stage 15");
<ide> // CDNAClone.results (MicroArrayResult)
<ide> createCDNACloneResultsCollection();
<del>
<del> LOG.info("insertReferences stage 15");
<add> // CompositeSequence.results (MicroArrayResult)
<add> createCompositeSeqResultsCollection();
<ide> // Gene.microArrayResults
<ide> createMicroArrayResultsCollection();
<ide>
<ide>
<ide>
<ide> /**
<del> * Creates a collection of MicroArrayResult objects on Genes.
<add> * Creates a collection of MicroArrayResult objects on CDNAClone.
<ide> * @throws Exception if anything goes wrong
<ide> */
<ide> protected void createCDNACloneResultsCollection() throws Exception {
<ide> // to indirection tables
<ide> if (osw instanceof ObjectStoreWriterInterMineImpl) {
<ide> ClassDescriptor cld = model.getClassDescriptorByName(CDNAClone.class.getName());
<add> DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
<add> }
<add> }
<add>
<add>
<add>
<add> /**
<add> * Creates a collection of MicroArrayResult objects on CompositeSequence.
<add> * @throws Exception if anything goes wrong
<add> */
<add> protected void createCompositeSeqResultsCollection() throws Exception {
<add> Query q = new Query();
<add> q.setDistinct(false);
<add> ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
<add>
<add> QueryClass qcCompositeSeq = new QueryClass(CompositeSequence.class);
<add> q.addFrom(qcCompositeSeq);
<add> q.addToSelect(qcCompositeSeq);
<add> q.addToOrderBy(qcCompositeSeq);
<add>
<add> QueryClass qcReporter = new QueryClass(Reporter.class);
<add> q.addFrom(qcReporter);
<add> q.addToSelect(qcReporter);
<add> q.addToOrderBy(qcReporter);
<add>
<add> QueryObjectReference reporterMaterial =
<add> new QueryObjectReference(qcReporter, "material");
<add> ContainsConstraint ccReporterMaterial =
<add> new ContainsConstraint(reporterMaterial, ConstraintOp.CONTAINS, qcCompositeSeq);
<add> cs.addConstraint(ccReporterMaterial);
<add>
<add> QueryClass qcResult = new QueryClass(MicroArrayResult.class);
<add> q.addFrom(qcResult);
<add> q.addToSelect(qcResult);
<add> q.addToOrderBy(qcResult);
<add>
<add> QueryCollectionReference reporterResults =
<add> new QueryCollectionReference(qcReporter, "results");
<add> ContainsConstraint ccReporterResults =
<add> new ContainsConstraint(reporterResults, ConstraintOp.CONTAINS, qcResult);
<add> cs.addConstraint(ccReporterResults);
<add>
<add> q.setConstraint(cs);
<add> ObjectStore os = osw.getObjectStore();
<add>
<add> ((ObjectStoreInterMineImpl) os).precompute(q);
<add> Results res = new Results(q, os, os.getSequence());
<add> res.setBatchSize(500);
<add>
<add> int count = 0;
<add> CompositeSequence lastComSeq = null;
<add> Set newCollection = new HashSet();
<add>
<add> osw.beginTransaction();
<add>
<add> Iterator resIter = res.iterator();
<add> while (resIter.hasNext()) {
<add> ResultsRow rr = (ResultsRow) resIter.next();
<add> CompositeSequence thisComSeq = (CompositeSequence) rr.get(0);
<add> MicroArrayResult maResult = (MicroArrayResult) rr.get(2);
<add>
<add> if (lastComSeq == null || !thisComSeq.getId().equals(lastComSeq.getId())) {
<add> if (lastComSeq != null) {
<add> // clone so we don't change the ObjectStore cache
<add> CompositeSequence tempComSeq = (CompositeSequence) PostProcessUtil
<add> .cloneInterMineObject(lastComSeq);
<add> TypeUtil.setFieldValue(tempComSeq, "results", newCollection);
<add> osw.store(tempComSeq);
<add> count++;
<add> }
<add> newCollection = new HashSet();
<add> }
<add>
<add> newCollection.add(maResult);
<add>
<add> lastComSeq = thisComSeq;
<add> }
<add>
<add> if (lastComSeq != null) {
<add> // clone so we don't change the ObjectStore cache
<add> CompositeSequence tempComSeq = (CompositeSequence) PostProcessUtil.cloneInterMineObject(lastComSeq);
<add> TypeUtil.setFieldValue(tempComSeq, "results", newCollection);
<add> osw.store(tempComSeq);
<add> count++;
<add> }
<add> LOG.info("Created " + count + " CompositeSequence.results collections");
<add> osw.commitTransaction();
<add>
<add> // now ANALYSE tables relating to class that has been altered - may be rows added
<add> // to indirection tables
<add> if (osw instanceof ObjectStoreWriterInterMineImpl) {
<add> ClassDescriptor cld = model.getClassDescriptorByName(CompositeSequence.class.getName());
<ide> DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
<ide> }
<ide> } |
|
Java | agpl-3.0 | 82596ce1a08f867dd1399863f33c162bb11508bb | 0 | jaytaylor/sql-layer,wfxiang08/sql-layer-1,shunwang/sql-layer-1,relateiq/sql-layer,qiuyesuifeng/sql-layer,relateiq/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,ngaut/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,relateiq/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,wfxiang08/sql-layer-1,shunwang/sql-layer-1,jaytaylor/sql-layer,relateiq/sql-layer,ngaut/sql-layer,qiuyesuifeng/sql-layer,shunwang/sql-layer-1,qiuyesuifeng/sql-layer | package com.akiban.cserver.store;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.TestCase;
import com.akiban.ais.ddl.DDLSource;
import com.akiban.ais.model.AkibaInformationSchema;
import com.akiban.cserver.CServerConfig;
import com.akiban.cserver.CServerConstants;
import com.akiban.cserver.IndexDef;
import com.akiban.cserver.InvalidOperationException;
import com.akiban.cserver.RowData;
import com.akiban.cserver.RowDef;
import com.akiban.cserver.RowDefCache;
import com.akiban.message.ErrorCode;
import com.akiban.util.ByteBufferFactory;
import com.persistit.Exchange;
import com.persistit.KeyState;
import com.persistit.TransactionRunnable;
import com.persistit.Tree;
import com.persistit.Volume;
import com.persistit.exception.RollbackException;
public class PersistitStoreWithAISTest extends TestCase implements
CServerConstants {
private final static String DDL_FILE_NAME = "src/test/resources/data_dictionary_test.ddl";
private final static String SCHEMA = "data_dictionary_test";
private final static String GROUP_SCHEMA = "akiba_objects";
private PersistitStore store;
private RowDefCache rowDefCache;
private interface RowVisitor {
void visit(final int depth) throws Exception;
}
private RowDef userRowDef(final String name) {
return rowDefCache.getRowDef(SCHEMA + "." + name);
}
private RowDef groupRowDef(final String name) {
return rowDefCache.getRowDef(GROUP_SCHEMA + "." + name);
}
class TestData {
final RowDef defC = userRowDef("customer");
final RowDef defO = userRowDef("order");
final RowDef defI = userRowDef("item");
final RowDef defA = userRowDef("address");
final RowDef defX = userRowDef("component");
final RowDef defCOI = groupRowDef("_akiba_customer");
final RowData rowC = new RowData(new byte[256]);
final RowData rowO = new RowData(new byte[256]);
final RowData rowI = new RowData(new byte[256]);
final RowData rowA = new RowData(new byte[256]);
final RowData rowX = new RowData(new byte[256]);
final int customers;
final int ordersPerCustomer;
final int itemsPerOrder;
final int componentsPerItem;
long cid;
long oid;
long iid;
long xid;
long elapsed;
long count = 0;
TestData(final int customers, final int ordersPerCustomer,
final int itemsPerOrder, final int componentsPerItem) {
this.customers = customers;
this.ordersPerCustomer = ordersPerCustomer;
this.itemsPerOrder = itemsPerOrder;
this.componentsPerItem = componentsPerItem;
}
void insertTestRows() throws Exception {
elapsed = System.nanoTime();
int unique = 0;
for (int c = 0; ++c <= customers;) {
cid = c;
rowC.reset(0, 256);
rowC.createRow(defC, new Object[] { cid, "Customer_" + cid });
store.writeRow(rowC);
for (int o = 0; ++o <= ordersPerCustomer;) {
oid = cid * 1000 + o;
rowO.reset(0, 256);
rowO.createRow(defO, new Object[] { oid, cid, 12345 });
store.writeRow(rowO);
for (int i = 0; ++i <= itemsPerOrder;) {
iid = oid * 1000 + i;
rowI.reset(0, 256);
rowI.createRow(defI, new Object[] { oid, iid, 123456,
654321 });
store.writeRow(rowI);
for (int x = 0; ++x <= componentsPerItem;) {
xid = iid * 1000 + x;
rowX.reset(0, 256);
rowX.createRow(defX, new Object[] { iid, xid, c,
++unique, "Description_" + unique });
store.writeRow(rowX);
}
}
}
for (int a = 0; a < (c % 3); a++) {
rowA.reset(0, 256);
rowA.createRow(defA, new Object[] { c, a, "addr1_" + c,
"addr2_" + c, "addr3_" + c });
store.writeRow(rowA);
}
}
elapsed = System.nanoTime() - elapsed;
}
void visitTestRows(final RowVisitor visitor) throws Exception {
elapsed = System.nanoTime();
int unique = 0;
for (int c = 0; ++c <= customers;) {
cid = c;
rowC.reset(0, 256);
rowC.createRow(defC, new Object[] { cid, "Customer_" + cid });
visitor.visit(0);
for (int o = 0; ++o <= ordersPerCustomer;) {
oid = cid * 1000 + o;
rowO.reset(0, 256);
rowO.createRow(defO, new Object[] { oid, cid, 12345 });
visitor.visit(1);
for (int i = 0; ++i <= itemsPerOrder;) {
iid = oid * 1000 + i;
rowI.reset(0, 256);
rowI.createRow(defI, new Object[] { oid, iid, 123456,
654321 });
visitor.visit(2);
for (int x = 0; ++x <= componentsPerItem;) {
xid = iid * 1000 + x;
rowX.reset(0, 256);
rowX.createRow(defX, new Object[] { iid, xid, c,
++unique, "Description_" + unique });
visitor.visit(3);
}
}
}
}
elapsed = System.nanoTime() - elapsed;
}
int totalRows() {
return totalCustomerRows() + totalOrderRows() + totalItemRows()
+ totalComponentRows();
}
int totalCustomerRows() {
return customers;
}
int totalOrderRows() {
return customers * ordersPerCustomer;
}
int totalItemRows() {
return customers * ordersPerCustomer * itemsPerOrder;
}
int totalComponentRows() {
return customers * ordersPerCustomer * itemsPerOrder
* componentsPerItem;
}
void start() {
elapsed = System.nanoTime();
}
void end() {
elapsed = System.nanoTime() - elapsed;
}
}
@Override
public void setUp() throws Exception {
rowDefCache = new RowDefCache();
store = new PersistitStore(CServerConfig.unitTestConfig(), rowDefCache);
final AkibaInformationSchema ais = new DDLSource()
.buildAIS(DDL_FILE_NAME);
rowDefCache.setAIS(ais);
store.startUp();
store.setOrdinals();
}
@Override
public void tearDown() throws Exception {
store.shutDown();
store = null;
rowDefCache = null;
}
public void testWriteCOIrows() throws Exception {
final TestData td = new TestData(10, 10, 10, 10);
td.insertTestRows();
System.out.println("testWriteCOIrows: inserted " + td.totalRows()
+ " rows in " + (td.elapsed / 1000L) + "us");
}
public void testScanCOIrows() throws Exception {
final TestData td = new TestData(1000, 10, 3, 2);
td.insertTestRows();
System.out.println("testScanCOIrows: inserted " + td.totalRows()
+ " rows in " + (td.elapsed / 1000L) + "us");
{
// simple test - get all I rows
td.start();
int scanCount = 0;
td.rowI.createRow(td.defI, new Object[] { null, null, null });
final byte[] columnBitMap = new byte[] { 0xF };
final int indexId = 0;
final RowCollector rc = store.newRowCollector(
td.defI.getRowDefId(), indexId, 0, td.rowI, td.rowI,
columnBitMap);
final ByteBuffer payload = ByteBufferFactory.allocate(256);
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(),
payload.position(), payload.limit());
for (int p = rowData.getBufferStart(); p < rowData
.getBufferEnd();) {
rowData.prepareRow(p);
p = rowData.getRowEnd();
scanCount++;
}
}
assertEquals(td.totalItemRows(), scanCount);
td.end();
System.out.println("testScanCOIrows: scanned " + scanCount
+ " rows in " + (td.elapsed / 1000L) + "us");
}
{
// select item by IID in user table `item`
td.start();
int scanCount = 0;
td.rowI.createRow(td.defI,
new Object[] { null, Integer.valueOf(1001001), null, null });
final byte[] columnBitMap = new byte[] { (byte) 0x3 };
final int indexId = td.defI.getPKIndexDef().getId();
final RowCollector rc = store.newRowCollector(
td.defI.getRowDefId(), indexId, 0, td.rowI, td.rowI,
columnBitMap);
final ByteBuffer payload = ByteBufferFactory.allocate(256);
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(),
payload.position(), payload.limit());
for (int p = rowData.getBufferStart(); p < rowData
.getBufferEnd();) {
rowData.prepareRow(p);
p = rowData.getRowEnd();
scanCount++;
}
}
assertEquals(1, scanCount);
td.end();
System.out.println("testScanCOIrows: scanned " + scanCount
+ " rows in " + (td.elapsed / 1000L) + "us");
}
{
// select items in COI table by index values on Order
td.start();
int scanCount = 0;
final RowData start = new RowData(new byte[256]);
final RowData end = new RowData(new byte[256]);
// C has 2 columns, A has 5 columns, O has 3 columns, I has 4
// columns, CC has 5 columns
start.createRow(td.defCOI, new Object[] { null, null, null, null,
null, null, null, 1004, null, null, null, null, null, null,
null, null, null, null, null });
end.createRow(td.defCOI, new Object[] { null, null, null, null,
null, null, null, 1007, null, null, null, null, null, null,
null, null, null, null, null });
final byte[] columnBitMap = projection(new RowDef[] { td.defC,
td.defO, td.defI }, td.defCOI.getFieldCount());
int indexId = findIndexId(td.defCOI, td.defO, 0);
final RowCollector rc = store.newRowCollector(
td.defCOI.getRowDefId(), indexId, 0, start, end,
columnBitMap);
final ByteBuffer payload = ByteBufferFactory.allocate(256);
//
// Expect all the C, O and I rows for orders 1004 through 1007,
// inclusive
// Total of 40
//
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(),
payload.position(), payload.limit());
for (int p = rowData.getBufferStart(); p < rowData
.getBufferEnd();) {
rowData.prepareRow(p);
System.out.println(rowData.toString(rowDefCache));
p = rowData.getRowEnd();
scanCount++;
}
}
assertEquals(rc.getDeliveredRows(), scanCount);
assertEquals(17, scanCount - rc.getRepeatedRows());
td.end();
System.out.println("testScanCOIrows: scanned " + scanCount
+ " rows in " + (td.elapsed / 1000L) + "us");
}
}
int findIndexId(final RowDef groupRowDef, final RowDef userRowDef,
final int fieldIndex) {
int indexId = -1;
final int findField = fieldIndex + userRowDef.getColumnOffset();
for (final IndexDef indexDef : groupRowDef.getIndexDefs()) {
if (indexDef.getFields().length == 1
&& indexDef.getFields()[0] == findField) {
indexId = indexDef.getId();
}
}
return indexId;
}
final byte[] projection(final RowDef[] rowDefs, final int width) {
final byte[] bitMap = new byte[(width + 7) / 8];
for (final RowDef rowDef : rowDefs) {
for (int bit = rowDef.getColumnOffset(); bit < rowDef
.getColumnOffset() + rowDef.getFieldCount(); bit++) {
bitMap[bit / 8] |= (1 << (bit % 8));
}
}
return bitMap;
}
public void testDropTable() throws Exception {
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
assertNotNull(volume.getTree(td.defCOI.getTreeName(), false));
assertNotNull(volume.getTree(td.defO.getPkTreeName(), false));
assertNotNull(volume.getTree(td.defI.getPkTreeName(), false));
store.dropTable(td.defO.getRowDefId());
assertTrue(store.getTableManager()
.getTableStatus(td.defO.getRowDefId()).isDeleted());
assertNotNull(volume.getTree(td.defO.getPkTreeName(), false));
store.dropTable(td.defI.getRowDefId());
assertNotNull(volume.getTree(td.defI.getPkTreeName(), false));
assertTrue(store.getTableManager()
.getTableStatus(td.defI.getRowDefId()).isDeleted());
store.dropTable(td.defA.getRowDefId());
assertNotNull(volume.getTree(td.defA.getPkTreeName(), false));
assertTrue(store.getTableManager()
.getTableStatus(td.defA.getRowDefId()).isDeleted());
store.dropTable(td.defC.getRowDefId());
assertTrue(store.getTableManager()
.getTableStatus(td.defC.getRowDefId()).isDeleted());
store.dropTable(td.defO.getRowDefId());
assertNotNull(volume.getTree(td.defO.getPkTreeName(), false));
assertTrue(store.getTableManager()
.getTableStatus(td.defO.getRowDefId()).isDeleted());
store.dropTable(td.defX.getRowDefId());
assertTrue(isGone(td.defCOI.getTreeName()));
assertTrue(isGone(td.defO.getPkTreeName()));
assertTrue(isGone(td.defI.getPkTreeName()));
assertTrue(isGone(td.defX.getPkTreeName()));
assertTrue(isGone(td.defA.getPkTreeName()));
}
// public void testDropSchema() throws Exception {
// //
// Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
// for (int loop = 0; loop < 20; loop++) {
// final TestData td = new TestData(10, 10, 10, 10);
// td.insertTestRows();
// store.dropSchema(SCHEMA);
// assertTrue(isGone(td.defCOI.getTreeName()));
// assertTrue(isGone(td.defO.getPkTreeName()));
// assertTrue(isGone(td.defI.getPkTreeName()));
// }
// }
public void testBug47() throws Exception {
//
Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
for (int loop = 0; loop < 20; loop++) {
final TestData td = new TestData(10, 10, 10, 10);
td.insertTestRows();
store.dropTable(td.defI.getRowDefId());
store.dropTable(td.defO.getRowDefId());
store.dropTable(td.defC.getRowDefId());
store.dropTable(td.defCOI.getRowDefId());
store.dropTable(td.defA.getRowDefId());
store.dropTable(td.defX.getRowDefId());
store.dropSchema(SCHEMA);
assertTrue(isGone(td.defCOI.getTreeName()));
assertTrue(isGone(td.defO.getPkTreeName()));
assertTrue(isGone(td.defI.getPkTreeName()));
}
}
public void testUniqueIndexes() throws Exception {
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
td.rowX.createRow(td.defX, new Object[] { 1002003, 23890345, 123, 44,
"test1" });
ErrorCode actual = null;
try {
store.writeRow(td.rowX);
} catch (InvalidOperationException e) {
actual = e.getCode();
}
assertEquals(ErrorCode.DUPLICATE_KEY, actual);
td.rowX.createRow(td.defX, new Object[] { 1002003, 23890345, 123,
44444, "test2" });
store.writeRow(td.rowX);
}
public void testUpdateRows() throws Exception {
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
long cid = 3;
long oid = cid * 1000 + 2;
long iid = oid * 1000 + 4;
long xid = iid * 1000 + 3;
td.rowX.createRow(td.defX, new Object[] { iid, xid, null, null });
final byte[] columnBitMap = new byte[] { (byte) 0x1F };
final ByteBuffer payload = ByteBufferFactory.allocate(1024);
RowCollector rc;
rc = store.newRowCollector(td.defX.getRowDefId(), td.defX
.getPKIndexDef().getId(), 0, td.rowX, td.rowX, columnBitMap);
payload.clear();
assertTrue(rc.collectNextRow(payload));
payload.flip();
RowData oldRowData = new RowData(payload.array(), payload.position(),
payload.limit());
oldRowData.prepareRow(oldRowData.getBufferStart());
RowData newRowData = new RowData(new byte[256]);
newRowData.createRow(td.defX, new Object[] { iid, xid, 4, 424242,
"Description_424242" });
store.updateRow(oldRowData, newRowData);
rc = store.newRowCollector(td.defX.getRowDefId(), td.defX
.getPKIndexDef().getId(), 0, td.rowX, td.rowX, columnBitMap);
payload.clear();
assertTrue(rc.collectNextRow(payload));
payload.flip();
RowData updateRowData = new RowData(payload.array(),
payload.position(), payload.limit());
updateRowData.prepareRow(updateRowData.getBufferStart());
System.out.println(updateRowData.toString(store.getRowDefCache()));
//
// Now attempt to update a leaf table's PK field.
//
newRowData = new RowData(new byte[256]);
newRowData.createRow(td.defX, new Object[] { iid, -xid, 4, 545454,
"Description_545454" });
store.updateRow(updateRowData, newRowData);
rc = store.newRowCollector(td.defX.getRowDefId(), td.defX
.getPKIndexDef().getId(), 0, updateRowData, updateRowData,
columnBitMap);
payload.clear();
assertTrue(!rc.collectNextRow(payload));
rc = store.newRowCollector(td.defX.getRowDefId(), td.defX
.getPKIndexDef().getId(), 0, newRowData, newRowData,
columnBitMap);
assertTrue(rc.collectNextRow(payload));
payload.flip();
updateRowData = new RowData(payload.array(), payload.position(),
payload.limit());
updateRowData.prepareRow(updateRowData.getBufferStart());
System.out.println(updateRowData.toString(store.getRowDefCache()));
// TODO:
// Hand-checked the index tables. Need SELECT on secondary indexes to
// verify them automatically.
}
public void testDeleteRows() throws Exception {
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
td.count = 0;
final RowVisitor visitor = new RowVisitor() {
public void visit(final int depth) throws Exception {
ErrorCode expectedError = null;
ErrorCode actualError = null;
try {
switch (depth) {
case 0:
// TODO - for now we can't do cascading DELETE so we
// expect an error
expectedError = ErrorCode.FK_CONSTRAINT_VIOLATION;
store.deleteRow(td.rowC);
break;
case 1:
// TODO - for now we can't do cascading DELETE so we
// expect an error
expectedError = ErrorCode.FK_CONSTRAINT_VIOLATION;
store.deleteRow(td.rowO);
break;
case 2:
// TODO - for now we can't do cascading DELETE so we
// expect an error
expectedError = ErrorCode.FK_CONSTRAINT_VIOLATION;
store.deleteRow(td.rowI);
break;
case 3:
expectedError = null;
if (td.xid % 2 == 0) {
store.deleteRow(td.rowX);
td.count++;
}
break;
default:
throw new Exception("depth = " + depth);
}
} catch (InvalidOperationException e) {
actualError = e.getCode();
}
assertEquals("at depth " + depth, expectedError, actualError);
}
};
td.visitTestRows(visitor);
int scanCount = 0;
td.rowX.createRow(td.defX, new Object[0]);
final byte[] columnBitMap = new byte[] { (byte) 0x1F };
final RowCollector rc = store.newRowCollector(td.defX.getRowDefId(),
td.defX.getPKIndexDef().getId(), 0, td.rowX, td.rowX,
columnBitMap);
final ByteBuffer payload = ByteBufferFactory.allocate(256);
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(), payload.position(),
payload.limit());
for (int p = rowData.getBufferStart(); p < rowData.getBufferEnd();) {
rowData.prepareRow(p);
p = rowData.getRowEnd();
scanCount++;
}
}
assertEquals(td.totalComponentRows() - td.count, scanCount);
// TODO:
// Hand-checked the index tables. Need SELECT on secondary indexes to
// verify them automatically.
}
public void testFetchRows() throws Exception {
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
{
final List<RowData> list = store.fetchRows("data_dictionary_test",
"item", "part_id", 1001001, 1001005, "item");
assertEquals(5, list.size());
}
{
final List<RowData> list = store.fetchRows("data_dictionary_test",
"customer", "customer_id", 1, 1, "item");
assertEquals(31, list.size());
}
{
final List<RowData> list = store.fetchRows("data_dictionary_test",
"customer", "customer_id", 1, 2, "address");
assertEquals(5, list.size());
}
{
final List<RowData> list = store.fetchRows("data_dictionary_test",
"customer", "customer_id", 1, 1, null);
for (final RowData rowData : list) {
System.out.println(rowData.toString(rowDefCache));
}
assertEquals(157, list.size());
}
}
public void testCommittedUpdateListener() throws Exception {
final Map<Integer, AtomicInteger> counts = new HashMap<Integer, AtomicInteger>();
final CommittedUpdateListener listener = new CommittedUpdateListener() {
@Override
public void updated(KeyState keyState, RowDef rowDef,
RowData oldRowData, RowData newRowData) {
ai(rowDef).addAndGet(1000000);
}
@Override
public void inserted(KeyState keyState, RowDef rowDef,
RowData rowData) {
ai(rowDef).addAndGet(1);
}
@Override
public void deleted(KeyState keyState, RowDef rowDef,
RowData rowData) {
ai(rowDef).addAndGet(1000);
}
AtomicInteger ai(final RowDef rowDef) {
AtomicInteger ai = counts.get(rowDef.getRowDefId());
if (ai == null) {
ai = new AtomicInteger();
counts.put(rowDef.getRowDefId(), ai);
}
return ai;
}
};
store.addCommittedUpdateListener(listener);
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
assertEquals(5, counts.get(td.defC.getRowDefId()).intValue());
assertEquals(25, counts.get(td.defO.getRowDefId()).intValue());
assertEquals(125, counts.get(td.defI.getRowDefId()).intValue());
assertEquals(625, counts.get(td.defX.getRowDefId()).intValue());
//
// Now delete or change every other X rows
//
int scanCount = 0;
td.rowX.createRow(td.defX, new Object[0]);
final byte[] columnBitMap = new byte[] { (byte) 0x1F };
final RowCollector rc = store.newRowCollector(td.defX.getRowDefId(),
td.defX.getPKIndexDef().getId(), 0, td.rowX, td.rowX,
columnBitMap);
final ByteBuffer payload = ByteBufferFactory.allocate(256);
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(), payload.position(),
payload.limit());
for (int p = rowData.getBufferStart(); p < rowData.getBufferEnd();) {
rowData.prepareRow(p);
if (scanCount++ % 2 == 0) {
store.deleteRow(rowData);
} else {
store.updateRow(rowData, rowData);
}
p = rowData.getRowEnd();
}
}
assertEquals(5, counts.get(td.defC.getRowDefId()).intValue());
assertEquals(25, counts.get(td.defO.getRowDefId()).intValue());
assertEquals(125, counts.get(td.defI.getRowDefId()).intValue());
assertEquals(312313625, counts.get(td.defX.getRowDefId()).intValue());
}
public void testDeferIndex() throws Exception {
final TestData td = new TestData(3, 3, 0, 0);
store.setDeferIndexes(true);
td.insertTestRows();
final StringWriter a, b, c, d;
dumpIndexes(new PrintWriter(a = new StringWriter()));
store.flushIndexes();
dumpIndexes(new PrintWriter(b = new StringWriter()));
store.deleteIndexes("");
dumpIndexes(new PrintWriter(c = new StringWriter()));
store.buildIndexes("");
dumpIndexes(new PrintWriter(d = new StringWriter()));
assertTrue(!a.toString().equals(b.toString()));
assertEquals(a.toString(), c.toString());
assertEquals(b.toString(), d.toString());
}
public void testRebuildIndex() throws Exception {
final TestData td = new TestData(3, 3, 3, 3);
td.insertTestRows();
final StringWriter a, b, c;
dumpIndexes(new PrintWriter(a = new StringWriter()));
store.deleteIndexes("");
dumpIndexes(new PrintWriter(b = new StringWriter()));
store.buildIndexes("");
dumpIndexes(new PrintWriter(c = new StringWriter()));
assertTrue(!a.toString().equals(b.toString()));
assertEquals(a.toString(), c.toString());
}
public void testBug283() throws Exception {
//
// Creates the index tables ahead of the h-table. This
// affects the Transaction commit order.
//
store.getDb().getTransaction().run(new TransactionRunnable() {
public void runTransaction() throws RollbackException {
for (int index = 1; index < 13; index++) {
final String treeName = "_akiba_customer$$" + index;
try {
final Exchange exchange = store.getExchange(treeName);
exchange.to("testBug283").store();
store.releaseExchange(exchange);
} catch (Exception e) {
throw new RollbackException(e);
}
}
}
});
final TestData td = new TestData(1, 1, 1, 1);
td.insertTestRows();
final AtomicBoolean broken = new AtomicBoolean(false);
final long expires = System.nanoTime() + 300000000000L; // 30 seconds
final AtomicInteger lastInserted = new AtomicInteger();
final AtomicInteger scanCount = new AtomicInteger();
final Thread thread1 = new Thread(new Runnable() {
public void run() {
for (int xid = 1001001002; System.nanoTime() < expires
&& !broken.get(); xid++) {
td.rowX.createRow(td.defX, new Object[] { 1001001, xid,
123, xid - 100100100, "part " + xid });
try {
store.writeRow(td.rowX);
lastInserted.set(xid);
} catch (Exception e) {
e.printStackTrace();
broken.set(true);
break;
}
}
}
}, "INSERTER");
final Thread thread2 = new Thread(new Runnable() {
public void run() {
final RowData start = new RowData(new byte[256]);
final RowData end = new RowData(new byte[256]);
final byte[] columnBitMap = new byte[] { (byte) 0xF };
final ByteBuffer payload = ByteBufferFactory.allocate(100000);
while (System.nanoTime() < expires && !broken.get()) {
int xid = lastInserted.get();
start.createRow(td.defX, new Object[] { 1001001, xid, null,
null });
end.createRow(td.defX, new Object[] { 1001001, xid + 10000,
null, null });
final int indexId = td.defX.getPKIndexDef().getId();
try {
final RowCollector rc = store.newRowCollector(
td.defX.getRowDefId(), indexId, 0, start, end,
columnBitMap);
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(),
payload.position(), payload.limit());
for (int p = rowData.getBufferStart(); p < rowData.getBufferEnd();) {
rowData.prepareRow(p);
p = rowData.getRowEnd();
scanCount.incrementAndGet();
}
}
// } catch (InvalidOperationException ioe) {
// broken.set(true);
// break;
} catch (Exception e) {
e.printStackTrace();
broken.set(true);
break;
}
}
}
}, "SCANNER");
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertTrue(!broken.get());
}
private void dumpIndexes(final PrintWriter pw) throws Exception {
for (final RowDef rowDef : rowDefCache.getRowDefs()) {
pw.println(rowDef);
for (final IndexDef indexDef : rowDef.getIndexDefs()) {
pw.println(indexDef);
dumpIndex(indexDef, pw);
}
}
pw.flush();
}
private void dumpIndex(final IndexDef indexDef, final PrintWriter pw)
throws Exception {
final Exchange ex = store.getExchange(indexDef.getRowDef(), indexDef);
ex.clear();
while (ex.next(true)) {
pw.println(ex.getKey());
}
pw.flush();
}
private boolean isGone(final String treeName) throws Exception {
Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
final Tree tree = volume.getTree(treeName, false);
if (tree == null) {
return true;
}
final Exchange exchange = store.getExchange(treeName);
exchange.clear();
return !exchange.hasChildren();
}
}
| src/test/java/com/akiban/cserver/store/PersistitStoreWithAISTest.java | package com.akiban.cserver.store;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import com.akiban.cserver.InvalidOperationException;
import com.akiban.message.ErrorCode;
import junit.framework.TestCase;
import com.akiban.ais.ddl.DDLSource;
import com.akiban.ais.model.AkibaInformationSchema;
import com.akiban.cserver.CServerConfig;
import com.akiban.cserver.CServerConstants;
import com.akiban.cserver.IndexDef;
import com.akiban.cserver.RowData;
import com.akiban.cserver.RowDef;
import com.akiban.cserver.RowDefCache;
import com.akiban.util.ByteBufferFactory;
import com.persistit.Exchange;
import com.persistit.KeyState;
import com.persistit.Tree;
import com.persistit.Volume;
public class PersistitStoreWithAISTest extends TestCase implements
CServerConstants {
private final static String DDL_FILE_NAME = "src/test/resources/data_dictionary_test.ddl";
private final static String SCHEMA = "data_dictionary_test";
private final static String GROUP_SCHEMA = "akiba_objects";
private PersistitStore store;
private RowDefCache rowDefCache;
private interface RowVisitor {
void visit(final int depth) throws Exception;
}
private RowDef userRowDef(final String name) {
return rowDefCache.getRowDef(SCHEMA + "." + name);
}
private RowDef groupRowDef(final String name) {
return rowDefCache.getRowDef(GROUP_SCHEMA + "." + name);
}
private class TestData {
final RowDef defC = userRowDef("customer");
final RowDef defO = userRowDef("order");
final RowDef defI = userRowDef("item");
final RowDef defA = userRowDef("address");
final RowDef defX = userRowDef("component");
final RowDef defCOI = groupRowDef("_akiba_customer");
final RowData rowC = new RowData(new byte[256]);
final RowData rowO = new RowData(new byte[256]);
final RowData rowI = new RowData(new byte[256]);
final RowData rowA = new RowData(new byte[256]);
final RowData rowX = new RowData(new byte[256]);
final int customers;
final int ordersPerCustomer;
final int itemsPerOrder;
final int componentsPerItem;
long cid;
long oid;
long iid;
long xid;
long elapsed;
long count = 0;
TestData(final int customers, final int ordersPerCustomer,
final int itemsPerOrder, final int componentsPerItem) {
this.customers = customers;
this.ordersPerCustomer = ordersPerCustomer;
this.itemsPerOrder = itemsPerOrder;
this.componentsPerItem = componentsPerItem;
}
void insertTestRows() throws Exception {
elapsed = System.nanoTime();
int unique = 0;
for (int c = 0; ++c <= customers;) {
cid = c;
rowC.reset(0, 256);
rowC.createRow(defC, new Object[] { cid, "Customer_" + cid });
store.writeRow(rowC);
for (int o = 0; ++o <= ordersPerCustomer;) {
oid = cid * 1000 + o;
rowO.reset(0, 256);
rowO.createRow(defO, new Object[] { oid, cid, 12345 });
store.writeRow(rowO);
for (int i = 0; ++i <= itemsPerOrder;) {
iid = oid * 1000 + i;
rowI.reset(0, 256);
rowI.createRow(defI, new Object[] { oid, iid, 123456,
654321 });
store.writeRow(rowI);
for (int x = 0; ++x <= componentsPerItem;) {
xid = iid * 1000 + x;
rowX.reset(0, 256);
rowX.createRow(defX, new Object[] { iid, xid, c,
++unique, "Description_" + unique });
store.writeRow(rowX);
}
}
}
for (int a = 0; a < (c % 3); a++) {
rowA.reset(0, 256);
rowA.createRow(defA, new Object[] { c, a, "addr1_" + c,
"addr2_" + c, "addr3_" + c });
store.writeRow(rowA);
}
}
elapsed = System.nanoTime() - elapsed;
}
void visitTestRows(final RowVisitor visitor) throws Exception {
elapsed = System.nanoTime();
int unique = 0;
for (int c = 0; ++c <= customers;) {
cid = c;
rowC.reset(0, 256);
rowC.createRow(defC, new Object[] { cid, "Customer_" + cid });
visitor.visit(0);
for (int o = 0; ++o <= ordersPerCustomer;) {
oid = cid * 1000 + o;
rowO.reset(0, 256);
rowO.createRow(defO, new Object[] { oid, cid, 12345 });
visitor.visit(1);
for (int i = 0; ++i <= itemsPerOrder;) {
iid = oid * 1000 + i;
rowI.reset(0, 256);
rowI.createRow(defI, new Object[] { oid, iid, 123456,
654321 });
visitor.visit(2);
for (int x = 0; ++x <= componentsPerItem;) {
xid = iid * 1000 + x;
rowX.reset(0, 256);
rowX.createRow(defX, new Object[] { iid, xid, c,
++unique, "Description_" + unique });
visitor.visit(3);
}
}
}
}
elapsed = System.nanoTime() - elapsed;
}
int totalRows() {
return totalCustomerRows() + totalOrderRows() + totalItemRows()
+ totalComponentRows();
}
int totalCustomerRows() {
return customers;
}
int totalOrderRows() {
return customers * ordersPerCustomer;
}
int totalItemRows() {
return customers * ordersPerCustomer * itemsPerOrder;
}
int totalComponentRows() {
return customers * ordersPerCustomer * itemsPerOrder
* componentsPerItem;
}
void start() {
elapsed = System.nanoTime();
}
void end() {
elapsed = System.nanoTime() - elapsed;
}
}
@Override
public void setUp() throws Exception {
rowDefCache = new RowDefCache();
store = new PersistitStore(CServerConfig.unitTestConfig(), rowDefCache);
final AkibaInformationSchema ais = new DDLSource()
.buildAIS(DDL_FILE_NAME);
rowDefCache.setAIS(ais);
store.startUp();
store.setOrdinals();
}
@Override
public void tearDown() throws Exception {
store.shutDown();
store = null;
rowDefCache = null;
}
public void testWriteCOIrows() throws Exception {
final TestData td = new TestData(10, 10, 10, 10);
td.insertTestRows();
System.out.println("testWriteCOIrows: inserted " + td.totalRows()
+ " rows in " + (td.elapsed / 1000L) + "us");
}
public void testScanCOIrows() throws Exception {
final TestData td = new TestData(1000, 10, 3, 2);
td.insertTestRows();
System.out.println("testScanCOIrows: inserted " + td.totalRows()
+ " rows in " + (td.elapsed / 1000L) + "us");
{
// simple test - get all I rows
td.start();
int scanCount = 0;
td.rowI.createRow(td.defI, new Object[] { null, null, null });
final byte[] columnBitMap = new byte[] { 0xF };
final int indexId = 0;
final RowCollector rc = store.newRowCollector(
td.defI.getRowDefId(), indexId, 0, td.rowI, td.rowI,
columnBitMap);
final ByteBuffer payload = ByteBufferFactory.allocate(256);
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(), payload
.position(), payload.limit());
for (int p = rowData.getBufferStart(); p < rowData
.getBufferEnd();) {
rowData.prepareRow(p);
p = rowData.getRowEnd();
scanCount++;
}
}
assertEquals(td.totalItemRows(), scanCount);
td.end();
System.out.println("testScanCOIrows: scanned " + scanCount
+ " rows in " + (td.elapsed / 1000L) + "us");
}
{
// select item by IID in user table `item`
td.start();
int scanCount = 0;
td.rowI.createRow(td.defI, new Object[] { null,
Integer.valueOf(1001001), null, null });
final byte[] columnBitMap = new byte[] { (byte) 0x3 };
final int indexId = td.defI.getPKIndexDef().getId();
final RowCollector rc = store.newRowCollector(
td.defI.getRowDefId(), indexId, 0, td.rowI, td.rowI,
columnBitMap);
final ByteBuffer payload = ByteBufferFactory.allocate(256);
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(), payload
.position(), payload.limit());
for (int p = rowData.getBufferStart(); p < rowData
.getBufferEnd();) {
rowData.prepareRow(p);
p = rowData.getRowEnd();
scanCount++;
}
}
assertEquals(1, scanCount);
td.end();
System.out.println("testScanCOIrows: scanned " + scanCount
+ " rows in " + (td.elapsed / 1000L) + "us");
}
{
// select items in COI table by index values on Order
td.start();
int scanCount = 0;
final RowData start = new RowData(new byte[256]);
final RowData end = new RowData(new byte[256]);
// C has 2 columns, A has 5 columns, O has 3 columns, I has 4
// columns, CC has 5 columns
start.createRow(td.defCOI, new Object[] { null, null, null, null,
null, null, null, 1004, null, null, null, null, null, null,
null, null, null, null, null });
end.createRow(td.defCOI, new Object[] { null, null, null, null,
null, null, null, 1007, null, null, null, null, null, null,
null, null, null, null, null });
final byte[] columnBitMap = projection(new RowDef[] { td.defC,
td.defO, td.defI }, td.defCOI.getFieldCount());
int indexId = findIndexId(td.defCOI, td.defO, 0);
final RowCollector rc = store.newRowCollector(td.defCOI
.getRowDefId(), indexId, 0, start, end, columnBitMap);
final ByteBuffer payload = ByteBufferFactory.allocate(256);
//
// Expect all the C, O and I rows for orders 1004 through 1007,
// inclusive
// Total of 40
//
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(), payload
.position(), payload.limit());
for (int p = rowData.getBufferStart(); p < rowData
.getBufferEnd();) {
rowData.prepareRow(p);
System.out.println(rowData.toString(rowDefCache));
p = rowData.getRowEnd();
scanCount++;
}
}
assertEquals(rc.getDeliveredRows(), scanCount);
assertEquals(17, scanCount - rc.getRepeatedRows());
td.end();
System.out.println("testScanCOIrows: scanned " + scanCount
+ " rows in " + (td.elapsed / 1000L) + "us");
}
}
int findIndexId(final RowDef groupRowDef, final RowDef userRowDef,
final int fieldIndex) {
int indexId = -1;
final int findField = fieldIndex + userRowDef.getColumnOffset();
for (final IndexDef indexDef : groupRowDef.getIndexDefs()) {
if (indexDef.getFields().length == 1
&& indexDef.getFields()[0] == findField) {
indexId = indexDef.getId();
}
}
return indexId;
}
final byte[] projection(final RowDef[] rowDefs, final int width) {
final byte[] bitMap = new byte[(width + 7) / 8];
for (final RowDef rowDef : rowDefs) {
for (int bit = rowDef.getColumnOffset(); bit < rowDef
.getColumnOffset()
+ rowDef.getFieldCount(); bit++) {
bitMap[bit / 8] |= (1 << (bit % 8));
}
}
return bitMap;
}
public void testDropTable() throws Exception {
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
assertNotNull(volume.getTree(td.defCOI.getTreeName(), false));
assertNotNull(volume.getTree(td.defO.getPkTreeName(), false));
assertNotNull(volume.getTree(td.defI.getPkTreeName(), false));
store.dropTable(td.defO.getRowDefId());
assertTrue(store.getTableManager()
.getTableStatus(td.defO.getRowDefId()).isDeleted());
assertNotNull(volume.getTree(td.defO.getPkTreeName(), false));
store.dropTable(td.defI.getRowDefId());
assertNotNull(volume.getTree(td.defI.getPkTreeName(), false));
assertTrue(store.getTableManager()
.getTableStatus(td.defI.getRowDefId()).isDeleted());
store.dropTable(td.defA.getRowDefId());
assertNotNull(volume.getTree(td.defA.getPkTreeName(), false));
assertTrue(store.getTableManager()
.getTableStatus(td.defA.getRowDefId()).isDeleted());
store.dropTable(td.defC.getRowDefId());
assertTrue(store.getTableManager()
.getTableStatus(td.defC.getRowDefId()).isDeleted());
store.dropTable(td.defO.getRowDefId());
assertNotNull(volume.getTree(td.defO.getPkTreeName(), false));
assertTrue(store.getTableManager()
.getTableStatus(td.defO.getRowDefId()).isDeleted());
store.dropTable(td.defX.getRowDefId());
assertTrue(isGone(td.defCOI.getTreeName()));
assertTrue(isGone(td.defO.getPkTreeName()));
assertTrue(isGone(td.defI.getPkTreeName()));
assertTrue(isGone(td.defX.getPkTreeName()));
assertTrue(isGone(td.defA.getPkTreeName()));
}
// public void testDropSchema() throws Exception {
// //
// Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
// for (int loop = 0; loop < 20; loop++) {
// final TestData td = new TestData(10, 10, 10, 10);
// td.insertTestRows();
// store.dropSchema(SCHEMA);
// assertTrue(isGone(td.defCOI.getTreeName()));
// assertTrue(isGone(td.defO.getPkTreeName()));
// assertTrue(isGone(td.defI.getPkTreeName()));
// }
// }
public void testBug47() throws Exception {
//
Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
for (int loop = 0; loop < 20; loop++) {
final TestData td = new TestData(10, 10, 10, 10);
td.insertTestRows();
store.dropTable(td.defI.getRowDefId());
store.dropTable(td.defO.getRowDefId());
store.dropTable(td.defC.getRowDefId());
store.dropTable(td.defCOI.getRowDefId());
store.dropTable(td.defA.getRowDefId());
store.dropTable(td.defX.getRowDefId());
store.dropSchema(SCHEMA);
assertTrue(isGone(td.defCOI.getTreeName()));
assertTrue(isGone(td.defO.getPkTreeName()));
assertTrue(isGone(td.defI.getPkTreeName()));
}
}
public void testUniqueIndexes() throws Exception {
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
td.rowX.createRow(td.defX, new Object[] { 1002003, 23890345, 123, 44,
"test1" });
ErrorCode actual = null;
try {
store.writeRow(td.rowX);
}
catch (InvalidOperationException e) {
actual = e.getCode();
}
assertEquals(ErrorCode.DUPLICATE_KEY, actual);
td.rowX.createRow(td.defX, new Object[] { 1002003, 23890345, 123,
44444, "test2" });
store.writeRow(td.rowX);
}
public void testUpdateRows() throws Exception {
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
long cid = 3;
long oid = cid * 1000 + 2;
long iid = oid * 1000 + 4;
long xid = iid * 1000 + 3;
td.rowX.createRow(td.defX, new Object[] { iid, xid, null, null });
final byte[] columnBitMap = new byte[] { (byte) 0x1F };
final ByteBuffer payload = ByteBufferFactory.allocate(1024);
RowCollector rc;
rc = store.newRowCollector(td.defX.getRowDefId(), td.defX
.getPKIndexDef().getId(), 0, td.rowX, td.rowX, columnBitMap);
payload.clear();
assertTrue(rc.collectNextRow(payload));
payload.flip();
RowData oldRowData = new RowData(payload.array(), payload.position(),
payload.limit());
oldRowData.prepareRow(oldRowData.getBufferStart());
RowData newRowData = new RowData(new byte[256]);
newRowData.createRow(td.defX, new Object[] { iid, xid, 4, 424242,
"Description_424242" });
store.updateRow(oldRowData, newRowData);
rc = store.newRowCollector(td.defX.getRowDefId(), td.defX
.getPKIndexDef().getId(), 0, td.rowX, td.rowX, columnBitMap);
payload.clear();
assertTrue(rc.collectNextRow(payload));
payload.flip();
RowData updateRowData = new RowData(payload.array(),
payload.position(), payload.limit());
updateRowData.prepareRow(updateRowData.getBufferStart());
System.out.println(updateRowData.toString(store.getRowDefCache()));
//
// Now attempt to update a leaf table's PK field.
//
newRowData = new RowData(new byte[256]);
newRowData.createRow(td.defX, new Object[] { iid, -xid, 4, 545454,
"Description_545454" });
store.updateRow(updateRowData, newRowData);
rc = store.newRowCollector(td.defX.getRowDefId(), td.defX
.getPKIndexDef().getId(), 0, updateRowData, updateRowData,
columnBitMap);
payload.clear();
assertTrue(!rc.collectNextRow(payload));
rc = store.newRowCollector(td.defX.getRowDefId(), td.defX
.getPKIndexDef().getId(), 0, newRowData, newRowData,
columnBitMap);
assertTrue(rc.collectNextRow(payload));
payload.flip();
updateRowData = new RowData(payload.array(), payload.position(),
payload.limit());
updateRowData.prepareRow(updateRowData.getBufferStart());
System.out.println(updateRowData.toString(store.getRowDefCache()));
// TODO:
// Hand-checked the index tables. Need SELECT on secondary indexes to
// verify them automatically.
}
public void testDeleteRows() throws Exception {
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
td.count = 0;
final RowVisitor visitor = new RowVisitor() {
public void visit(final int depth) throws Exception {
ErrorCode expectedError = null;
ErrorCode actualError = null;
try {
switch (depth) {
case 0:
// TODO - for now we can't do cascading DELETE so we
// expect an error
expectedError = ErrorCode.FK_CONSTRAINT_VIOLATION;
store.deleteRow(td.rowC);
break;
case 1:
// TODO - for now we can't do cascading DELETE so we
// expect an error
expectedError = ErrorCode.FK_CONSTRAINT_VIOLATION;
store.deleteRow(td.rowO);
break;
case 2:
// TODO - for now we can't do cascading DELETE so we
// expect an error
expectedError = ErrorCode.FK_CONSTRAINT_VIOLATION;
store.deleteRow(td.rowI);
break;
case 3:
expectedError = null;
if (td.xid % 2 == 0) {
store.deleteRow(td.rowX);
td.count++;
}
break;
default:
throw new Exception("depth = " + depth);
}
}
catch (InvalidOperationException e) {
actualError = e.getCode();
}
assertEquals("at depth " + depth, expectedError, actualError);
}
};
td.visitTestRows(visitor);
int scanCount = 0;
td.rowX.createRow(td.defX, new Object[0]);
final byte[] columnBitMap = new byte[] { (byte) 0x1F };
final RowCollector rc = store.newRowCollector(td.defX.getRowDefId(),
td.defX.getPKIndexDef().getId(), 0, td.rowX, td.rowX,
columnBitMap);
final ByteBuffer payload = ByteBufferFactory.allocate(256);
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(), payload.position(),
payload.limit());
for (int p = rowData.getBufferStart(); p < rowData.getBufferEnd();) {
rowData.prepareRow(p);
p = rowData.getRowEnd();
scanCount++;
}
}
assertEquals(td.totalComponentRows() - td.count, scanCount);
// TODO:
// Hand-checked the index tables. Need SELECT on secondary indexes to
// verify them automatically.
}
public void testFetchRows() throws Exception {
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
{
final List<RowData> list = store.fetchRows("data_dictionary_test",
"item", "part_id", 1001001, 1001005, "item");
assertEquals(5, list.size());
}
{
final List<RowData> list = store.fetchRows("data_dictionary_test",
"customer", "customer_id", 1, 1, "item");
assertEquals(31, list.size());
}
{
final List<RowData> list = store.fetchRows("data_dictionary_test",
"customer", "customer_id", 1, 2, "address");
assertEquals(5, list.size());
}
{
final List<RowData> list = store.fetchRows("data_dictionary_test",
"customer", "customer_id", 1, 1, null);
for (final RowData rowData : list) {
System.out.println(rowData.toString(rowDefCache));
}
assertEquals(157, list.size());
}
}
public void testCommittedUpdateListener() throws Exception {
final Map<Integer, AtomicInteger> counts = new HashMap<Integer, AtomicInteger>();
final CommittedUpdateListener listener = new CommittedUpdateListener() {
@Override
public void updated(KeyState keyState, RowDef rowDef,
RowData oldRowData, RowData newRowData) {
ai(rowDef).addAndGet(1000000);
}
@Override
public void inserted(KeyState keyState, RowDef rowDef,
RowData rowData) {
ai(rowDef).addAndGet(1);
}
@Override
public void deleted(KeyState keyState, RowDef rowDef,
RowData rowData) {
ai(rowDef).addAndGet(1000);
}
AtomicInteger ai(final RowDef rowDef) {
AtomicInteger ai = counts.get(rowDef.getRowDefId());
if (ai == null) {
ai = new AtomicInteger();
counts.put(rowDef.getRowDefId(), ai);
}
return ai;
}
};
store.addCommittedUpdateListener(listener);
final TestData td = new TestData(5, 5, 5, 5);
td.insertTestRows();
assertEquals(5, counts.get(td.defC.getRowDefId()).intValue());
assertEquals(25, counts.get(td.defO.getRowDefId()).intValue());
assertEquals(125, counts.get(td.defI.getRowDefId()).intValue());
assertEquals(625, counts.get(td.defX.getRowDefId()).intValue());
//
// Now delete or change every other X rows
//
int scanCount = 0;
td.rowX.createRow(td.defX, new Object[0]);
final byte[] columnBitMap = new byte[] { (byte) 0x1F };
final RowCollector rc = store.newRowCollector(td.defX.getRowDefId(),
td.defX.getPKIndexDef().getId(), 0, td.rowX, td.rowX,
columnBitMap);
final ByteBuffer payload = ByteBufferFactory.allocate(256);
while (rc.hasMore()) {
payload.clear();
while (rc.collectNextRow(payload))
;
payload.flip();
RowData rowData = new RowData(payload.array(), payload.position(),
payload.limit());
for (int p = rowData.getBufferStart(); p < rowData.getBufferEnd();) {
rowData.prepareRow(p);
if (scanCount++ % 2 == 0) {
store.deleteRow(rowData);
} else {
store.updateRow(rowData, rowData);
}
p = rowData.getRowEnd();
}
}
assertEquals(5, counts.get(td.defC.getRowDefId()).intValue());
assertEquals(25, counts.get(td.defO.getRowDefId()).intValue());
assertEquals(125, counts.get(td.defI.getRowDefId()).intValue());
assertEquals(312313625, counts.get(td.defX.getRowDefId()).intValue());
}
public void testDeferIndex() throws Exception {
final TestData td = new TestData(3, 3, 0, 0);
store.setDeferIndexes(true);
td.insertTestRows();
final StringWriter a, b, c, d;
dumpIndexes(new PrintWriter(a = new StringWriter()));
store.flushIndexes();
dumpIndexes(new PrintWriter(b = new StringWriter()));
store.deleteIndexes("");
dumpIndexes(new PrintWriter(c = new StringWriter()));
store.buildIndexes("");
dumpIndexes(new PrintWriter(d = new StringWriter()));
assertTrue(!a.toString().equals(b.toString()));
assertEquals(a.toString(), c.toString());
assertEquals(b.toString(), d.toString());
}
public void testRebuildIndex() throws Exception {
final TestData td = new TestData(3, 3, 3, 3);
td.insertTestRows();
final StringWriter a, b, c;
dumpIndexes(new PrintWriter(a = new StringWriter()));
store.deleteIndexes("");
dumpIndexes(new PrintWriter(b = new StringWriter()));
store.buildIndexes("");
dumpIndexes(new PrintWriter(c = new StringWriter()));
assertTrue(!a.toString().equals(b.toString()));
assertEquals(a.toString(), c.toString());
}
private void dumpIndexes(final PrintWriter pw) throws Exception {
for (final RowDef rowDef : rowDefCache.getRowDefs()) {
pw.println(rowDef);
for (final IndexDef indexDef : rowDef.getIndexDefs()) {
pw.println(indexDef);
dumpIndex(indexDef, pw);
}
}
pw.flush();
}
private void dumpIndex(final IndexDef indexDef, final PrintWriter pw)
throws Exception {
final Exchange ex = store.getExchange(indexDef.getRowDef(), indexDef);
ex.clear();
while (ex.next(true)) {
pw.println(ex.getKey());
}
pw.flush();
}
private boolean isGone(final String treeName) throws Exception {
Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
final Tree tree = volume.getTree(treeName, false);
if (tree == null) {
return true;
}
final Exchange exchange = store.getExchange(treeName);
exchange.clear();
return !exchange.hasChildren();
}
}
| Test added to exhibit Bug 283 | src/test/java/com/akiban/cserver/store/PersistitStoreWithAISTest.java | Test added to exhibit Bug 283 | <ide><path>rc/test/java/com/akiban/cserver/store/PersistitStoreWithAISTest.java
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<del>import com.akiban.cserver.InvalidOperationException;
<del>import com.akiban.message.ErrorCode;
<ide> import junit.framework.TestCase;
<ide>
<ide> import com.akiban.ais.ddl.DDLSource;
<ide> import com.akiban.cserver.CServerConfig;
<ide> import com.akiban.cserver.CServerConstants;
<ide> import com.akiban.cserver.IndexDef;
<add>import com.akiban.cserver.InvalidOperationException;
<ide> import com.akiban.cserver.RowData;
<ide> import com.akiban.cserver.RowDef;
<ide> import com.akiban.cserver.RowDefCache;
<add>import com.akiban.message.ErrorCode;
<ide> import com.akiban.util.ByteBufferFactory;
<ide> import com.persistit.Exchange;
<ide> import com.persistit.KeyState;
<add>import com.persistit.TransactionRunnable;
<ide> import com.persistit.Tree;
<ide> import com.persistit.Volume;
<add>import com.persistit.exception.RollbackException;
<ide>
<ide> public class PersistitStoreWithAISTest extends TestCase implements
<ide> CServerConstants {
<ide> return rowDefCache.getRowDef(GROUP_SCHEMA + "." + name);
<ide> }
<ide>
<del> private class TestData {
<add> class TestData {
<ide> final RowDef defC = userRowDef("customer");
<ide> final RowDef defO = userRowDef("order");
<ide> final RowDef defI = userRowDef("item");
<ide> while (rc.collectNextRow(payload))
<ide> ;
<ide> payload.flip();
<del> RowData rowData = new RowData(payload.array(), payload
<del> .position(), payload.limit());
<add> RowData rowData = new RowData(payload.array(),
<add> payload.position(), payload.limit());
<ide> for (int p = rowData.getBufferStart(); p < rowData
<ide> .getBufferEnd();) {
<ide> rowData.prepareRow(p);
<ide> // select item by IID in user table `item`
<ide> td.start();
<ide> int scanCount = 0;
<del> td.rowI.createRow(td.defI, new Object[] { null,
<del> Integer.valueOf(1001001), null, null });
<add> td.rowI.createRow(td.defI,
<add> new Object[] { null, Integer.valueOf(1001001), null, null });
<ide>
<ide> final byte[] columnBitMap = new byte[] { (byte) 0x3 };
<ide> final int indexId = td.defI.getPKIndexDef().getId();
<ide> while (rc.collectNextRow(payload))
<ide> ;
<ide> payload.flip();
<del> RowData rowData = new RowData(payload.array(), payload
<del> .position(), payload.limit());
<add> RowData rowData = new RowData(payload.array(),
<add> payload.position(), payload.limit());
<ide> for (int p = rowData.getBufferStart(); p < rowData
<ide> .getBufferEnd();) {
<ide> rowData.prepareRow(p);
<ide> td.defO, td.defI }, td.defCOI.getFieldCount());
<ide>
<ide> int indexId = findIndexId(td.defCOI, td.defO, 0);
<del> final RowCollector rc = store.newRowCollector(td.defCOI
<del> .getRowDefId(), indexId, 0, start, end, columnBitMap);
<add> final RowCollector rc = store.newRowCollector(
<add> td.defCOI.getRowDefId(), indexId, 0, start, end,
<add> columnBitMap);
<ide> final ByteBuffer payload = ByteBufferFactory.allocate(256);
<ide> //
<ide> // Expect all the C, O and I rows for orders 1004 through 1007,
<ide> while (rc.collectNextRow(payload))
<ide> ;
<ide> payload.flip();
<del> RowData rowData = new RowData(payload.array(), payload
<del> .position(), payload.limit());
<add> RowData rowData = new RowData(payload.array(),
<add> payload.position(), payload.limit());
<ide> for (int p = rowData.getBufferStart(); p < rowData
<ide> .getBufferEnd();) {
<ide> rowData.prepareRow(p);
<ide> final byte[] bitMap = new byte[(width + 7) / 8];
<ide> for (final RowDef rowDef : rowDefs) {
<ide> for (int bit = rowDef.getColumnOffset(); bit < rowDef
<del> .getColumnOffset()
<del> + rowDef.getFieldCount(); bit++) {
<add> .getColumnOffset() + rowDef.getFieldCount(); bit++) {
<ide> bitMap[bit / 8] |= (1 << (bit % 8));
<ide> }
<ide> }
<ide> assertTrue(isGone(td.defA.getPkTreeName()));
<ide> }
<ide>
<del>// public void testDropSchema() throws Exception {
<del>// //
<del>// Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
<del>// for (int loop = 0; loop < 20; loop++) {
<del>// final TestData td = new TestData(10, 10, 10, 10);
<del>// td.insertTestRows();
<del>// store.dropSchema(SCHEMA);
<del>// assertTrue(isGone(td.defCOI.getTreeName()));
<del>// assertTrue(isGone(td.defO.getPkTreeName()));
<del>// assertTrue(isGone(td.defI.getPkTreeName()));
<del>// }
<del>// }
<add> // public void testDropSchema() throws Exception {
<add> // //
<add> // Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
<add> // for (int loop = 0; loop < 20; loop++) {
<add> // final TestData td = new TestData(10, 10, 10, 10);
<add> // td.insertTestRows();
<add> // store.dropSchema(SCHEMA);
<add> // assertTrue(isGone(td.defCOI.getTreeName()));
<add> // assertTrue(isGone(td.defO.getPkTreeName()));
<add> // assertTrue(isGone(td.defI.getPkTreeName()));
<add> // }
<add> // }
<ide>
<ide> public void testBug47() throws Exception {
<ide> //
<ide> ErrorCode actual = null;
<ide> try {
<ide> store.writeRow(td.rowX);
<del> }
<del> catch (InvalidOperationException e) {
<add> } catch (InvalidOperationException e) {
<ide> actual = e.getCode();
<ide> }
<ide> assertEquals(ErrorCode.DUPLICATE_KEY, actual);
<ide> default:
<ide> throw new Exception("depth = " + depth);
<ide> }
<del> }
<del> catch (InvalidOperationException e) {
<add> } catch (InvalidOperationException e) {
<ide> actualError = e.getCode();
<ide> }
<ide> assertEquals("at depth " + depth, expectedError, actualError);
<ide> assertEquals(a.toString(), c.toString());
<ide> }
<ide>
<add> public void testBug283() throws Exception {
<add> //
<add> // Creates the index tables ahead of the h-table. This
<add> // affects the Transaction commit order.
<add> //
<add> store.getDb().getTransaction().run(new TransactionRunnable() {
<add> public void runTransaction() throws RollbackException {
<add> for (int index = 1; index < 13; index++) {
<add> final String treeName = "_akiba_customer$$" + index;
<add> try {
<add> final Exchange exchange = store.getExchange(treeName);
<add> exchange.to("testBug283").store();
<add> store.releaseExchange(exchange);
<add> } catch (Exception e) {
<add> throw new RollbackException(e);
<add> }
<add> }
<add> }
<add> });
<add> final TestData td = new TestData(1, 1, 1, 1);
<add> td.insertTestRows();
<add> final AtomicBoolean broken = new AtomicBoolean(false);
<add> final long expires = System.nanoTime() + 300000000000L; // 30 seconds
<add> final AtomicInteger lastInserted = new AtomicInteger();
<add> final AtomicInteger scanCount = new AtomicInteger();
<add> final Thread thread1 = new Thread(new Runnable() {
<add> public void run() {
<add> for (int xid = 1001001002; System.nanoTime() < expires
<add> && !broken.get(); xid++) {
<add> td.rowX.createRow(td.defX, new Object[] { 1001001, xid,
<add> 123, xid - 100100100, "part " + xid });
<add> try {
<add> store.writeRow(td.rowX);
<add> lastInserted.set(xid);
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> broken.set(true);
<add> break;
<add> }
<add> }
<add> }
<add> }, "INSERTER");
<add>
<add> final Thread thread2 = new Thread(new Runnable() {
<add> public void run() {
<add> final RowData start = new RowData(new byte[256]);
<add> final RowData end = new RowData(new byte[256]);
<add> final byte[] columnBitMap = new byte[] { (byte) 0xF };
<add> final ByteBuffer payload = ByteBufferFactory.allocate(100000);
<add> while (System.nanoTime() < expires && !broken.get()) {
<add> int xid = lastInserted.get();
<add> start.createRow(td.defX, new Object[] { 1001001, xid, null,
<add> null });
<add> end.createRow(td.defX, new Object[] { 1001001, xid + 10000,
<add> null, null });
<add>
<add> final int indexId = td.defX.getPKIndexDef().getId();
<add>
<add> try {
<add> final RowCollector rc = store.newRowCollector(
<add> td.defX.getRowDefId(), indexId, 0, start, end,
<add> columnBitMap);
<add> while (rc.hasMore()) {
<add> payload.clear();
<add> while (rc.collectNextRow(payload))
<add> ;
<add> payload.flip();
<add> RowData rowData = new RowData(payload.array(),
<add> payload.position(), payload.limit());
<add> for (int p = rowData.getBufferStart(); p < rowData.getBufferEnd();) {
<add> rowData.prepareRow(p);
<add> p = rowData.getRowEnd();
<add> scanCount.incrementAndGet();
<add> }
<add> }
<add> // } catch (InvalidOperationException ioe) {
<add> // broken.set(true);
<add> // break;
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> broken.set(true);
<add> break;
<add> }
<add>
<add> }
<add> }
<add> }, "SCANNER");
<add>
<add> thread1.start();
<add> thread2.start();
<add> thread1.join();
<add> thread2.join();
<add> assertTrue(!broken.get());
<add>
<add> }
<add>
<ide> private void dumpIndexes(final PrintWriter pw) throws Exception {
<ide> for (final RowDef rowDef : rowDefCache.getRowDefs()) {
<ide> pw.println(rowDef);
<ide> }
<ide> pw.flush();
<ide> }
<del>
<add>
<ide> private boolean isGone(final String treeName) throws Exception {
<ide> Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME);
<ide> final Tree tree = volume.getTree(treeName, false); |
|
Java | apache-2.0 | f1a1aa9a7cf712e55b5500cdf8e9485a670e3e65 | 0 | spiffyui/spiffyui,spiffyui/spiffyui,spiffyui/spiffyui | /*******************************************************************************
*
* Copyright 2011 Spiffy UI Team
*
* 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.spiffyui.client.rest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.spiffyui.client.JSONUtil;
import org.spiffyui.client.JSUtil;
import org.spiffyui.client.MessageUtil;
import org.spiffyui.client.i18n.SpiffyUIStrings;
import org.spiffyui.client.rest.v2.RESTOAuthProvider;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptException;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
/**
* A set of utilities for calling REST from GWT.
*/
public final class RESTility
{
private static final SpiffyUIStrings STRINGS = (SpiffyUIStrings) GWT.create(SpiffyUIStrings.class);
private static final String LOCALE_COOKIE = "Spiffy_Locale";
private static final RESTility RESTILITY = new RESTility();
/**
* This method represents an HTTP GET request
*/
public static final HTTPMethod GET = RESTILITY.new HTTPMethod("GET");
/**
* This method represents an HTTP PUT request
*/
public static final HTTPMethod PUT = RESTILITY.new HTTPMethod("PUT");
/**
* This method represents an HTTP POST request
*/
public static final HTTPMethod POST = RESTILITY.new HTTPMethod("POST");
/**
* This method represents an HTTP DELETE request
*/
public static final HTTPMethod DELETE = RESTILITY.new HTTPMethod("DELETE");
private static boolean g_inLoginProcess = false;
private static List<RESTLoginCallBack> g_loginListeners = new ArrayList<RESTLoginCallBack>();
private int m_callCount = 0;
private boolean m_hasLoggedIn = false;
private boolean m_logInListenerCalled = false;
private boolean m_secureCookies = false;
private String m_sessionCookie = "Spiffy_Session";
private static RESTAuthProvider g_authProvider;
private static RESTOAuthProvider g_oAuthProvider;
private String m_sessionCookiePath;
/**
* This is a helper type class so we can pass the HTTP method as a type safe
* object instead of a string.
*/
public final class HTTPMethod
{
private String m_method;
/**
* Create a new HTTPMethod object
*
* @param method the method
*/
private HTTPMethod(String method)
{
m_method = method;
}
/**
* Get the method string for this object
*
* @return the method string
*/
private String getMethod()
{
return m_method;
}
}
private Map<RESTCallback, RESTCallStruct> m_restCalls = new HashMap<RESTCallback, RESTCallStruct>();
private String m_userToken = null;
private String m_tokenType = null;
private String m_tokenServerUrl = null;
private String m_username = null;
private String m_tokenServerLogoutUrl = null;
private String m_bestLocale = null;
/**
* Just to make sure that nobody else can instatiate this object.
*/
private RESTility()
{
}
private static final String URI_KEY = "uri";
private static final String SIGNOFF_URI_KEY = "signoffuri";
static {
RESTAuthProvider authUtil = new AuthUtil();
RESTility.setAuthProvider(authUtil);
}
/**
* <p>
* Sets the authentication provider used for future REST requests.
* </p>
*
* <p>
* By default authentication is provided by the AuthUtil class, but this
* class may be replaced to provide support for custom authentication schemes.
* </p>
*
* @param authProvider
* the new authentication provider
*
* @see AuthUtil
*/
public static void setAuthProvider(RESTAuthProvider authProvider)
{
g_authProvider = authProvider;
}
/**
* Set the OAuth provider for this application.
*
* @param oAuthProvider
* the oAuth provider
*/
public static void setOAuthProvider(RESTOAuthProvider oAuthProvider)
{
g_oAuthProvider = oAuthProvider;
}
/**
* <p>
* Sets the name of the Spiffy UI session cookie.
* </p>
*
* <p>
* Spiffy UI uses a local cookie to save the current user token. This cookie has
* the name <code>Spiffy_Session</code> by default. This method will change the
* name of the cookie to something else.
* </p>
*
* <p>
* Calling this method will not change the name of the cookie until a REST call is made
* which causes the cookie to be reset.
* </p>
*
* @param name the name of the cookie Spiffy UI session cookie
*/
public static void setSessionCookieName(String name)
{
if (name == null) {
throw new IllegalArgumentException("The session cookie name must not be null");
}
RESTILITY.m_sessionCookie = name;
}
/**
* Gets the current name of the Spiffy UI session cookie.
*
* @return the name of the session cookie
*/
public static String getSessionCookieName()
{
return RESTILITY.m_sessionCookie;
}
/**
* <p>
* Sets if RESTility cookies should only be sent via SSL.
* </p>
*
* <p>
* RESTility stores a small amount of information locally so users can refresh the page
* without logging out or resetting their locale. This information is sometimes stored
* in cookies. These cookies are normally not sent back to the server, but can be in
* some cases.
* </p>
*
* <p>
* If your application is concerned with sercurity you might want to require all cookies
* are only sent via a secure connection (SSL). Set this method true to make all cookies
* stored be RESTility and Spiffy UI require an SSL connection before they are sent.
* </p>
*
* <p>
* The default value of this field is false.
* </p>
*
* @param secure true if cookies should require SSL and false otherwise
*/
public static void setRequireSecureCookies(boolean secure)
{
RESTILITY.m_secureCookies = secure;
}
/**
* Determines if RESTility will force all cookies to require SSL.
*
* @return true if cookies require SSL and false otherwise
*/
public static boolean requiresSecureCookies()
{
return RESTILITY.m_secureCookies;
}
/**
* Gets the current auth provider which will be used for future REST calls.
*
* @return The current auth provider
*/
public static RESTAuthProvider getAuthProvider()
{
return g_authProvider;
}
/**
* Make a login request using RESTility authentication framework.
*
* @param callback the rest callback called when the login is complete
* @param response the response from the server requiring the login
* @param url the URL of the authentication server
* @param errorCode the error code from the server returned with the 401
*
* @exception RESTException
* if there was an exception when making the login request
*/
public static void login(RESTCallback callback, Response response, String url, String errorCode)
throws RESTException
{
RESTILITY.doLogin(callback, response, url, errorCode, null);
}
/**
* Make a login request using RESTility authentication framework.
*
* @param callback the rest callback called when the login is complete
* @param response the response from the server requiring the login
* @param url the URL of the authentication server
* @param exception the RESTException which prompted this login
*
* @exception RESTException
* if there was an exception when making the login request
*/
public static void login(RESTCallback callback, Response response, String url, RESTException exception)
throws RESTException
{
RESTILITY.doLogin(callback, response, url, null, exception);
}
private static String trimQuotes(String header)
{
if (header == null) {
return header;
}
String ret = header;
if (ret.startsWith("\"")) {
ret = ret.substring(1);
}
if (ret.endsWith("\"")) {
ret = ret.substring(0, ret.length() - 1);
}
return ret;
}
private void doLogin(RESTCallback callback, Response response, String url, String errorCode, RESTException exception)
throws RESTException
{
JSUtil.println("doLogin(" + url + ", " + errorCode + ")");
/*
When the server returns a status code 401 they are required
to send back the WWW-Authenticate header to tell us how to
authenticate.
*/
String auth = response.getHeader("WWW-Authenticate");
if (auth == null) {
throw new RESTException(RESTException.NO_AUTH_HEADER,
"", STRINGS.noAuthHeader(),
new HashMap<String, String>(),
response.getStatusCode(),
url);
}
/*
* Now we have to parse out the token server URL and other information.
*
* The String should look like this:
*
* X-OPAQUE uri=<token server URI>,signoffUri=<token server logout url>
*
* First we'll remove the token type
*/
String tokenType = auth;
String loginUri = null;
String logoutUri = null;
JSUtil.println("auth: " + auth);
if (tokenType.indexOf(' ') != -1) {
tokenType = tokenType.substring(0, tokenType.indexOf(' ')).trim();
auth = auth.substring(auth.indexOf(' ') + 1);
if (tokenType.indexOf(',') != -1) {
String props[] = auth.split(",");
JSUtil.println("props: " + props);
for (String prop : props) {
if (prop.trim().toLowerCase().startsWith(URI_KEY)) {
loginUri = prop.substring(prop.indexOf('=') + 1, prop.length()).trim();
} else if (prop.trim().toLowerCase().startsWith(SIGNOFF_URI_KEY)) {
logoutUri = prop.substring(prop.indexOf('=') + 1, prop.length()).trim();
}
}
loginUri = trimQuotes(loginUri);
logoutUri = trimQuotes(logoutUri);
if (logoutUri.trim().length() == 0) {
logoutUri = loginUri;
}
}
}
JSUtil.println("tokenType: " + tokenType);
setTokenType(tokenType);
setTokenServerURL(loginUri);
setTokenServerLogoutURL(logoutUri);
removeCookie(RESTILITY.m_sessionCookie);
removeCookie(LOCALE_COOKIE);
JSUtil.println("g_oAuthProvider: " + g_oAuthProvider);
JSUtil.println("tokenType: " + tokenType);
if (g_oAuthProvider != null && tokenType.equalsIgnoreCase("Bearer") || tokenType.equalsIgnoreCase("MAC")) {
handleOAuthRequest(callback, loginUri, response, exception);
} else if (g_authProvider instanceof org.spiffyui.client.rest.v2.RESTAuthProvider) {
((org.spiffyui.client.rest.v2.RESTAuthProvider) g_authProvider).showLogin(callback, loginUri, response, exception);
} else {
g_authProvider.showLogin(callback, loginUri, errorCode);
}
}
private void handleOAuthRequest(RESTCallback callback, String tokenServerUrl, Response response, RESTException exception)
throws RESTException
{
String authUrl = g_oAuthProvider.getAuthServerUrl(callback, tokenServerUrl, response, exception);
JSUtil.println("authUrl: " + authUrl);
handleOAuthRequestJS(this, authUrl, g_oAuthProvider.getClientId(), g_oAuthProvider.getScope());
}
private void oAuthComplete(String token, String tokenType)
{
setTokenType(tokenType);
setUserToken(token);
finishRESTCalls();
}
private native String base64Encode(String s) /*-{
return $wnd.Base64.encode(s);
}-*/;
private native void handleOAuthRequestJS(RESTility callback, String authUrl, String clientId, String scope) /*-{
$wnd.spiffyui.oAuthAuthenticate(authUrl, clientId, scope, function(token, tokenType) {
[email protected]::oAuthComplete(Ljava/lang/String;Ljava/lang/String;)(token,tokenType);
});
}-*/;
/**
* Returns HTTPMethod corresponding to method name.
* If the passed in method does not match any, GET is returned.
*
* @param method a String representation of a http method
* @return the HTTPMethod corresponding to the passed in String method representation.
*/
public static HTTPMethod parseString(String method)
{
if (POST.getMethod().equalsIgnoreCase(method)) {
return POST;
} else if (PUT.getMethod().equalsIgnoreCase(method)) {
return PUT;
} else if (DELETE.getMethod().equalsIgnoreCase(method)) {
return DELETE;
} else {
//Otherwise return GET
return GET;
}
}
/**
* Upon logout, delete cookie and clear out all member variables
*/
public static void doLocalLogout()
{
RESTILITY.m_hasLoggedIn = false;
RESTILITY.m_logInListenerCalled = false;
RESTILITY.m_callCount = 0;
RESTILITY.m_userToken = null;
RESTILITY.m_tokenType = null;
RESTILITY.m_tokenServerUrl = null;
RESTILITY.m_tokenServerLogoutUrl = null;
RESTILITY.m_username = null;
removeCookie(RESTILITY.m_sessionCookie);
removeCookie(LOCALE_COOKIE);
}
/**
* The normal GWT mechanism for removing cookies will remove a cookie at the path
* the page is on. The is a possibility that the session cookie was set on the
* server with a slightly different path. In that case we need to try to delete
* the cookie on all the paths of the current URL. This method handles that case.
*
* @param name the name of the cookie to remove
*/
private static void removeCookie(String name)
{
Cookies.removeCookie(name);
if (Cookies.getCookie(name) != null) {
/*
* This could mean that the cookie was there,
* but was on a different path than the one that
* we get by default.
*/
removeCookie(name, Window.Location.getPath());
}
}
private static void removeCookie(String name, String currentPath)
{
Cookies.removeCookie(name, currentPath);
if (Cookies.getCookie(name) != null) {
/*
* This could mean that the cookie was there,
* but was on a different path than the one that
* we were passed. In that case we'll bump up
* the path and try again.
*/
String path = currentPath;
if (path.charAt(0) != '/') {
path = "/" + path;
}
int slashloc = path.lastIndexOf('/');
if (slashloc > 1) {
path = path.substring(0, slashloc);
removeCookie(name, path);
}
}
}
/**
* In some cases, like login, the original REST call returns an error and we
* need to run it again. This call gets the same REST request information and
* tries the request again.
*/
public static void finishRESTCalls()
{
for (RESTCallback callback : RESTILITY.m_restCalls.keySet()) {
RESTCallStruct struct = RESTILITY.m_restCalls.get(callback);
if (struct != null && struct.shouldReplay()) {
callREST(struct.getUrl(), struct.getData(), struct.getMethod(), callback);
}
}
}
/**
* Make a rest call using an HTTP GET to the specified URL.
*
* @param callback the callback to invoke
* @param url the properly encoded REST url to call
*/
public static void callREST(String url, RESTCallback callback)
{
callREST(url, "", RESTility.GET, callback);
}
/**
* Make a rest call using an HTTP GET to the specified URL including
* the specified data..
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param callback the callback to invoke
*/
public static void callREST(String url, String data, RESTCallback callback)
{
callREST(url, data, RESTility.GET, callback);
}
/**
* Set the user token in JavaScript memory and and saves it in a cookie.
* @param token user token
*/
public static void setUserToken(String token)
{
g_inLoginProcess = false;
RESTILITY.m_userToken = token;
setSessionToken();
}
/**
* Set the authentication server url in JavaScript memory and and saves it in a cookie.
* @param url authentication server url
*/
public static void setTokenServerURL(String url)
{
RESTILITY.m_tokenServerUrl = url;
setSessionToken();
}
/**
* Fire the login success event to all listeners if it hasn't been fired already.
*/
public static void fireLoginSuccess()
{
RESTILITY.m_hasLoggedIn = true;
if (!RESTILITY.m_logInListenerCalled) {
for (RESTLoginCallBack listener : g_loginListeners) {
listener.onLoginSuccess();
}
RESTILITY.m_logInListenerCalled = true;
}
}
/**
* <p>
* Set the type of token RESTility will pass.
* </p>
*
* <p>
* Most of the time the token type is specified by the REST server and the
* client does not have to specify this value. This method is mostly used
* for testing.
* </p>
*
* @param type the token type
*/
public static void setTokenType(String type)
{
RESTILITY.m_tokenType = type;
setSessionToken();
}
/**
* Set the user name in JavaScript memory and and saves it in a cookie.
* @param username user name
*/
public static void setUsername(String username)
{
RESTILITY.m_username = username;
setSessionToken();
}
/**
* Set the authentication server logout url in JavaScript memory and and saves it in a cookie.
* @param url authentication server logout url
*/
public static void setTokenServerLogoutURL(String url)
{
RESTILITY.m_tokenServerLogoutUrl = url;
setSessionToken();
}
/**
* We can't know the best locale until after the user logs in because we need to consider
* their locale from the identity vault. So we get the locale as part of the identity
* information and then store this in a cookie. If the cookie doesn't match the current
* locale then we need to refresh the page so we can reload the JavaScript libraries.
*
* @param locale the locale
*/
public static void setBestLocale(String locale)
{
if (getBestLocale() != null) {
if (!getBestLocale().equals(locale)) {
/*
If the best locale from the server doesn't
match the cookie. That means we set the cookie
with the new locale and refresh the page.
*/
RESTILITY.m_bestLocale = locale;
setSessionToken();
JSUtil.reload();
} else {
/*
If the best locale from the server matches
the best locale from the cookie then we are
done.
*/
return;
}
} else {
/*
This means they didn't have a best locale from
the server stored as a cookie in the client. So
we set the locale from the server into the cookie.
*/
RESTILITY.m_bestLocale = locale;
setSessionToken();
/*
* If there are any REST requests in process when we refresh
* the page they will cause errors that show up before the
* page reloads. Hiding the page makes those errors invisible.
*/
JSUtil.hide("body", "");
JSUtil.reload();
}
}
/**
* <p>
* Set the path for the Spiffy_Session cookie.
* </p>
*
* <p>
* When Spiffy UI uses token based authentication it saves token and user information
* in a cookie named Spiffy_Session. This cookie allows the user to remain logged in
* after they refresh the page the reset JavaScript memory.
* </p>
*
* <p>
* By default that cookie uses the path of the current page. If an application uses
* multiple pages it can make sense to use a more general path for this cookie to make
* it available to other URLs in the application.
* </p>
*
* <p>
* The path must be set before the first authentication request. If it is called
* afterward the cookie path will not change.
* </p>
*
* @param newPath the new path for the cookie or null if the cookie should use the path of the current page
*/
public static void setSessionCookiePath(String newPath)
{
RESTILITY.m_sessionCookiePath = newPath;
}
/**
* Get the path of the session cookie. By default this is null indicating a path of
* the current page will be used.
*
* @return the current session cookie path.
*/
public static String getSessionCookiePath()
{
return RESTILITY.m_sessionCookiePath;
}
private static void setSessionToken()
{
if (RESTILITY.m_sessionCookiePath != null) {
Cookies.setCookie(RESTILITY.m_sessionCookie, RESTILITY.m_tokenType + "," +
RESTILITY.m_userToken + "," + RESTILITY.m_tokenServerUrl + "," +
RESTILITY.m_tokenServerLogoutUrl + "," + RESTILITY.m_username,
null, null, RESTILITY.m_sessionCookiePath, RESTILITY.m_secureCookies);
if (RESTILITY.m_bestLocale != null) {
Cookies.setCookie(LOCALE_COOKIE, RESTILITY.m_bestLocale, null, null,
RESTILITY.m_sessionCookiePath, RESTILITY.m_secureCookies);
}
} else {
Cookies.setCookie(RESTILITY.m_sessionCookie, RESTILITY.m_tokenType + "," +
RESTILITY.m_userToken + "," + RESTILITY.m_tokenServerUrl + "," +
RESTILITY.m_tokenServerLogoutUrl + "," + RESTILITY.m_username,
null, null, null, RESTILITY.m_secureCookies);
if (RESTILITY.m_bestLocale != null) {
Cookies.setCookie(LOCALE_COOKIE, RESTILITY.m_bestLocale, null, null, null, RESTILITY.m_secureCookies);
}
}
}
/**
* Returns a boolean flag indicating whether user has logged in or not
*
* @return boolean indicating whether user has logged in or not
*/
public static boolean hasUserLoggedIn()
{
return RESTILITY.m_hasLoggedIn;
}
/**
* Returns user's full authentication token, prefixed with "X-OPAQUE"
*
* @return user's full authentication token prefixed with "X-OPAQUE"
*/
public static String getFullAuthToken()
{
return getTokenType() + " " + getUserToken();
}
private static void checkSessionCookie()
{
String sessionCookie = Cookies.getCookie(RESTILITY.m_sessionCookie);
if (sessionCookie != null && sessionCookie.length() > 0) {
// If the cookie value is quoted, strip off the enclosing quotes
if (sessionCookie.length() > 2 &&
sessionCookie.charAt(0) == '"' &&
sessionCookie.charAt(sessionCookie.length() - 1) == '"') {
sessionCookie = sessionCookie.substring(1, sessionCookie.length() - 1);
}
String sessionCookiePieces [] = sessionCookie.split(",");
if (sessionCookiePieces != null) {
if (sessionCookiePieces.length >= 1) {
RESTILITY.m_tokenType = sessionCookiePieces [0];
}
if (sessionCookiePieces.length >= 2) {
RESTILITY.m_userToken = sessionCookiePieces [1];
}
if (sessionCookiePieces.length >= 3) {
RESTILITY.m_tokenServerUrl = sessionCookiePieces [2];
}
if (sessionCookiePieces.length >= 4) {
RESTILITY.m_tokenServerLogoutUrl = sessionCookiePieces [3];
}
if (sessionCookiePieces.length >= 5) {
RESTILITY.m_username = sessionCookiePieces [4];
}
}
}
}
/**
* Returns user's authentication token
*
* @return user's authentication token
*/
public static String getUserToken()
{
if (RESTILITY.m_userToken == null) {
checkSessionCookie();
}
return RESTILITY.m_userToken;
}
/**
* Returns user's authentication token type
*
* @return user's authentication token type
*/
public static String getTokenType()
{
if (RESTILITY.m_tokenType == null) {
checkSessionCookie();
}
return RESTILITY.m_tokenType;
}
/**
* Returns the authentication server url
*
* @return authentication server url
*/
public static String getTokenServerUrl()
{
if (RESTILITY.m_tokenServerUrl == null) {
checkSessionCookie();
}
return RESTILITY.m_tokenServerUrl;
}
/**
* Returns authentication server logout url
*
* @return authentication server logout url
*/
public static String getTokenServerLogoutUrl()
{
if (RESTILITY.m_tokenServerLogoutUrl == null) {
checkSessionCookie();
}
return RESTILITY.m_tokenServerLogoutUrl;
}
/**
* Returns the name of the currently logged in user or null
* if the current user is not logged in.
*
* @return user name
*/
public static String getUsername()
{
if (RESTILITY.m_username == null) {
checkSessionCookie();
}
return RESTILITY.m_username;
}
/**
* Returns best matched locale
*
* @return best matched locale
*/
public static String getBestLocale()
{
if (RESTILITY.m_bestLocale != null) {
return RESTILITY.m_bestLocale;
} else {
RESTILITY.m_bestLocale = Cookies.getCookie(LOCALE_COOKIE);
return RESTILITY.m_bestLocale;
}
}
public static List<RESTLoginCallBack> getLoginListeners()
{
return g_loginListeners;
}
/**
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method, RESTCallback callback)
{
callREST(url, data, method, callback, false, null);
}
/**
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
* @param etag the option etag for this request
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method,
RESTCallback callback, String etag)
{
callREST(url, data, method, callback, false, etag);
}
/**
* The client can't really handle the test for all XSS attacks, but we can
* do some general sanity checking.
*
* @param data the data to check
*
* @return true if the data is valid and false otherwise
*/
private static boolean hasPotentialXss(final String data)
{
if (data == null) {
return false;
}
String uppercaseData = data.toUpperCase();
if (uppercaseData.indexOf("<SCRIPT") > -1) {
return true;
}
return false;
}
/**
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
* @param isLoginRequest
* true if this is a request to login and false otherwise
* @param etag the option etag for this request
*
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method,
RESTCallback callback, boolean isLoginRequest, String etag)
{
callREST(url, data, method, callback, isLoginRequest, true, etag);
}
/**
* <p>
* Make an HTTP call and get the results as a JSON object. This method handles
* allows the caller to override any HTTP headers in the request.
* </p>
*
* <p>
* By default RESTility sets two HTTP headers: <code>Accept=application/json</code> and
* <code>Accept-Charset=UTF-8</code>. Other headers are added by the browser running this
* application.
* </p>
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
* @param etag the option etag for this request
* @param headers a map containing the headers to the HTTP request. Any item
* in this map will override the default headers.
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method,
RESTCallback callback, String etag, Map<String, String> headers)
{
callREST(url, data, method, callback, false, true, etag, headers);
}
/**
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
* @param isLoginRequest
* true if this is a request to login and false otherwise
* @param shouldReplay true if this request should repeat after a login request
* if this request returns a 401
* @param etag the option etag for this request
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method,
RESTCallback callback, boolean isLoginRequest,
boolean shouldReplay, String etag)
{
callREST(url, data, method, callback, isLoginRequest, shouldReplay, etag, null);
}
/**
* <p>
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
* </p>
*
* <p>
* By default RESTility sets two HTTP headers: <code>Accept=application/json</code> and
* <code>Accept-Charset=UTF-8</code>. Other headers are added by the browser running this
* application.
* </p>
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
* @param isLoginRequest
* true if this is a request to login and false otherwise
* @param shouldReplay true if this request should repeat after a login request
* if this request returns a 401
* @param etag the option etag for this request
* @param headers a map containing the headers to the HTTP request. Any item
* in this map will override the default headers.
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method,
RESTCallback callback, boolean isLoginRequest,
boolean shouldReplay, String etag, Map<String, String> headers)
{
RESTOptions options = new RESTOptions();
options.setURL(url);
if (data != null && data.trim().length() > 0) {
options.setData(JSONParser.parseStrict(data));
}
options.setMethod(method);
options.setCallback(callback);
options.setIsLoginRequest(isLoginRequest);
options.setShouldReplay(shouldReplay);
options.setEtag(etag);
options.setHeaders(headers);
callREST(options);
}
/**
* <p>
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
* </p>
*
* @param options the options for the REST request
*/
public static void callREST(RESTOptions options)
{
if (hasPotentialXss(options.getDataString())) {
options.getCallback().onError(new RESTException(RESTException.XSS_ERROR,
"", STRINGS.noServerContact(),
new HashMap<String, String>(),
-1, options.getURL()));
return;
}
RESTILITY.m_restCalls.put(options.getCallback(), new RESTCallStruct(options.getURL(),
options.getDataString(), options.getMethod(),
options.shouldReplay(), options.getEtag()));
RequestBuilder builder = new RESTRequestBuilder(options.getMethod().getMethod(), options.getURL());
/*
Set our headers
*/
builder.setHeader("Accept", "application/json");
builder.setHeader("Accept-Charset", "UTF-8");
if (options.getHeaders() != null) {
for (String k : options.getHeaders().keySet()) {
builder.setHeader(k, options.getHeaders().get(k));
}
}
if (RESTILITY.m_bestLocale != null) {
/*
* The REST end points use the Accept-Language header to determine
* the locale to use for the contents of the REST request. Normally
* the browser will fill this in with the browser locale and that
* doesn't always match the preferred locale from the Identity Vault
* so we need to set this value with the correct preferred locale.
*/
builder.setHeader("Accept-Language", RESTILITY.m_bestLocale);
}
if (getUserToken() != null &&
getTokenServerUrl() != null) {
builder.setHeader("Authorization", getFullAuthToken());
builder.setHeader("TS-URL", getTokenServerUrl());
}
if (options.getEtag() != null) {
builder.setHeader("If-Match", options.getEtag());
}
if (options.getData() != null) {
/*
Set our request data
*/
builder.setRequestData(options.getDataString());
//b/c jaxb/jersey chokes when there is no data when content-type is json
builder.setHeader("Content-Type", "application/json");
}
builder.setCallback(RESTILITY.new RESTRequestCallback(options.getCallback()));
try {
/*
If we are in the process of logging in then all other
requests will just return with a 401 until the login
is finished. We want to delay those requests until
the login is complete when we will replay all of them.
*/
if (options.isLoginRequest() || !g_inLoginProcess) {
builder.send();
}
} catch (RequestException e) {
MessageUtil.showFatalError(e.getMessage());
}
}
/**
* The RESTCallBack object that implements the RequestCallback interface
*/
private class RESTRequestCallback implements RequestCallback
{
private RESTCallback m_origCallback;
public RESTRequestCallback(RESTCallback callback)
{
m_origCallback = callback;
}
/**
* Check the server response for an NCAC formatted fault and parse it into a RESTException
* if it is .
*
* @param val the JSON value returned from the server
* @param response the server response
*
* @return the RESTException if the server response contains an NCAC formatted fault
*/
private RESTException handleNcacFault(JSONValue val, Response response)
{
RESTCallStruct struct = RESTILITY.m_restCalls.get(m_origCallback);
RESTException exception = JSONUtil.getRESTException(val, response.getStatusCode(), struct.getUrl());
if (exception == null) {
return null;
} else {
if (RESTException.AUTH_SERVER_UNAVAILABLE.equals(exception.getSubcode())) {
/*
* This is a special case where the server can't connect to the
* authentication server to validate the token.
*/
MessageUtil.showFatalError(STRINGS.unabledAuthServer());
}
return exception;
}
}
/**
* Handles an unauthorized (401) response from the server
*
* @param struct the struct for this request
* @param exception the exception for this request if available
* @param response the response object
*
* @return true if this is an invalid request and false otherwise
*/
private boolean handleUnauthorized(RESTCallStruct struct, RESTException exception, Response response)
{
JSUtil.println("response.getStatusCode(): " + response.getStatusCode());
JSUtil.println("struct.getUrl(): " + struct.getUrl());
if (response.getStatusCode() == Response.SC_UNAUTHORIZED) {
if (g_inLoginProcess) {
/*
* If we're already in the process of logging in then it will complete
* and this call will be replayed and we don't want to start a second
* login process.
*/
return true;
}
g_inLoginProcess = true;
/*
* For return values of 401 we need to show the login dialog
*/
try {
for (RESTLoginCallBack listener : g_loginListeners) {
listener.loginPrompt();
}
String code = null;
if (exception != null) {
code = exception.getSubcode();
}
doLogin(m_origCallback, response, struct.getUrl(), code, exception);
} catch (RESTException e) {
RESTILITY.m_restCalls.remove(m_origCallback);
m_origCallback.onError(e);
}
return true;
} else {
return false;
}
}
@Override
public void onResponseReceived(Request request, Response response)
{
JSUtil.println("onResponseReceived.response.getStatusCode(): " + response.getStatusCode());
JSUtil.println("RESTILITY.m_restCalls.get(m_origCallback)..getUrl(): " +
RESTILITY.m_restCalls.get(m_origCallback).getUrl());
if (response.getStatusCode() == 0) {
/*
This means we couldn't contact the server. It might be that the
server is down or that we have a network timeout
*/
RESTCallStruct struct = RESTILITY.m_restCalls.remove(m_origCallback);
m_origCallback.onError(new RESTException(RESTException.NO_SERVER_RESPONSE,
"", STRINGS.noServerContact(),
new HashMap<String, String>(),
response.getStatusCode(),
struct.getUrl()));
return;
}
JSUtil.println("checkJSON(response.getText()): " + checkJSON(response.getText()));
if (!checkJSON(response.getText())) {
if (handleUnauthorized(RESTILITY.m_restCalls.get(m_origCallback), null, response)) {
return;
} else {
RESTCallStruct struct = RESTILITY.m_restCalls.remove(m_origCallback);
m_origCallback.onError(new RESTException(RESTException.UNPARSABLE_RESPONSE,
"", "", new HashMap<String, String>(),
response.getStatusCode(),
struct.getUrl()));
return;
}
}
JSONValue val = null;
RESTException exception = null;
if (response.getText() != null &&
response.getText().trim().length() > 1) {
val = null;
try {
val = JSONParser.parseStrict(response.getText());
} catch (JavaScriptException e) {
/*
This means we couldn't parse the response this is unlikely
because we have already checked it, but it is possible.
*/
RESTCallStruct struct = RESTILITY.m_restCalls.get(m_origCallback);
exception = new RESTException(RESTException.UNPARSABLE_RESPONSE,
"", response.getText(), new HashMap<String, String>(),
response.getStatusCode(),
struct.getUrl());
}
exception = handleNcacFault(val, response);
}
RESTCallStruct struct = RESTILITY.m_restCalls.get(m_origCallback);
if (handleUnauthorized(struct, exception, response)) {
/*
Then this is a 401 and the login will handle it
*/
return;
} else {
handleSuccessfulResponse(val, exception, response);
}
}
/**
* Handle successful REST responses which have parsable JSON, aren't NCAC faults,
* and don't contain login requests.
*
* @param val the JSON value returned from the server
* @param exception the exception generated by the response if available
* @param response the server response
*/
private void handleSuccessfulResponse(JSONValue val, RESTException exception, Response response)
{
RESTILITY.m_restCalls.remove(m_origCallback);
if (exception != null) {
m_origCallback.onError(exception);
} else {
RESTILITY.m_callCount++;
/*
* You have to have at least three valid REST calls before
* we show the application UI. This covers the build info
* and the successful login with and invalid token. It
* would be really nice if we didn't have to worry about
* this at this level, but then the UI will flash sometimes
* before the user has logged in. Hackito Ergo Sum.
*/
if (RESTILITY.m_callCount > 2) {
fireLoginSuccess();
}
if (response.getHeader("ETag") != null &&
m_origCallback instanceof ConcurrentRESTCallback) {
((ConcurrentRESTCallback) m_origCallback).setETag(response.getHeader("ETag"));
}
m_origCallback.onSuccess(val);
}
}
public void onError(Request request, Throwable exception)
{
MessageUtil.showFatalError(exception.getMessage());
}
}
/**
* The GWT parser calls the JavaScript eval function. This is dangerous since it
* can execute arbitrary JavaScript. This method does a simple check to make sure
* the JSON data we get back from the server is safe to parse.
*
* This parsing scheme is taken from RFC 4627 - http://www.ietf.org/rfc/rfc4627.txt
*
* @param json the JSON string to test
*
* @return true if it is safe to parse and false otherwise
*/
private static native boolean checkJSON(String json) /*-{
return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
json.replace(/"(\\.|[^"\\])*"/g, '')));
}-*/;
/**
* Add login listeners
*
* @param callback listeners to be added
*/
public static void addLoginListener(RESTLoginCallBack callback)
{
RESTility.g_loginListeners.add(callback);
}
/**
* Remove login listeners
*
* @param callback listeners to be removed
*/
public static void removeLoginListener(RESTLoginCallBack callback)
{
RESTility.g_loginListeners.remove(callback);
}
}
/**
* A struct for holding data about a REST request
*/
class RESTCallStruct
{
private String m_url;
private String m_data;
private RESTility.HTTPMethod m_method;
private boolean m_shouldReplay;
private String m_etag;
/**
* Creates a new RESTCallStruct
*
* @param url the URL for this REST call
* @param data the data for this REST call
* @param method the method for this REST call
* @param shouldReplay should this request be repeated if we get a 401
*/
protected RESTCallStruct(String url, String data, RESTility.HTTPMethod method,
boolean shouldReplay, String etag)
{
m_url = url;
m_data = data;
m_method = method;
m_shouldReplay = shouldReplay;
m_etag = etag;
}
/**
* Gets the URL
*
* @return the URL
*/
public String getUrl()
{
return m_url;
}
/**
* Gets the data
*
* @return the data
*/
public String getData()
{
return m_data;
}
/**
* Gets the HTTP method
*
* @return the method
*/
public RESTility.HTTPMethod getMethod()
{
return m_method;
}
/**
* Gets the ETag for this call
*
* @return the ETag
*/
public String getETag()
{
return m_etag;
}
/**
* Should this request repeat
*
* @return true if it should repeat, false otherwise
*/
public boolean shouldReplay()
{
return m_shouldReplay;
}
}
/**
* This class extends RequestBuilder so we can call PUT and DELETE
*/
class RESTRequestBuilder extends RequestBuilder
{
/**
* Creates a new RESTRequestBuilder
*
* @param method the HTTP method
* @param url the request URL
*/
public RESTRequestBuilder(String method, String url)
{
super(method, url);
}
}
| spiffyui/src/main/java/org/spiffyui/client/rest/RESTility.java | /*******************************************************************************
*
* Copyright 2011 Spiffy UI Team
*
* 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.spiffyui.client.rest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.spiffyui.client.JSONUtil;
import org.spiffyui.client.JSUtil;
import org.spiffyui.client.MessageUtil;
import org.spiffyui.client.i18n.SpiffyUIStrings;
import org.spiffyui.client.rest.v2.RESTOAuthProvider;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptException;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
/**
* A set of utilities for calling REST from GWT.
*/
public final class RESTility
{
private static final SpiffyUIStrings STRINGS = (SpiffyUIStrings) GWT.create(SpiffyUIStrings.class);
private static final String LOCALE_COOKIE = "Spiffy_Locale";
private static final RESTility RESTILITY = new RESTility();
/**
* This method represents an HTTP GET request
*/
public static final HTTPMethod GET = RESTILITY.new HTTPMethod("GET");
/**
* This method represents an HTTP PUT request
*/
public static final HTTPMethod PUT = RESTILITY.new HTTPMethod("PUT");
/**
* This method represents an HTTP POST request
*/
public static final HTTPMethod POST = RESTILITY.new HTTPMethod("POST");
/**
* This method represents an HTTP DELETE request
*/
public static final HTTPMethod DELETE = RESTILITY.new HTTPMethod("DELETE");
private static boolean g_inLoginProcess = false;
private static List<RESTLoginCallBack> g_loginListeners = new ArrayList<RESTLoginCallBack>();
private int m_callCount = 0;
private boolean m_hasLoggedIn = false;
private boolean m_logInListenerCalled = false;
private boolean m_secureCookies = false;
private String m_sessionCookie = "Spiffy_Session";
private static RESTAuthProvider g_authProvider;
private static RESTOAuthProvider g_oAuthProvider;
private String m_sessionCookiePath;
/**
* This is a helper type class so we can pass the HTTP method as a type safe
* object instead of a string.
*/
public final class HTTPMethod
{
private String m_method;
/**
* Create a new HTTPMethod object
*
* @param method the method
*/
private HTTPMethod(String method)
{
m_method = method;
}
/**
* Get the method string for this object
*
* @return the method string
*/
private String getMethod()
{
return m_method;
}
}
private Map<RESTCallback, RESTCallStruct> m_restCalls = new HashMap<RESTCallback, RESTCallStruct>();
private String m_userToken = null;
private String m_tokenType = null;
private String m_tokenServerUrl = null;
private String m_username = null;
private String m_tokenServerLogoutUrl = null;
private String m_bestLocale = null;
/**
* Just to make sure that nobody else can instatiate this object.
*/
private RESTility()
{
}
private static final String URI_KEY = "uri";
private static final String SIGNOFF_URI_KEY = "signoffuri";
static {
RESTAuthProvider authUtil = new AuthUtil();
RESTility.setAuthProvider(authUtil);
}
/**
* <p>
* Sets the authentication provider used for future REST requests.
* </p>
*
* <p>
* By default authentication is provided by the AuthUtil class, but this
* class may be replaced to provide support for custom authentication schemes.
* </p>
*
* @param authProvider
* the new authentication provider
*
* @see AuthUtil
*/
public static void setAuthProvider(RESTAuthProvider authProvider)
{
g_authProvider = authProvider;
}
/**
* Set the OAuth provider for this application.
*
* @param oAuthProvider
* the oAuth provider
*/
public static void setOAuthProvider(RESTOAuthProvider oAuthProvider)
{
g_oAuthProvider = oAuthProvider;
}
/**
* <p>
* Sets the name of the Spiffy UI session cookie.
* </p>
*
* <p>
* Spiffy UI uses a local cookie to save the current user token. This cookie has
* the name <code>Spiffy_Session</code> by default. This method will change the
* name of the cookie to something else.
* </p>
*
* <p>
* Calling this method will not change the name of the cookie until a REST call is made
* which causes the cookie to be reset.
* </p>
*
* @param name the name of the cookie Spiffy UI session cookie
*/
public static void setSessionCookieName(String name)
{
if (name == null) {
throw new IllegalArgumentException("The session cookie name must not be null");
}
RESTILITY.m_sessionCookie = name;
}
/**
* Gets the current name of the Spiffy UI session cookie.
*
* @return the name of the session cookie
*/
public static String getSessionCookieName()
{
return RESTILITY.m_sessionCookie;
}
/**
* <p>
* Sets if RESTility cookies should only be sent via SSL.
* </p>
*
* <p>
* RESTility stores a small amount of information locally so users can refresh the page
* without logging out or resetting their locale. This information is sometimes stored
* in cookies. These cookies are normally not sent back to the server, but can be in
* some cases.
* </p>
*
* <p>
* If your application is concerned with sercurity you might want to require all cookies
* are only sent via a secure connection (SSL). Set this method true to make all cookies
* stored be RESTility and Spiffy UI require an SSL connection before they are sent.
* </p>
*
* <p>
* The default value of this field is false.
* </p>
*
* @param secure true if cookies should require SSL and false otherwise
*/
public static void setRequireSecureCookies(boolean secure)
{
RESTILITY.m_secureCookies = secure;
}
/**
* Determines if RESTility will force all cookies to require SSL.
*
* @return true if cookies require SSL and false otherwise
*/
public static boolean requiresSecureCookies()
{
return RESTILITY.m_secureCookies;
}
/**
* Gets the current auth provider which will be used for future REST calls.
*
* @return The current auth provider
*/
public static RESTAuthProvider getAuthProvider()
{
return g_authProvider;
}
/**
* Make a login request using RESTility authentication framework.
*
* @param callback the rest callback called when the login is complete
* @param response the response from the server requiring the login
* @param url the URL of the authentication server
* @param errorCode the error code from the server returned with the 401
*
* @exception RESTException
* if there was an exception when making the login request
*/
public static void login(RESTCallback callback, Response response, String url, String errorCode)
throws RESTException
{
RESTILITY.doLogin(callback, response, url, errorCode, null);
}
/**
* Make a login request using RESTility authentication framework.
*
* @param callback the rest callback called when the login is complete
* @param response the response from the server requiring the login
* @param url the URL of the authentication server
* @param exception the RESTException which prompted this login
*
* @exception RESTException
* if there was an exception when making the login request
*/
public static void login(RESTCallback callback, Response response, String url, RESTException exception)
throws RESTException
{
RESTILITY.doLogin(callback, response, url, null, exception);
}
private static String trimQuotes(String header)
{
if (header == null) {
return header;
}
String ret = header;
if (ret.startsWith("\"")) {
ret = ret.substring(1);
}
if (ret.endsWith("\"")) {
ret = ret.substring(0, ret.length() - 1);
}
return ret;
}
private void doLogin(RESTCallback callback, Response response, String url, String errorCode, RESTException exception)
throws RESTException
{
JSUtil.println("doLogin(" + url + ", " + errorCode + ")");
g_inLoginProcess = true;
/*
When the server returns a status code 401 they are required
to send back the WWW-Authenticate header to tell us how to
authenticate.
*/
String auth = response.getHeader("WWW-Authenticate");
if (auth == null) {
throw new RESTException(RESTException.NO_AUTH_HEADER,
"", STRINGS.noAuthHeader(),
new HashMap<String, String>(),
response.getStatusCode(),
url);
}
/*
* Now we have to parse out the token server URL and other information.
*
* The String should look like this:
*
* X-OPAQUE uri=<token server URI>,signoffUri=<token server logout url>
*
* First we'll remove the token type
*/
String tokenType = auth;
String loginUri = null;
String logoutUri = null;
JSUtil.println("auth: " + auth);
if (tokenType.indexOf(' ') != -1) {
tokenType = tokenType.substring(0, tokenType.indexOf(' ')).trim();
auth = auth.substring(auth.indexOf(' ') + 1);
if (tokenType.indexOf(',') != -1) {
String props[] = auth.split(",");
JSUtil.println("props: " + props);
for (String prop : props) {
if (prop.trim().toLowerCase().startsWith(URI_KEY)) {
loginUri = prop.substring(prop.indexOf('=') + 1, prop.length()).trim();
} else if (prop.trim().toLowerCase().startsWith(SIGNOFF_URI_KEY)) {
logoutUri = prop.substring(prop.indexOf('=') + 1, prop.length()).trim();
}
}
loginUri = trimQuotes(loginUri);
logoutUri = trimQuotes(logoutUri);
if (logoutUri.trim().length() == 0) {
logoutUri = loginUri;
}
}
}
JSUtil.println("tokenType: " + tokenType);
setTokenType(tokenType);
setTokenServerURL(loginUri);
setTokenServerLogoutURL(logoutUri);
removeCookie(RESTILITY.m_sessionCookie);
removeCookie(LOCALE_COOKIE);
JSUtil.println("g_oAuthProvider: " + g_oAuthProvider);
JSUtil.println("tokenType: " + tokenType);
if (g_oAuthProvider != null && tokenType.equalsIgnoreCase("Bearer") || tokenType.equalsIgnoreCase("MAC")) {
handleOAuthRequest(callback, loginUri, response, exception);
} else if (g_authProvider instanceof org.spiffyui.client.rest.v2.RESTAuthProvider) {
((org.spiffyui.client.rest.v2.RESTAuthProvider) g_authProvider).showLogin(callback, loginUri, response, exception);
} else {
g_authProvider.showLogin(callback, loginUri, errorCode);
}
}
private void handleOAuthRequest(RESTCallback callback, String tokenServerUrl, Response response, RESTException exception)
throws RESTException
{
String authUrl = g_oAuthProvider.getAuthServerUrl(callback, tokenServerUrl, response, exception);
JSUtil.println("authUrl: " + authUrl);
handleOAuthRequestJS(this, authUrl, g_oAuthProvider.getClientId(), g_oAuthProvider.getScope());
}
private void oAuthComplete(String token, String tokenType)
{
setTokenType(tokenType);
setUserToken(token);
finishRESTCalls();
}
private native String base64Encode(String s) /*-{
return $wnd.Base64.encode(s);
}-*/;
private native void handleOAuthRequestJS(RESTility callback, String authUrl, String clientId, String scope) /*-{
$wnd.spiffyui.oAuthAuthenticate(authUrl, clientId, scope, function(token, tokenType) {
[email protected]::oAuthComplete(Ljava/lang/String;Ljava/lang/String;)(token,tokenType);
});
}-*/;
/**
* Returns HTTPMethod corresponding to method name.
* If the passed in method does not match any, GET is returned.
*
* @param method a String representation of a http method
* @return the HTTPMethod corresponding to the passed in String method representation.
*/
public static HTTPMethod parseString(String method)
{
if (POST.getMethod().equalsIgnoreCase(method)) {
return POST;
} else if (PUT.getMethod().equalsIgnoreCase(method)) {
return PUT;
} else if (DELETE.getMethod().equalsIgnoreCase(method)) {
return DELETE;
} else {
//Otherwise return GET
return GET;
}
}
/**
* Upon logout, delete cookie and clear out all member variables
*/
public static void doLocalLogout()
{
RESTILITY.m_hasLoggedIn = false;
RESTILITY.m_logInListenerCalled = false;
RESTILITY.m_callCount = 0;
RESTILITY.m_userToken = null;
RESTILITY.m_tokenType = null;
RESTILITY.m_tokenServerUrl = null;
RESTILITY.m_tokenServerLogoutUrl = null;
RESTILITY.m_username = null;
removeCookie(RESTILITY.m_sessionCookie);
removeCookie(LOCALE_COOKIE);
}
/**
* The normal GWT mechanism for removing cookies will remove a cookie at the path
* the page is on. The is a possibility that the session cookie was set on the
* server with a slightly different path. In that case we need to try to delete
* the cookie on all the paths of the current URL. This method handles that case.
*
* @param name the name of the cookie to remove
*/
private static void removeCookie(String name)
{
Cookies.removeCookie(name);
if (Cookies.getCookie(name) != null) {
/*
* This could mean that the cookie was there,
* but was on a different path than the one that
* we get by default.
*/
removeCookie(name, Window.Location.getPath());
}
}
private static void removeCookie(String name, String currentPath)
{
Cookies.removeCookie(name, currentPath);
if (Cookies.getCookie(name) != null) {
/*
* This could mean that the cookie was there,
* but was on a different path than the one that
* we were passed. In that case we'll bump up
* the path and try again.
*/
String path = currentPath;
if (path.charAt(0) != '/') {
path = "/" + path;
}
int slashloc = path.lastIndexOf('/');
if (slashloc > 1) {
path = path.substring(0, slashloc);
removeCookie(name, path);
}
}
}
/**
* In some cases, like login, the original REST call returns an error and we
* need to run it again. This call gets the same REST request information and
* tries the request again.
*/
public static void finishRESTCalls()
{
for (RESTCallback callback : RESTILITY.m_restCalls.keySet()) {
RESTCallStruct struct = RESTILITY.m_restCalls.get(callback);
if (struct != null && struct.shouldReplay()) {
callREST(struct.getUrl(), struct.getData(), struct.getMethod(), callback);
}
}
}
/**
* Make a rest call using an HTTP GET to the specified URL.
*
* @param callback the callback to invoke
* @param url the properly encoded REST url to call
*/
public static void callREST(String url, RESTCallback callback)
{
callREST(url, "", RESTility.GET, callback);
}
/**
* Make a rest call using an HTTP GET to the specified URL including
* the specified data..
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param callback the callback to invoke
*/
public static void callREST(String url, String data, RESTCallback callback)
{
callREST(url, data, RESTility.GET, callback);
}
/**
* Set the user token in JavaScript memory and and saves it in a cookie.
* @param token user token
*/
public static void setUserToken(String token)
{
g_inLoginProcess = false;
RESTILITY.m_userToken = token;
setSessionToken();
}
/**
* Set the authentication server url in JavaScript memory and and saves it in a cookie.
* @param url authentication server url
*/
public static void setTokenServerURL(String url)
{
RESTILITY.m_tokenServerUrl = url;
setSessionToken();
}
/**
* Fire the login success event to all listeners if it hasn't been fired already.
*/
public static void fireLoginSuccess()
{
RESTILITY.m_hasLoggedIn = true;
if (!RESTILITY.m_logInListenerCalled) {
for (RESTLoginCallBack listener : g_loginListeners) {
listener.onLoginSuccess();
}
RESTILITY.m_logInListenerCalled = true;
}
}
/**
* <p>
* Set the type of token RESTility will pass.
* </p>
*
* <p>
* Most of the time the token type is specified by the REST server and the
* client does not have to specify this value. This method is mostly used
* for testing.
* </p>
*
* @param type the token type
*/
public static void setTokenType(String type)
{
RESTILITY.m_tokenType = type;
setSessionToken();
}
/**
* Set the user name in JavaScript memory and and saves it in a cookie.
* @param username user name
*/
public static void setUsername(String username)
{
RESTILITY.m_username = username;
setSessionToken();
}
/**
* Set the authentication server logout url in JavaScript memory and and saves it in a cookie.
* @param url authentication server logout url
*/
public static void setTokenServerLogoutURL(String url)
{
RESTILITY.m_tokenServerLogoutUrl = url;
setSessionToken();
}
/**
* We can't know the best locale until after the user logs in because we need to consider
* their locale from the identity vault. So we get the locale as part of the identity
* information and then store this in a cookie. If the cookie doesn't match the current
* locale then we need to refresh the page so we can reload the JavaScript libraries.
*
* @param locale the locale
*/
public static void setBestLocale(String locale)
{
if (getBestLocale() != null) {
if (!getBestLocale().equals(locale)) {
/*
If the best locale from the server doesn't
match the cookie. That means we set the cookie
with the new locale and refresh the page.
*/
RESTILITY.m_bestLocale = locale;
setSessionToken();
JSUtil.reload();
} else {
/*
If the best locale from the server matches
the best locale from the cookie then we are
done.
*/
return;
}
} else {
/*
This means they didn't have a best locale from
the server stored as a cookie in the client. So
we set the locale from the server into the cookie.
*/
RESTILITY.m_bestLocale = locale;
setSessionToken();
/*
* If there are any REST requests in process when we refresh
* the page they will cause errors that show up before the
* page reloads. Hiding the page makes those errors invisible.
*/
JSUtil.hide("body", "");
JSUtil.reload();
}
}
/**
* <p>
* Set the path for the Spiffy_Session cookie.
* </p>
*
* <p>
* When Spiffy UI uses token based authentication it saves token and user information
* in a cookie named Spiffy_Session. This cookie allows the user to remain logged in
* after they refresh the page the reset JavaScript memory.
* </p>
*
* <p>
* By default that cookie uses the path of the current page. If an application uses
* multiple pages it can make sense to use a more general path for this cookie to make
* it available to other URLs in the application.
* </p>
*
* <p>
* The path must be set before the first authentication request. If it is called
* afterward the cookie path will not change.
* </p>
*
* @param newPath the new path for the cookie or null if the cookie should use the path of the current page
*/
public static void setSessionCookiePath(String newPath)
{
RESTILITY.m_sessionCookiePath = newPath;
}
/**
* Get the path of the session cookie. By default this is null indicating a path of
* the current page will be used.
*
* @return the current session cookie path.
*/
public static String getSessionCookiePath()
{
return RESTILITY.m_sessionCookiePath;
}
private static void setSessionToken()
{
if (RESTILITY.m_sessionCookiePath != null) {
Cookies.setCookie(RESTILITY.m_sessionCookie, RESTILITY.m_tokenType + "," +
RESTILITY.m_userToken + "," + RESTILITY.m_tokenServerUrl + "," +
RESTILITY.m_tokenServerLogoutUrl + "," + RESTILITY.m_username,
null, null, RESTILITY.m_sessionCookiePath, RESTILITY.m_secureCookies);
if (RESTILITY.m_bestLocale != null) {
Cookies.setCookie(LOCALE_COOKIE, RESTILITY.m_bestLocale, null, null,
RESTILITY.m_sessionCookiePath, RESTILITY.m_secureCookies);
}
} else {
Cookies.setCookie(RESTILITY.m_sessionCookie, RESTILITY.m_tokenType + "," +
RESTILITY.m_userToken + "," + RESTILITY.m_tokenServerUrl + "," +
RESTILITY.m_tokenServerLogoutUrl + "," + RESTILITY.m_username,
null, null, null, RESTILITY.m_secureCookies);
if (RESTILITY.m_bestLocale != null) {
Cookies.setCookie(LOCALE_COOKIE, RESTILITY.m_bestLocale, null, null, null, RESTILITY.m_secureCookies);
}
}
}
/**
* Returns a boolean flag indicating whether user has logged in or not
*
* @return boolean indicating whether user has logged in or not
*/
public static boolean hasUserLoggedIn()
{
return RESTILITY.m_hasLoggedIn;
}
/**
* Returns user's full authentication token, prefixed with "X-OPAQUE"
*
* @return user's full authentication token prefixed with "X-OPAQUE"
*/
public static String getFullAuthToken()
{
return getTokenType() + " " + getUserToken();
}
private static void checkSessionCookie()
{
String sessionCookie = Cookies.getCookie(RESTILITY.m_sessionCookie);
if (sessionCookie != null && sessionCookie.length() > 0) {
// If the cookie value is quoted, strip off the enclosing quotes
if (sessionCookie.length() > 2 &&
sessionCookie.charAt(0) == '"' &&
sessionCookie.charAt(sessionCookie.length() - 1) == '"') {
sessionCookie = sessionCookie.substring(1, sessionCookie.length() - 1);
}
String sessionCookiePieces [] = sessionCookie.split(",");
if (sessionCookiePieces != null) {
if (sessionCookiePieces.length >= 1) {
RESTILITY.m_tokenType = sessionCookiePieces [0];
}
if (sessionCookiePieces.length >= 2) {
RESTILITY.m_userToken = sessionCookiePieces [1];
}
if (sessionCookiePieces.length >= 3) {
RESTILITY.m_tokenServerUrl = sessionCookiePieces [2];
}
if (sessionCookiePieces.length >= 4) {
RESTILITY.m_tokenServerLogoutUrl = sessionCookiePieces [3];
}
if (sessionCookiePieces.length >= 5) {
RESTILITY.m_username = sessionCookiePieces [4];
}
}
}
}
/**
* Returns user's authentication token
*
* @return user's authentication token
*/
public static String getUserToken()
{
if (RESTILITY.m_userToken == null) {
checkSessionCookie();
}
return RESTILITY.m_userToken;
}
/**
* Returns user's authentication token type
*
* @return user's authentication token type
*/
public static String getTokenType()
{
if (RESTILITY.m_tokenType == null) {
checkSessionCookie();
}
return RESTILITY.m_tokenType;
}
/**
* Returns the authentication server url
*
* @return authentication server url
*/
public static String getTokenServerUrl()
{
if (RESTILITY.m_tokenServerUrl == null) {
checkSessionCookie();
}
return RESTILITY.m_tokenServerUrl;
}
/**
* Returns authentication server logout url
*
* @return authentication server logout url
*/
public static String getTokenServerLogoutUrl()
{
if (RESTILITY.m_tokenServerLogoutUrl == null) {
checkSessionCookie();
}
return RESTILITY.m_tokenServerLogoutUrl;
}
/**
* Returns the name of the currently logged in user or null
* if the current user is not logged in.
*
* @return user name
*/
public static String getUsername()
{
if (RESTILITY.m_username == null) {
checkSessionCookie();
}
return RESTILITY.m_username;
}
/**
* Returns best matched locale
*
* @return best matched locale
*/
public static String getBestLocale()
{
if (RESTILITY.m_bestLocale != null) {
return RESTILITY.m_bestLocale;
} else {
RESTILITY.m_bestLocale = Cookies.getCookie(LOCALE_COOKIE);
return RESTILITY.m_bestLocale;
}
}
public static List<RESTLoginCallBack> getLoginListeners()
{
return g_loginListeners;
}
/**
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method, RESTCallback callback)
{
callREST(url, data, method, callback, false, null);
}
/**
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
* @param etag the option etag for this request
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method,
RESTCallback callback, String etag)
{
callREST(url, data, method, callback, false, etag);
}
/**
* The client can't really handle the test for all XSS attacks, but we can
* do some general sanity checking.
*
* @param data the data to check
*
* @return true if the data is valid and false otherwise
*/
private static boolean hasPotentialXss(final String data)
{
if (data == null) {
return false;
}
String uppercaseData = data.toUpperCase();
if (uppercaseData.indexOf("<SCRIPT") > -1) {
return true;
}
return false;
}
/**
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
* @param isLoginRequest
* true if this is a request to login and false otherwise
* @param etag the option etag for this request
*
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method,
RESTCallback callback, boolean isLoginRequest, String etag)
{
callREST(url, data, method, callback, isLoginRequest, true, etag);
}
/**
* <p>
* Make an HTTP call and get the results as a JSON object. This method handles
* allows the caller to override any HTTP headers in the request.
* </p>
*
* <p>
* By default RESTility sets two HTTP headers: <code>Accept=application/json</code> and
* <code>Accept-Charset=UTF-8</code>. Other headers are added by the browser running this
* application.
* </p>
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
* @param etag the option etag for this request
* @param headers a map containing the headers to the HTTP request. Any item
* in this map will override the default headers.
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method,
RESTCallback callback, String etag, Map<String, String> headers)
{
callREST(url, data, method, callback, false, true, etag, headers);
}
/**
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
* @param isLoginRequest
* true if this is a request to login and false otherwise
* @param shouldReplay true if this request should repeat after a login request
* if this request returns a 401
* @param etag the option etag for this request
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method,
RESTCallback callback, boolean isLoginRequest,
boolean shouldReplay, String etag)
{
callREST(url, data, method, callback, isLoginRequest, shouldReplay, etag, null);
}
/**
* <p>
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
* </p>
*
* <p>
* By default RESTility sets two HTTP headers: <code>Accept=application/json</code> and
* <code>Accept-Charset=UTF-8</code>. Other headers are added by the browser running this
* application.
* </p>
*
* @param url the properly encoded REST url to call
* @param data the data to pass to the URL
* @param method the HTTP method, defaults to GET
* @param callback the callback object for handling the request results
* @param isLoginRequest
* true if this is a request to login and false otherwise
* @param shouldReplay true if this request should repeat after a login request
* if this request returns a 401
* @param etag the option etag for this request
* @param headers a map containing the headers to the HTTP request. Any item
* in this map will override the default headers.
*/
public static void callREST(String url, String data, RESTility.HTTPMethod method,
RESTCallback callback, boolean isLoginRequest,
boolean shouldReplay, String etag, Map<String, String> headers)
{
RESTOptions options = new RESTOptions();
options.setURL(url);
if (data != null && data.trim().length() > 0) {
options.setData(JSONParser.parseStrict(data));
}
options.setMethod(method);
options.setCallback(callback);
options.setIsLoginRequest(isLoginRequest);
options.setShouldReplay(shouldReplay);
options.setEtag(etag);
options.setHeaders(headers);
callREST(options);
}
/**
* <p>
* Make an HTTP call and get the results as a JSON object. This method handles
* cases like login, error parsing, and configuration requests.
* </p>
*
* @param options the options for the REST request
*/
public static void callREST(RESTOptions options)
{
if (hasPotentialXss(options.getDataString())) {
options.getCallback().onError(new RESTException(RESTException.XSS_ERROR,
"", STRINGS.noServerContact(),
new HashMap<String, String>(),
-1, options.getURL()));
return;
}
RESTILITY.m_restCalls.put(options.getCallback(), new RESTCallStruct(options.getURL(),
options.getDataString(), options.getMethod(),
options.shouldReplay(), options.getEtag()));
RequestBuilder builder = new RESTRequestBuilder(options.getMethod().getMethod(), options.getURL());
/*
Set our headers
*/
builder.setHeader("Accept", "application/json");
builder.setHeader("Accept-Charset", "UTF-8");
if (options.getHeaders() != null) {
for (String k : options.getHeaders().keySet()) {
builder.setHeader(k, options.getHeaders().get(k));
}
}
if (RESTILITY.m_bestLocale != null) {
/*
* The REST end points use the Accept-Language header to determine
* the locale to use for the contents of the REST request. Normally
* the browser will fill this in with the browser locale and that
* doesn't always match the preferred locale from the Identity Vault
* so we need to set this value with the correct preferred locale.
*/
builder.setHeader("Accept-Language", RESTILITY.m_bestLocale);
}
if (getUserToken() != null &&
getTokenServerUrl() != null) {
builder.setHeader("Authorization", getFullAuthToken());
builder.setHeader("TS-URL", getTokenServerUrl());
}
if (options.getEtag() != null) {
builder.setHeader("If-Match", options.getEtag());
}
if (options.getData() != null) {
/*
Set our request data
*/
builder.setRequestData(options.getDataString());
//b/c jaxb/jersey chokes when there is no data when content-type is json
builder.setHeader("Content-Type", "application/json");
}
builder.setCallback(RESTILITY.new RESTRequestCallback(options.getCallback()));
try {
/*
If we are in the process of logging in then all other
requests will just return with a 401 until the login
is finished. We want to delay those requests until
the login is complete when we will replay all of them.
*/
if (options.isLoginRequest() || !g_inLoginProcess) {
builder.send();
}
} catch (RequestException e) {
MessageUtil.showFatalError(e.getMessage());
}
}
/**
* The RESTCallBack object that implements the RequestCallback interface
*/
private class RESTRequestCallback implements RequestCallback
{
private RESTCallback m_origCallback;
public RESTRequestCallback(RESTCallback callback)
{
m_origCallback = callback;
}
/**
* Check the server response for an NCAC formatted fault and parse it into a RESTException
* if it is .
*
* @param val the JSON value returned from the server
* @param response the server response
*
* @return the RESTException if the server response contains an NCAC formatted fault
*/
private RESTException handleNcacFault(JSONValue val, Response response)
{
RESTCallStruct struct = RESTILITY.m_restCalls.get(m_origCallback);
RESTException exception = JSONUtil.getRESTException(val, response.getStatusCode(), struct.getUrl());
if (exception == null) {
return null;
} else {
if (RESTException.AUTH_SERVER_UNAVAILABLE.equals(exception.getSubcode())) {
/*
* This is a special case where the server can't connect to the
* authentication server to validate the token.
*/
MessageUtil.showFatalError(STRINGS.unabledAuthServer());
}
return exception;
}
}
/**
* Handles an unauthorized (401) response from the server
*
* @param struct the struct for this request
* @param exception the exception for this request if available
* @param response the response object
*
* @return true if this is an invalid request and false otherwise
*/
private boolean handleUnauthorized(RESTCallStruct struct, RESTException exception, Response response)
{
JSUtil.println("response.getStatusCode(): " + response.getStatusCode());
JSUtil.println("struct.getUrl(): " + struct.getUrl());
if (response.getStatusCode() == Response.SC_UNAUTHORIZED) {
/*
* For return values of 401 we need to show the login dialog
*/
try {
for (RESTLoginCallBack listener : g_loginListeners) {
listener.loginPrompt();
}
String code = null;
if (exception != null) {
code = exception.getSubcode();
}
doLogin(m_origCallback, response, struct.getUrl(), code, exception);
} catch (RESTException e) {
RESTILITY.m_restCalls.remove(m_origCallback);
m_origCallback.onError(e);
}
return true;
} else {
return false;
}
}
@Override
public void onResponseReceived(Request request, Response response)
{
JSUtil.println("onResponseReceived.response.getStatusCode(): " + response.getStatusCode());
JSUtil.println("RESTILITY.m_restCalls.get(m_origCallback)..getUrl(): " +
RESTILITY.m_restCalls.get(m_origCallback).getUrl());
if (response.getStatusCode() == 0) {
/*
This means we couldn't contact the server. It might be that the
server is down or that we have a network timeout
*/
RESTCallStruct struct = RESTILITY.m_restCalls.remove(m_origCallback);
m_origCallback.onError(new RESTException(RESTException.NO_SERVER_RESPONSE,
"", STRINGS.noServerContact(),
new HashMap<String, String>(),
response.getStatusCode(),
struct.getUrl()));
return;
}
JSUtil.println("checkJSON(response.getText()): " + checkJSON(response.getText()));
if (!checkJSON(response.getText())) {
if (handleUnauthorized(RESTILITY.m_restCalls.get(m_origCallback), null, response)) {
return;
} else {
RESTCallStruct struct = RESTILITY.m_restCalls.remove(m_origCallback);
m_origCallback.onError(new RESTException(RESTException.UNPARSABLE_RESPONSE,
"", "", new HashMap<String, String>(),
response.getStatusCode(),
struct.getUrl()));
return;
}
}
JSONValue val = null;
RESTException exception = null;
if (response.getText() != null &&
response.getText().trim().length() > 1) {
val = null;
try {
val = JSONParser.parseStrict(response.getText());
} catch (JavaScriptException e) {
/*
This means we couldn't parse the response this is unlikely
because we have already checked it, but it is possible.
*/
RESTCallStruct struct = RESTILITY.m_restCalls.get(m_origCallback);
exception = new RESTException(RESTException.UNPARSABLE_RESPONSE,
"", response.getText(), new HashMap<String, String>(),
response.getStatusCode(),
struct.getUrl());
}
exception = handleNcacFault(val, response);
}
RESTCallStruct struct = RESTILITY.m_restCalls.get(m_origCallback);
if (handleUnauthorized(struct, exception, response)) {
/*
Then this is a 401 and the login will handle it
*/
return;
} else {
handleSuccessfulResponse(val, exception, response);
}
}
/**
* Handle successful REST responses which have parsable JSON, aren't NCAC faults,
* and don't contain login requests.
*
* @param val the JSON value returned from the server
* @param exception the exception generated by the response if available
* @param response the server response
*/
private void handleSuccessfulResponse(JSONValue val, RESTException exception, Response response)
{
RESTILITY.m_restCalls.remove(m_origCallback);
if (exception != null) {
m_origCallback.onError(exception);
} else {
RESTILITY.m_callCount++;
/*
* You have to have at least three valid REST calls before
* we show the application UI. This covers the build info
* and the successful login with and invalid token. It
* would be really nice if we didn't have to worry about
* this at this level, but then the UI will flash sometimes
* before the user has logged in. Hackito Ergo Sum.
*/
if (RESTILITY.m_callCount > 2) {
fireLoginSuccess();
}
if (response.getHeader("ETag") != null &&
m_origCallback instanceof ConcurrentRESTCallback) {
((ConcurrentRESTCallback) m_origCallback).setETag(response.getHeader("ETag"));
}
m_origCallback.onSuccess(val);
}
}
public void onError(Request request, Throwable exception)
{
MessageUtil.showFatalError(exception.getMessage());
}
}
/**
* The GWT parser calls the JavaScript eval function. This is dangerous since it
* can execute arbitrary JavaScript. This method does a simple check to make sure
* the JSON data we get back from the server is safe to parse.
*
* This parsing scheme is taken from RFC 4627 - http://www.ietf.org/rfc/rfc4627.txt
*
* @param json the JSON string to test
*
* @return true if it is safe to parse and false otherwise
*/
private static native boolean checkJSON(String json) /*-{
return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
json.replace(/"(\\.|[^"\\])*"/g, '')));
}-*/;
/**
* Add login listeners
*
* @param callback listeners to be added
*/
public static void addLoginListener(RESTLoginCallBack callback)
{
RESTility.g_loginListeners.add(callback);
}
/**
* Remove login listeners
*
* @param callback listeners to be removed
*/
public static void removeLoginListener(RESTLoginCallBack callback)
{
RESTility.g_loginListeners.remove(callback);
}
}
/**
* A struct for holding data about a REST request
*/
class RESTCallStruct
{
private String m_url;
private String m_data;
private RESTility.HTTPMethod m_method;
private boolean m_shouldReplay;
private String m_etag;
/**
* Creates a new RESTCallStruct
*
* @param url the URL for this REST call
* @param data the data for this REST call
* @param method the method for this REST call
* @param shouldReplay should this request be repeated if we get a 401
*/
protected RESTCallStruct(String url, String data, RESTility.HTTPMethod method,
boolean shouldReplay, String etag)
{
m_url = url;
m_data = data;
m_method = method;
m_shouldReplay = shouldReplay;
m_etag = etag;
}
/**
* Gets the URL
*
* @return the URL
*/
public String getUrl()
{
return m_url;
}
/**
* Gets the data
*
* @return the data
*/
public String getData()
{
return m_data;
}
/**
* Gets the HTTP method
*
* @return the method
*/
public RESTility.HTTPMethod getMethod()
{
return m_method;
}
/**
* Gets the ETag for this call
*
* @return the ETag
*/
public String getETag()
{
return m_etag;
}
/**
* Should this request repeat
*
* @return true if it should repeat, false otherwise
*/
public boolean shouldReplay()
{
return m_shouldReplay;
}
}
/**
* This class extends RequestBuilder so we can call PUT and DELETE
*/
class RESTRequestBuilder extends RequestBuilder
{
/**
* Creates a new RESTRequestBuilder
*
* @param method the HTTP method
* @param url the request URL
*/
public RESTRequestBuilder(String method, String url)
{
super(method, url);
}
}
| We are now making sure to queue up REST requests while the completing OAuth logins.
| spiffyui/src/main/java/org/spiffyui/client/rest/RESTility.java | We are now making sure to queue up REST requests while the completing OAuth logins. | <ide><path>piffyui/src/main/java/org/spiffyui/client/rest/RESTility.java
<ide> throws RESTException
<ide> {
<ide> JSUtil.println("doLogin(" + url + ", " + errorCode + ")");
<del> g_inLoginProcess = true;
<ide>
<ide> /*
<ide> When the server returns a status code 401 they are required
<ide> JSUtil.println("response.getStatusCode(): " + response.getStatusCode());
<ide> JSUtil.println("struct.getUrl(): " + struct.getUrl());
<ide> if (response.getStatusCode() == Response.SC_UNAUTHORIZED) {
<add> if (g_inLoginProcess) {
<add> /*
<add> * If we're already in the process of logging in then it will complete
<add> * and this call will be replayed and we don't want to start a second
<add> * login process.
<add> */
<add> return true;
<add> }
<add>
<add> g_inLoginProcess = true;
<ide> /*
<ide> * For return values of 401 we need to show the login dialog
<ide> */ |
|
Java | apache-2.0 | 0d8bfd839ffc7a1cf27f5790447b4275a9bbe9e2 | 0 | legdba/servicebox,legdba/servicebox,legdba/servicebox,legdba/servicebox-jaxrs,legdba/servicebox,legdba/servicebox-jaxrs,legdba/servicebox,legdba/servicebox-jaxrs,legdba/servicebox-jaxrs,legdba/servicebox-jaxrs | package com.brimarx.servicebox;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.brimarx.servicebox.backend.BackendFactory;
import com.brimarx.servicebox.services.CalcService;
import com.brimarx.servicebox.services.EchoService;
import com.brimarx.servicebox.services.LeakService;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class EmbededServer
{
public static void main(String[] args)
{
EmbededServer srv = new EmbededServer();
try {
JCommander jc = new JCommander(srv, args);
if (srv.help) {
jc.usage();
System.exit(0);
}
srv.run();
} catch (ParameterException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
private static final int DEFAULT_HTTP_PORT = 8080;
private static final String DEFAULT_APP_LOG_LEVEL = "info";
private static final String DEFAULT_SRV_LOG_LEVEL = "warn";
private static final String DEFAULT_BE_OPTS_CASSANDRA = "127.0.0.1";
@Parameter(names={"-h", "--help"}, description = "display help")
private boolean help = false;
@Parameter(names={"-p", "--port"}, description = "HTTP server port number; default to " + DEFAULT_HTTP_PORT)
private int httpPort = DEFAULT_HTTP_PORT;
@Parameter(names={"-l", "--log"}, description = "http server log level: debug, info, warn or error; default to " + DEFAULT_APP_LOG_LEVEL)
private String appLogLevel = DEFAULT_APP_LOG_LEVEL;
@Parameter(names={ "--logsrv"}, description = "application log level: debug, info, warn or error; default to " + DEFAULT_SRV_LOG_LEVEL)
private String rootLogLevel = DEFAULT_SRV_LOG_LEVEL;
@Parameter(names={ "--srvloglevel"}, description = "logback config file; disables other log options; uses internal preset config and CLI options by default")
private String logbackConfig = null;
@Parameter(names={ "--be-type"}, description = "backend type; defaults to " + BackendFactory.TYPE_MEMORY + "; cassandra is supported as well and takes a node IP in the --be-endpoint param")
private String beType = BackendFactory.TYPE_MEMORY;
@Parameter(names={ "--be-opts"}, description = "backend connectivity options; this depends on the --be-type value. 'memory' backend ignores this argument. 'cassandra' backend reads the cluster IP(s) there.")
private String beEndpoint = null;
private void run()
{
try
{
// Override logback default config with set options
if (logbackConfig == null)
{
System.setProperty("LOGLEVEL_APP", appLogLevel);
System.setProperty("LOGLEVEL_SRV", rootLogLevel);
}
else
{
initLogsFrom(logbackConfig);
}
logger = LoggerFactory.getLogger(EmbededServer.class);
// We are done with init, now we can setup and start the server itself
logger.info("server starting...");
logger.info("info level enabled");
logger.debug("debug level enabled");
// Set backend connection
if (BackendFactory.TYPE_CASSANDRA.equalsIgnoreCase(beType) && beEndpoint == null) beEndpoint= DEFAULT_BE_OPTS_CASSANDRA;
CalcService.setBackend(BackendFactory.build(beType, beEndpoint));
// Expose the resources/webdav directory static content with / as a basedir
ResourceHandler rh = new ResourceHandler();
rh.setDirectoriesListed(true);rh.setWelcomeFiles(new String[]{"index.html"});
java.net.URL webappResource = EmbededServer.class.getClassLoader().getResource("webapp");
if (webappResource == null) throw new IllegalStateException("webapp resource not found");
String webDir = webappResource.toExternalForm();
rh.setResourceBase(webDir);
// Create server
final Server server = new Server(httpPort);
ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
context.addServlet(createJAXRSServletHolder(CalcService.class, 1), "/calc/*");
context.addServlet(createJAXRSServletHolder(LeakService.class, 2), "/leak/*");
context.addServlet(createJAXRSServletHolder(EchoService.class, 3), "/echo/*");
// Add both our JAX-RS service and static content to be served by the server
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { rh, context, new DefaultHandler() });
server.setHandler(handlers);
// Set graceful shutdown limited to 1sec
server.setStopAtShutdown(true);
server.setStopTimeout(1000);
// Run the server
server.start();
logger.warn("server started; serving requests on port {} ...", httpPort);
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
try
{
logger.warn("SIGTERM, stopping server");
server.stop();
}
catch (Exception e)
{
logger.error("server stop failed", e);
}
}
});
server.join();
logger.warn("server stopped");
System.exit(0);
}
catch (Exception e)
{
e.printStackTrace(System.err);
System.exit(2);
} }
private static void initLogsFrom(String file) throws JoranException
{
File fn = new File(file);
LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(fn);
}
// Create the embeded service with JAX-RS interface enabled
private static ServletHolder createJAXRSServletHolder(Class clazz, int order) {
ServletHolder sh = new ServletHolder(ServletContainer.class);
sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
sh.setInitParameter("jersey.config.server.provider.classnames", clazz.getCanonicalName());
sh.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
sh.setInitOrder(order);
return sh;
}
private static Logger logger = null; // don't init statically to avoid slf4j init to occur before command line is read an log options set
}
| src/main/java/com/brimarx/servicebox/EmbededServer.java | package com.brimarx.servicebox;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.brimarx.servicebox.backend.Backend;
import com.brimarx.servicebox.backend.BackendFactory;
import com.brimarx.servicebox.services.CalcService;
import com.brimarx.servicebox.services.EchoService;
import com.brimarx.servicebox.services.LeakService;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class EmbededServer
{
public static void main(String[] args)
{
EmbededServer srv = new EmbededServer();
try {
JCommander jc = new JCommander(srv, args);
if (srv.help) {
jc.usage();
System.exit(0);
}
srv.run();
} catch (ParameterException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
private static final int DEFAULT_HTTP_PORT = 8080;
private static final String DEFAULT_APP_LOG_LEVEL = "info";
private static final String DEFAULT_SRV_LOG_LEVEL = "warn";
private static final String DEFAULT_BE_OPTS_CASSANDRA = "127.0.0.1";
@Parameter(names={"-h", "--help"}, description = "display help")
private boolean help = false;
@Parameter(names={"-p", "--port"}, description = "HTTP server port number; default to " + DEFAULT_HTTP_PORT)
private int httpPort = DEFAULT_HTTP_PORT;
@Parameter(names={"-l", "--log"}, description = "http server log level: debug, info, warn or error; default to " + DEFAULT_APP_LOG_LEVEL)
private String appLogLevel = DEFAULT_APP_LOG_LEVEL;
@Parameter(names={ "--logsrv"}, description = "application log level: debug, info, warn or error; default to " + DEFAULT_SRV_LOG_LEVEL)
private String rootLogLevel = DEFAULT_SRV_LOG_LEVEL;
@Parameter(names={ "--srvloglevel"}, description = "logback config file; disables other log options; uses internal preset config and CLI options by default")
private String logbackConfig = null;
@Parameter(names={ "--be-type"}, description = "backend type; defaults to " + BackendFactory.TYPE_MEMORY + "; cassandra is supported as well and takes a node IP in the --be-endpoint param")
private String beType = BackendFactory.TYPE_MEMORY;
@Parameter(names={ "--be-opts"}, description = "backend connectivity options; this depends on the --be-type value. 'memory' backend ignores this argument. 'cassandra' backend reads the cluster IP(s) there.")
private String beEndpoint = null;
private void run()
{
try
{
// Override logback default config with set options
if (logbackConfig == null)
{
System.setProperty("LOGLEVEL_APP", appLogLevel);
System.setProperty("LOGLEVEL_SRV", rootLogLevel);
}
else
{
initLogsFrom(logbackConfig);
}
logger = LoggerFactory.getLogger(EmbededServer.class);
// We are done with init, now we can setup and start the server itself
logger.info("server starting...");
logger.info("info level enabled");
logger.debug("debug level enabled");
// Set backend connection
if (BackendFactory.TYPE_CASSANDRA.equalsIgnoreCase(beType) && beEndpoint == null) beEndpoint= DEFAULT_BE_OPTS_CASSANDRA;
CalcService.setBackend(BackendFactory.build(beType, beEndpoint));
// Expose the resources/webdav directory static content with / as a basedir
ResourceHandler rh = new ResourceHandler();
rh.setDirectoriesListed(true);rh.setWelcomeFiles(new String[]{"index.html"});
java.net.URL webappResource = EmbededServer.class.getClassLoader().getResource("webapp");
if (webappResource == null) throw new IllegalStateException("webapp resource not found");
String webDir = webappResource.toExternalForm();
rh.setResourceBase(webDir);
// Create server
final Server server = new Server(httpPort);
ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
context.addServlet(createJAXRSServletHolder(CalcService.class, 1), "/calc/*");
context.addServlet(createJAXRSServletHolder(LeakService.class, 2), "/leak/*");
context.addServlet(createJAXRSServletHolder(EchoService.class, 3), "/echo/*");
// Add both our JAX-RS service and static content to be served by the server
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { rh, context, new DefaultHandler() });
server.setHandler(handlers);
// Set graceful shutdown limited to 1sec
server.setStopAtShutdown(true);
server.setStopTimeout(1000);
// Run the server
server.start();
logger.warn("server started; serving requests on port {} ...", httpPort);
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
try
{
logger.warn("SIGTERM, stopping server");
server.stop();
}
catch (Exception e)
{
logger.error("server stop failed", e);
}
}
});
server.join();
logger.warn("server stopped");
System.exit(0);
}
catch (Exception e)
{
e.printStackTrace(System.err);
System.exit(2);
} }
private static void initLogsFrom(String file) throws JoranException
{
File fn = new File(file);
LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(fn);
}
// Create the embeded service with JAX-RS interface enabled
private static ServletHolder createJAXRSServletHolder(Class clazz, int order) {
ServletHolder sh = new ServletHolder(ServletContainer.class);
sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
sh.setInitParameter("jersey.config.server.provider.classnames", clazz.getCanonicalName());
sh.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
sh.setInitOrder(order);
return sh;
}
private static Logger logger = null; // don't init statically to avoid slf4j init to occur before command line is read an log options set
}
| remove warning
| src/main/java/com/brimarx/servicebox/EmbededServer.java | remove warning | <ide><path>rc/main/java/com/brimarx/servicebox/EmbededServer.java
<ide> import com.beust.jcommander.JCommander;
<ide> import com.beust.jcommander.Parameter;
<ide> import com.beust.jcommander.ParameterException;
<del>import com.brimarx.servicebox.backend.Backend;
<ide> import com.brimarx.servicebox.backend.BackendFactory;
<ide> import com.brimarx.servicebox.services.CalcService;
<ide> import com.brimarx.servicebox.services.EchoService; |
|
JavaScript | mit | 63e4f70cfef87c4ca4cb6213b743e93169d43d55 | 0 | bluesky136/backbone-login-master,bluesky136/backbone-login-master | /*
* Node Express app server with API endpoints
* --------------------------------------------
* Creates a SQLite3 schema and users table for inserting, updating, and deleting
* user records. Passwords are salted and a combined salt+hash is stored in the db.
* Also signs and unsigns cookies which it uses to persist the client's authentication.
*
*/
/*added this because the original wouldn't connect*/
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);
//
var express = require('express'),
http = require('http'),
config = require("./config"),
var bcrypt = require('bcrypt');
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash('B4c0/\/', salt, function(err, hash) {
// Store hash in your password DB.
});
});
sqlite = require("sqlite3"),
_ = require("underscore"),
app = express(),
port = process.env.PORT || config.port,
server = http.createServer(app).listen(port);
// Initialize sqlite and create our db if it doesnt exist
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(__dirname+'/db/bb-login.db');
// Create our users table if it doesn't exist
db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, username TEXT UNIQUE, password TEXT, auth_token TEXT UNIQUE)");
// Allow node to be run with proxy passing
app.enable('trust proxy');
// Logging config
app.configure('local', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Compression (gzip)
app.use( express.compress() );
app.use( express.methodOverride() );
app.use( express.urlencoded() ); // Needed to parse POST data sent as JSON payload
app.use( express.json() );
// Cookie config
app.use( express.cookieParser( config.cookieSecret ) ); // populates req.signedCookies
app.use( express.cookieSession( config.sessionSecret ) ); // populates req.session, needed for CSRF
// We need serverside view templating to initially set the CSRF token in the <head> metadata
// Otherwise, the html could just be served statically from the public directory
app.set('view engine', 'html');
app.set('views', __dirname + '/views' );
app.engine('html', require('hbs').__express);
app.use(express.static(__dirname+'/public'));
app.use(express.csrf());
app.use( app.router );
app.get("/", function(req, res){
res.render('index', { csrfToken: req.csrfToken() });
});
// GET /api/auth
// @desc: checks a user's auth status based on cookie
app.get("/api/auth", function(req, res){
db.get("SELECT * FROM users WHERE id = ? AND auth_token = ?", [ req.signedCookies.user_id, req.signedCookies.auth_token ], function(err, user){
if(user){
res.json({ user: _.omit(user, ['password', 'auth_token']) });
} else {
res.json({ error: "Client has no valid login cookies." });
}
});
});
// POST /api/auth/login
// @desc: logs in a user
app.post("/api/auth/login", function(req, res){
db.get("SELECT * FROM users WHERE username = ?", [ req.body.username ], function(err, user){
if(user){
// Compare the POSTed password with the encrypted db password
if( bcrypt.compareSync( req.body.password, user.password)){
res.cookie('user_id', user.id, { signed: true, maxAge: config.cookieMaxAge });
res.cookie('auth_token', user.auth_token, { signed: true, maxAge: config.cookieMaxAge });
// Correct credentials, return the user object
res.json({ user: _.omit(user, ['password', 'auth_token']) });
} else {
// Username did not match password given
res.json({ error: "Invalid username or password." });
}
} else {
// Could not find the username
res.json({ error: "Username does not exist." });
}
});
});
// POST /api/auth/signup
// @desc: creates a user
app.post("/api/auth/signup", function(req, res){
db.serialize(function(){
db.run("INSERT INTO users(username, name, password, auth_token) VALUES (?, ?, ?, ?)",
[ req.body.username, req.body.name, bcrypt.hashSync(req.body.password, 8), bcrypt.genSaltSync(8) ], function(err, rows){
if(err){
res.json({ error: "Username has been taken.", field: "username" });
} else {
// Retrieve the inserted user data
db.get("SELECT * FROM users WHERE username = ?", [ req.body.username ], function(err, user){
if(!user) {
console.log(err, rows);
res.json({ error: "Error while trying to register user." });
} else {
// Set the user cookies and return the cleansed user data
res.cookie('user_id', user.id, { signed: true, maxAge: config.cookieMaxAge });
res.cookie('auth_token', user.auth_token, { signed: true, maxAge: config.cookieMaxAge });
res.json({ user: _.omit(user, ['password', 'auth_token']) });
}
});
}
});
});
});
// POST /api/auth/logout
// @desc: logs out a user, clearing the signed cookies
app.post("/api/auth/logout", function(req, res){
res.clearCookie('user_id');
res.clearCookie('auth_token');
res.json({ success: "User successfully logged out." });
});
// POST /api/auth/remove_account
// @desc: deletes a user
app.post("/api/auth/remove_account", function(req, res){
db.run("DELETE FROM users WHERE id = ? AND auth_token = ?", [ req.signedCookies.user_id, req.signedCookies.auth_token ], function(err, rows){
if(err){
res.json({ error: "Error while trying to delete user." });
} else {
res.clearCookie('user_id');
res.clearCookie('auth_token');
res.json({ success: "User successfully deleted." });
}
});
});
// Close the db connection on process exit
// (should already happen, but to be safe)
process.on("exit", function(){
db.close();
});
console.log("STARTUP:: Express server listening on port::", port, ", environment:: ", app.settings.env);
| server.js | /*
* Node Express app server with API endpoints
* --------------------------------------------
* Creates a SQLite3 schema and users table for inserting, updating, and deleting
* user records. Passwords are salted and a combined salt+hash is stored in the db.
* Also signs and unsigns cookies which it uses to persist the client's authentication.
*
*/
/*added this because the original wouldn't connect*/
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);
//
var express = require('express'),
http = require('http'),
config = require("./config"),
bcrypt = require("bcrypt"),
sqlite = require("sqlite3"),
_ = require("underscore"),
app = express(),
port = process.env.PORT || config.port,
server = http.createServer(app).listen(port);
// Initialize sqlite and create our db if it doesnt exist
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(__dirname+'/db/bb-login.db');
// Create our users table if it doesn't exist
db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, username TEXT UNIQUE, password TEXT, auth_token TEXT UNIQUE)");
// Allow node to be run with proxy passing
app.enable('trust proxy');
// Logging config
app.configure('local', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Compression (gzip)
app.use( express.compress() );
app.use( express.methodOverride() );
app.use( express.urlencoded() ); // Needed to parse POST data sent as JSON payload
app.use( express.json() );
// Cookie config
app.use( express.cookieParser( config.cookieSecret ) ); // populates req.signedCookies
app.use( express.cookieSession( config.sessionSecret ) ); // populates req.session, needed for CSRF
// We need serverside view templating to initially set the CSRF token in the <head> metadata
// Otherwise, the html could just be served statically from the public directory
app.set('view engine', 'html');
app.set('views', __dirname + '/views' );
app.engine('html', require('hbs').__express);
app.use(express.static(__dirname+'/public'));
app.use(express.csrf());
app.use( app.router );
app.get("/", function(req, res){
res.render('index', { csrfToken: req.csrfToken() });
});
// GET /api/auth
// @desc: checks a user's auth status based on cookie
app.get("/api/auth", function(req, res){
db.get("SELECT * FROM users WHERE id = ? AND auth_token = ?", [ req.signedCookies.user_id, req.signedCookies.auth_token ], function(err, user){
if(user){
res.json({ user: _.omit(user, ['password', 'auth_token']) });
} else {
res.json({ error: "Client has no valid login cookies." });
}
});
});
// POST /api/auth/login
// @desc: logs in a user
app.post("/api/auth/login", function(req, res){
db.get("SELECT * FROM users WHERE username = ?", [ req.body.username ], function(err, user){
if(user){
// Compare the POSTed password with the encrypted db password
if( bcrypt.compareSync( req.body.password, user.password)){
res.cookie('user_id', user.id, { signed: true, maxAge: config.cookieMaxAge });
res.cookie('auth_token', user.auth_token, { signed: true, maxAge: config.cookieMaxAge });
// Correct credentials, return the user object
res.json({ user: _.omit(user, ['password', 'auth_token']) });
} else {
// Username did not match password given
res.json({ error: "Invalid username or password." });
}
} else {
// Could not find the username
res.json({ error: "Username does not exist." });
}
});
});
// POST /api/auth/signup
// @desc: creates a user
app.post("/api/auth/signup", function(req, res){
db.serialize(function(){
db.run("INSERT INTO users(username, name, password, auth_token) VALUES (?, ?, ?, ?)",
[ req.body.username, req.body.name, bcrypt.hashSync(req.body.password, 8), bcrypt.genSaltSync(8) ], function(err, rows){
if(err){
res.json({ error: "Username has been taken.", field: "username" });
} else {
// Retrieve the inserted user data
db.get("SELECT * FROM users WHERE username = ?", [ req.body.username ], function(err, user){
if(!user) {
console.log(err, rows);
res.json({ error: "Error while trying to register user." });
} else {
// Set the user cookies and return the cleansed user data
res.cookie('user_id', user.id, { signed: true, maxAge: config.cookieMaxAge });
res.cookie('auth_token', user.auth_token, { signed: true, maxAge: config.cookieMaxAge });
res.json({ user: _.omit(user, ['password', 'auth_token']) });
}
});
}
});
});
});
// POST /api/auth/logout
// @desc: logs out a user, clearing the signed cookies
app.post("/api/auth/logout", function(req, res){
res.clearCookie('user_id');
res.clearCookie('auth_token');
res.json({ success: "User successfully logged out." });
});
// POST /api/auth/remove_account
// @desc: deletes a user
app.post("/api/auth/remove_account", function(req, res){
db.run("DELETE FROM users WHERE id = ? AND auth_token = ?", [ req.signedCookies.user_id, req.signedCookies.auth_token ], function(err, rows){
if(err){
res.json({ error: "Error while trying to delete user." });
} else {
res.clearCookie('user_id');
res.clearCookie('auth_token');
res.json({ success: "User successfully deleted." });
}
});
});
// Close the db connection on process exit
// (should already happen, but to be safe)
process.on("exit", function(){
db.close();
});
console.log("STARTUP:: Express server listening on port::", port, ", environment:: ", app.settings.env);
| Update server.js
storing new user to database. to be updated | server.js | Update server.js | <ide><path>erver.js
<ide> http = require('http'),
<ide>
<ide> config = require("./config"),
<del> bcrypt = require("bcrypt"),
<add> var bcrypt = require('bcrypt');
<add> bcrypt.genSalt(10, function(err, salt) {
<add> bcrypt.hash('B4c0/\/', salt, function(err, hash) {
<add> // Store hash in your password DB.
<add> });
<add>});
<ide> sqlite = require("sqlite3"),
<ide> _ = require("underscore"),
<ide> |
|
Java | apache-2.0 | 3fc34a8e1c71e710392c1af626d1e88bc1044dc5 | 0 | Scrumplex/Sprummlbot,Scrumplex/Sprummlbot | package ga.codesplash.scrumplex.sprummlbot;
import com.github.theholywaffle.teamspeak3.TS3ApiAsync;
import com.github.theholywaffle.teamspeak3.TS3Query;
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Just an variable class
* Only variables are defined here
*/
public class Vars {
public static TS3Query QUERY = null;
public static TS3ApiAsync API = null;
public static int RECONNECT_TIMES = -1;
public static TS3Query.FloodRate FLOODRATE = TS3Query.FloodRate.DEFAULT;
public static final String AD_LINK = "https://github.com/Scrumplex/Sprummlbot";
public static final String VERSION = "0.3.3";
public static final int BUILD_ID = 33;
public static final String AUTHOR = "Scrumplex";
public static final List<String> NOTIFY = new ArrayList<>();
public static String SERVER = "";
public static String[] LOGIN = {"", ""};
public static int SERVER_ID = 1;
public static int QID;
public static String NICK = "Sprummlbot";
public static int PORT_SQ = 10011;
public static int WEBINTERFACE_PORT = 9911;
public static final List<String> LOGINABLE = new ArrayList<>();
public static final HashMap<String, String> AVAILABLE_LOGINS = new HashMap<>();
public static boolean AFK_ENABLED = true;
public static final List<Integer> AFKALLOWED = new ArrayList<>();
public static int AFK_CHANNEL_ID = 0;
public static int AFK_TIME = 600000;
public static final List<String> AFK_ALLOWED = new ArrayList<>();
public static final Map<String, Integer> IN_AFK = new HashMap<>();
public static boolean SUPPORT_ENABLED = true;
public static int SUPPORT_CHANNEL_ID = 0;
public static final List<String> SUPPORTERS = new ArrayList<>();
public static final List<String> IN_SUPPORT = new ArrayList<>();
public static boolean ANTIREC_ENABLED = true;
public static final List<String> ANTIREC_WHITELIST = new ArrayList<>();
public static boolean BROADCAST_ENABLED = true;
public static final List<String> BROADCASTS = new ArrayList<>();
public static final List<String> BROADCAST_IGNORE = new ArrayList<>();
public static Integer BROADCAST_INTERVAL = 300;
public static boolean VPNCHECKER_ENABLED = true;
public static int VPNCHECKER_INTERVAL = 20;
public static boolean VPNCHECKER_SAVE = true;
public static final List<String> VPNCHECKER_WL = new ArrayList<>();
public static boolean GROUPPROTECT_ENABLED = true;
public static final Map<Integer, List<String>> GROUPPROTECT_LIST = new HashMap<>();
public static File INTERACTIVEBANNER_FILE = null;
public static Color INTERACTIVEBANNER_COLOR = null;
public static int INTERACTIVEBANNER_FONT_SIZE = 15;
public static int[] INTERACTIVEBANNER_TIME_POS = {0,0};
public static int[] INTERACTIVEBANNER_DATE_POS = {0,0};
public static int[] INTERACTIVEBANNER_USERS_POS = {0,0};
public static boolean UPDATE_ENABLED = true;
public static boolean UPDATE_AVAILABLE = false;
public static int DEBUG = 0;
public static int TIMER_TICK = 4000;
}
| src/main/java/ga/codesplash/scrumplex/sprummlbot/Vars.java | package ga.codesplash.scrumplex.sprummlbot;
import com.github.theholywaffle.teamspeak3.TS3ApiAsync;
import com.github.theholywaffle.teamspeak3.TS3Query;
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Just an variable class
* Only variables are defined here
*/
public class Vars {
public static TS3Query QUERY = null;
public static TS3ApiAsync API = null;
public static int RECONNECT_TIMES = -1;
public static TS3Query.FloodRate FLOODRATE = TS3Query.FloodRate.DEFAULT;
public static final String AD_LINK = "https://github.com/Scrumplex/Sprummlbot";
public static final String VERSION = "0.3.3 Beta";
public static final int BUILD_ID = 32;
public static final String AUTHOR = "Scrumplex";
public static final List<String> NOTIFY = new ArrayList<>();
public static String SERVER = "";
public static String[] LOGIN = {"", ""};
public static int SERVER_ID = 1;
public static int QID;
public static String NICK = "Sprummlbot";
public static int PORT_SQ = 10011;
public static int WEBINTERFACE_PORT = 9911;
public static final List<String> LOGINABLE = new ArrayList<>();
public static final HashMap<String, String> AVAILABLE_LOGINS = new HashMap<>();
public static boolean AFK_ENABLED = true;
public static final List<Integer> AFKALLOWED = new ArrayList<>();
public static int AFK_CHANNEL_ID = 0;
public static int AFK_TIME = 600000;
public static final List<String> AFK_ALLOWED = new ArrayList<>();
public static final Map<String, Integer> IN_AFK = new HashMap<>();
public static boolean SUPPORT_ENABLED = true;
public static int SUPPORT_CHANNEL_ID = 0;
public static final List<String> SUPPORTERS = new ArrayList<>();
public static final List<String> IN_SUPPORT = new ArrayList<>();
public static boolean ANTIREC_ENABLED = true;
public static final List<String> ANTIREC_WHITELIST = new ArrayList<>();
public static boolean BROADCAST_ENABLED = true;
public static final List<String> BROADCASTS = new ArrayList<>();
public static final List<String> BROADCAST_IGNORE = new ArrayList<>();
public static Integer BROADCAST_INTERVAL = 300;
public static boolean VPNCHECKER_ENABLED = true;
public static int VPNCHECKER_INTERVAL = 20;
public static boolean VPNCHECKER_SAVE = true;
public static final List<String> VPNCHECKER_WL = new ArrayList<>();
public static boolean GROUPPROTECT_ENABLED = true;
public static final Map<Integer, List<String>> GROUPPROTECT_LIST = new HashMap<>();
public static File INTERACTIVEBANNER_FILE = null;
public static Color INTERACTIVEBANNER_COLOR = null;
public static int INTERACTIVEBANNER_FONT_SIZE = 15;
public static int[] INTERACTIVEBANNER_TIME_POS = {0,0};
public static int[] INTERACTIVEBANNER_DATE_POS = {0,0};
public static int[] INTERACTIVEBANNER_USERS_POS = {0,0};
public static boolean UPDATE_ENABLED = true;
public static boolean UPDATE_AVAILABLE = false;
public static int DEBUG = 0;
public static int TIMER_TICK = 4000;
}
| 0.3.3
| src/main/java/ga/codesplash/scrumplex/sprummlbot/Vars.java | 0.3.3 | <ide><path>rc/main/java/ga/codesplash/scrumplex/sprummlbot/Vars.java
<ide> public static TS3Query.FloodRate FLOODRATE = TS3Query.FloodRate.DEFAULT;
<ide>
<ide> public static final String AD_LINK = "https://github.com/Scrumplex/Sprummlbot";
<del> public static final String VERSION = "0.3.3 Beta";
<del> public static final int BUILD_ID = 32;
<add> public static final String VERSION = "0.3.3";
<add> public static final int BUILD_ID = 33;
<ide> public static final String AUTHOR = "Scrumplex";
<ide> public static final List<String> NOTIFY = new ArrayList<>();
<ide> |
|
Java | agpl-3.0 | 7b3b451236dcb22311afe376b35f6d5413dc3b5d | 0 | gotodeepak1122/enviroCar-server,enviroCar/enviroCar-server,autermann/enviroCar-server,Drifftr/enviroCar-server,Drifftr/enviroCar-server,enviroCar/enviroCar-server,autermann/enviroCar-server,gotodeepak1122/enviroCar-server,enviroCar/enviroCar-server,autermann/enviroCar-server | /*
* Copyright (C) 2013 The enviroCar project
*
* 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.envirocar.server.mongo.entity;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bson.types.ObjectId;
import org.envirocar.server.core.entities.DimensionedNumber;
import org.envirocar.server.core.entities.Fueling;
import org.envirocar.server.core.entities.Sensor;
import org.envirocar.server.core.entities.User;
import org.joda.time.DateTime;
import com.github.jmkgreen.morphia.Key;
import com.github.jmkgreen.morphia.annotations.Embedded;
import com.github.jmkgreen.morphia.annotations.Entity;
import com.github.jmkgreen.morphia.annotations.Id;
import com.github.jmkgreen.morphia.annotations.Indexed;
import com.github.jmkgreen.morphia.annotations.Property;
import com.github.jmkgreen.morphia.annotations.Transient;
import com.github.jmkgreen.morphia.utils.IndexDirection;
import com.google.common.base.Strings;
/**
* Mongo implementation of a {@link Fueling}.
*
* @author Christian Autermann
*/
@Entity("fuelings")
public class MongoFueling extends MongoEntityBase implements Fueling {
public static final String FUEL_TYPE = "fuelType";
public static final String COST = "cost";
public static final String VOLUME = "volume";
public static final String MILEAGE = "mileage";
public static final String TIME = "time";
public static final String MISSED_FUEL_STOP = "missedFuelStop";
public static final String COMMENT = "comment";
public static final String CAR = "car";
public static final String USER = "user";
@Id
private ObjectId id = new ObjectId();
@Property(FUEL_TYPE)
private String fuelType;
@Embedded(COST)
private DimensionedNumber cost;
@Embedded(VOLUME)
private DimensionedNumber volume;
@Embedded(MILEAGE)
private DimensionedNumber mileage;
@Property(COMMENT)
private String comment;
@Indexed(IndexDirection.DESC)
@Property(TIME)
private DateTime time;
@Embedded(CAR)
private MongoSensor car;
@Indexed
@Property(USER)
private Key<MongoUser> user;
@Transient
private User _user;
@Property(MISSED_FUEL_STOP)
private boolean missedFuelStop;
@Override
public String getFuelType() {
return this.fuelType;
}
@Override
public void setFuelType(@Nullable String type) {
this.fuelType = type;
}
@Override
public boolean hasFuelType() {
return this.fuelType != null;
}
@Override
public DimensionedNumber getCost() {
return this.cost;
}
@Override
public void setCost(@Nullable DimensionedNumber cost) {
this.cost = cost;
}
@Override
public boolean hasCost() {
return this.cost != null;
}
@Override
public DimensionedNumber getVolume() {
return this.volume;
}
@Override
public void setVolume(@Nullable DimensionedNumber volume) {
this.volume = volume;
}
@Override
public boolean hasVolume() {
return this.volume != null;
}
@Override
public DimensionedNumber getMileage() {
return this.mileage;
}
@Override
public void setMileage(@Nullable DimensionedNumber mileage) {
this.mileage = mileage;
}
@Override
public boolean hasMileage() {
return this.mileage != null;
}
@Override
public DateTime getTime() {
return this.time;
}
@Override
public void setTime(@Nullable DateTime time) {
this.time = time;
}
@Override
public boolean hasTime() {
return this.time != null;
}
@Override
public boolean isMissedFuelStop() {
return this.missedFuelStop;
}
@Override
public void setMissedFuelStop(boolean missedFuelStop) {
this.missedFuelStop = missedFuelStop;
}
@Override
public String getComment() {
return this.comment;
}
@Override
public void setComment(@Nullable String comment) {
this.comment = Strings.emptyToNull(comment);
}
@Override
public boolean hasComment() {
return this.comment != null;
}
@Override
public Sensor getCar() {
return this.car;
}
@Override
public void setCar(@Nullable Sensor sensor) {
this.car = (MongoSensor) sensor;
}
@Override
public boolean hasCar() {
return this.car != null;
}
@Override
public User getUser() {
if (this._user == null) {
this._user = getMongoDB().deref(MongoUser.class, this.user);
}
return this._user;
}
@Override
public void setUser(@Nullable User user) {
Key<MongoUser> nKey = getMongoDB().key((MongoUser) user);
if (nKey == null || !nKey.equals(this.user)) {
this.user = nKey;
this._user = null;
}
}
@Override
public boolean hasUser() {
return this.user != null;
}
@Override
public String getIdentifier() {
return this.id.toString();
}
@Override
public void setIdentifier(@Nonnull String identifier) {
this.id = new ObjectId(identifier);
}
@Override
public boolean hasIdentifier() {
return true;
}
/**
* Get the identifier of this {@code Fueling} as an {@code ObjectId}.
*
* @return the identifier
*/
public ObjectId getId() {
return this.id;
}
/**
* Sets the identifier of this {@code Fueling} as an {@code ObjectId}.
*
* @param id the identifier
*/
public void setId(@Nonnull ObjectId id) {
this.id = checkNotNull(id);
}
}
| mongo/src/main/java/org/envirocar/server/mongo/entity/MongoFueling.java | /*
* Copyright (C) 2013 The enviroCar project
*
* 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.envirocar.server.mongo.entity;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.bson.types.ObjectId;
import org.envirocar.server.core.entities.DimensionedNumber;
import org.envirocar.server.core.entities.Fueling;
import org.envirocar.server.core.entities.Sensor;
import org.envirocar.server.core.entities.User;
import org.joda.time.DateTime;
import com.github.jmkgreen.morphia.Key;
import com.github.jmkgreen.morphia.annotations.Embedded;
import com.github.jmkgreen.morphia.annotations.Id;
import com.github.jmkgreen.morphia.annotations.Indexed;
import com.github.jmkgreen.morphia.annotations.Property;
import com.github.jmkgreen.morphia.annotations.Transient;
import com.github.jmkgreen.morphia.utils.IndexDirection;
import com.google.common.base.Strings;
/**
* Mongo implementation of a {@link Fueling}.
*
* @author Christian Autermann
*/
public class MongoFueling extends MongoEntityBase implements Fueling {
public static final String FUEL_TYPE = "fuelType";
public static final String COST = "cost";
public static final String VOLUME = "volume";
public static final String MILEAGE = "mileage";
public static final String TIME = "time";
public static final String MISSED_FUEL_STOP = "missedFuelStop";
public static final String COMMENT = "comment";
public static final String CAR = "car";
public static final String USER = "user";
@Id
private ObjectId id = new ObjectId();
@Property(FUEL_TYPE)
private String fuelType;
@Property(COST)
private DimensionedNumber cost;
@Property(VOLUME)
private DimensionedNumber volume;
@Property(MILEAGE)
private DimensionedNumber mileage;
@Property(COMMENT)
private String comment;
@Indexed(IndexDirection.DESC)
@Property(TIME)
private DateTime time;
@Embedded(CAR)
private MongoSensor car;
@Indexed
@Property(USER)
private Key<MongoUser> user;
@Transient
private User _user;
@Property(MISSED_FUEL_STOP)
private boolean missedFuelStop;
@Override
public String getFuelType() {
return this.fuelType;
}
@Override
public void setFuelType(@Nullable String type) {
this.fuelType = type;
}
@Override
public boolean hasFuelType() {
return this.fuelType != null;
}
@Override
public DimensionedNumber getCost() {
return this.cost;
}
@Override
public void setCost(@Nullable DimensionedNumber cost) {
this.cost = cost;
}
@Override
public boolean hasCost() {
return this.cost != null;
}
@Override
public DimensionedNumber getVolume() {
return this.volume;
}
@Override
public void setVolume(@Nullable DimensionedNumber volume) {
this.volume = volume;
}
@Override
public boolean hasVolume() {
return this.volume != null;
}
@Override
public DimensionedNumber getMileage() {
return this.mileage;
}
@Override
public void setMileage(@Nullable DimensionedNumber mileage) {
this.mileage = mileage;
}
@Override
public boolean hasMileage() {
return this.mileage != null;
}
@Override
public DateTime getTime() {
return this.time;
}
@Override
public void setTime(@Nullable DateTime time) {
this.time = time;
}
@Override
public boolean hasTime() {
return this.time != null;
}
@Override
public boolean isMissedFuelStop() {
return this.missedFuelStop;
}
@Override
public void setMissedFuelStop(boolean missedFuelStop) {
this.missedFuelStop = missedFuelStop;
}
@Override
public String getComment() {
return this.comment;
}
@Override
public void setComment(@Nullable String comment) {
this.comment = Strings.emptyToNull(comment);
}
@Override
public boolean hasComment() {
return this.comment != null;
}
@Override
public Sensor getCar() {
return this.car;
}
@Override
public void setCar(@Nullable Sensor sensor) {
this.car = (MongoSensor) sensor;
}
@Override
public boolean hasCar() {
return this.car != null;
}
@Override
public User getUser() {
if (this._user == null) {
this._user = getMongoDB().deref(MongoUser.class, this.user);
}
return this._user;
}
@Override
public void setUser(@Nullable User user) {
Key<MongoUser> nKey = getMongoDB().key((MongoUser) user);
if (nKey == null || !nKey.equals(this.user)) {
this.user = nKey;
this._user = null;
}
}
@Override
public boolean hasUser() {
return this.user != null;
}
@Override
public String getIdentifier() {
return this.id.toString();
}
@Override
public void setIdentifier(@Nonnull String identifier) {
this.id = new ObjectId(identifier);
}
@Override
public boolean hasIdentifier() {
return true;
}
/**
* Get the identifier of this {@code Fueling} as an {@code ObjectId}.
*
* @return the identifier
*/
public ObjectId getId() {
return this.id;
}
/**
* Sets the identifier of this {@code Fueling} as an {@code ObjectId}.
*
* @param id the identifier
*/
public void setId(@Nonnull ObjectId id) {
this.id = checkNotNull(id);
}
}
| embedded annotation for numer/unit pairs
| mongo/src/main/java/org/envirocar/server/mongo/entity/MongoFueling.java | embedded annotation for numer/unit pairs | <ide><path>ongo/src/main/java/org/envirocar/server/mongo/entity/MongoFueling.java
<ide>
<ide> import com.github.jmkgreen.morphia.Key;
<ide> import com.github.jmkgreen.morphia.annotations.Embedded;
<add>import com.github.jmkgreen.morphia.annotations.Entity;
<ide> import com.github.jmkgreen.morphia.annotations.Id;
<ide> import com.github.jmkgreen.morphia.annotations.Indexed;
<ide> import com.github.jmkgreen.morphia.annotations.Property;
<ide> *
<ide> * @author Christian Autermann
<ide> */
<add>@Entity("fuelings")
<ide> public class MongoFueling extends MongoEntityBase implements Fueling {
<ide> public static final String FUEL_TYPE = "fuelType";
<ide> public static final String COST = "cost";
<ide> private ObjectId id = new ObjectId();
<ide> @Property(FUEL_TYPE)
<ide> private String fuelType;
<del> @Property(COST)
<add> @Embedded(COST)
<ide> private DimensionedNumber cost;
<del> @Property(VOLUME)
<add> @Embedded(VOLUME)
<ide> private DimensionedNumber volume;
<del> @Property(MILEAGE)
<add> @Embedded(MILEAGE)
<ide> private DimensionedNumber mileage;
<ide> @Property(COMMENT)
<ide> private String comment; |
|
JavaScript | bsd-3-clause | a99362e0eed71792cc2e808972523bde963cabff | 0 | westonplatter/learning_javascript | // chapter 3 tests
//
describe("Chapter 3 Specs", function(){
describe("show the 5 Javascript data types", function(){
// test by creating variable, then checking "typeof" for that variable
it("Undefined", function(){
expect(typeof(undefined)).toBe("undefined");
});
it("Boolean", function(){
var isBoolean = true;
expect(typeof(isBoolean)).toBe("boolean");
});
it("String", function(){
var name = "John Doe";
expect(typeof(name)).toBe("string");
});
it("Number", function(){
var age = 36;
expect(typeof(age)).toBe("number");
});
it("Object", function(){
var person = new Object();
expect(typeof(person)).toBe("object");
});
it("Function", function(){
function isOld(age)
{
alert("Dude you're aging!");
}
expect(typeof(isOld)).toBe("function");
});
});
describe("page 29 - apply use strict when declaring variables", function(){
xit("withOUT 'use strict'");
xit("with'use strict'");
});
describe("page 34 - Boolean data types", function(){
describe("convert Boolean to", function(){
it("Boolean results in the same value", function() {
expect(Boolean(true)).toBe(true);
});
it("String is true for non empty strings", function() {
expect(Boolean("anything")).toBe(true);
});
it("String is false for empty strings", function() {
expect(Boolean("")).toBe(false);
});
it("Number is false for zero", function() {
expect(Boolean(0)).toBe(false);
});
it("Number is true for 1", function() {
expect(Boolean(1)).toBe(true);
});
it("Number is false for NaN", function() {
expect(Boolean(NaN)).toBe(false);
});
});
});
describe("page 35 - Number data types", function(){
describe("declaring integers", function(){
it("as ints", function() {
var i = 5;
expect(i).toBe(5);
});
it("as octals (base 8) requires the first char to be 0", function() {
var octal = 070;
expect(octal).toBe(56);
});
it("as hexidecimals (base 16) requires the first 2 chars to be 0x", function() {
var hex = 0xA;
expect(hex).toBe(10);
});
});
it("as floating points requires 1 number to be after the decimal point", function(){
var fp1 = 2.1;
expect(fp1).toBe(2.1);
var fp2 = 0.1;
expect(fp2).toBe(0.1);
var regularInteger = 1.;
expect(regularInteger).toBe(1);
});
it("as NaN", function(){
var nan = NaN;
// see top of page 38
expect(nan == NaN).toBe(false);
});
});
describe("page 42 - String data types", function(){
it("can use single quotes", function(){
var one = '1';
expect(one).toBe("1");
});
it("can use double quotes", function(){
var two = "2";
expect(two).toBe('2');
});
it("get the length of a string", function(){
var string_of_3_letters = "abc";
expect(string_of_3_letters.length).toBe(3);
var empty_string = "";
expect(empty_string.length).toBe(0);
});
describe("page 43 - toString() conversions of non Strings", function(){
var number = 11;
it("toString() should return base10 string", function() {
expect(number.toString()).toBe("11");
});
it("toString() with radix 2 should return base2", function() {
expect(number.toString(2)).toBe("1011");
});
it("toString() with radix 11 should return base11", function() {
expect(number.toString(11)).toBe("10");
});
it("toString() with radix 16 should return hexidecimal", function() {
expect(number.toString(16)).toBe("b");
});
});
describe("page 44 - String() conversions", function(){
});
});
describe("Object data type", function() {
describe("page 45 - default object properities", function() {
});
describe("page 45 - default object methods", function() {
});
});
describe("Operators", function() {
describe("Unary operators", function() {
it("page 46: ++ should increment by 1", function() {
var i = 0;
i++;
expect(i).toBe(1);
});
it("page 46: -- should decrement by 1", function() {
var i = 0;
i--;
expect(i).toBe(-1);
});
xit("page 47: ++ increment before", function() {});
xit("page 47: ++ increment after", function() {});
});
describe("Bitwise operators", function() {
});
describe("Boolean operators", function() {
});
describe("Multiplicative operators", function() {
});
describe("Additive operators", function() {
});
describe("Equality operators", function() {
});
describe("Conditional or ternary operators", function() {
xit("should how it's the same as if ... else", function() {});
});
describe("If statement", function() {});
describe("Do-While statement", function() {});
describe("While statement", function() {});
describe("For statement", function() {});
describe("For-In statement", function() {});
describe("Break in loop functions", function() {});
describe("Conintue in loop functions", function() {});
describe("Breaks AND Conintues in loop functions", function() {});
describe("With statement", function() {});
describe("Switch statement", function() {});
describe("Functions", function(){
describe("argments", function() {});
describe("overloading", function() {});
});
});
})
| resources/professional_javascript-zakas/Chapter03/Chapter03Spec.js | // chapter 3 tests
//
describe("Chapter 3 Specs", function(){
describe("show the 5 Javascript data types", function(){
// test by creating variable, then checking "typeof" for that variable
it("Undefined", function(){
expect(typeof(undefined)).toBe("undefined");
});
it("Boolean", function(){
var isBoolean = true;
expect(typeof(isBoolean)).toBe("boolean");
});
it("String", function(){
var name = "John Doe";
expect(typeof(name)).toBe("string");
});
it("Number", function(){
var age = 36;
expect(typeof(age)).toBe("number");
});
it("Object", function(){
var person = new Object();
expect(typeof(person)).toBe("object");
});
it("Function", function(){
function isOld(age)
{
alert("Dude you're aging!");
}
expect(typeof(isOld)).toBe("function");
});
});
describe("page 29 - apply use strict when declaring variables", function(){
xit("withOUT 'use strict'");
xit("with'use strict'");
});
describe("page 34 - Boolean data types", function(){
describe("convert Boolean to", function(){
it("Boolean results in the same value", function() {
expect(Boolean(true)).toBe(true);
});
it("String is true for non empty strings", function() {
expect(Boolean("anything")).toBe(true);
});
it("String is false for empty strings", function() {
expect(Boolean("")).toBe(false);
});
it("Number is false for zero", function() {
expect(Boolean(0)).toBe(false);
});
it("Number is true for 1", function() {
expect(Boolean(1)).toBe(true);
});
it("Number is false for NaN", function() {
expect(Boolean(NaN)).toBe(false);
});
});
});
describe("page 35 - Number data types", function(){
describe("declaring integers", function(){
it("as ints", function() {
var i = 5;
expect(i).toBe(5);
});
it("as octals (base 8) requires the first char to be 0", function() {
var octal = 070;
expect(octal).toBe(56);
});
it("as hexidecimals (base 16) requires the first 2 chars to be 0x", function() {
var hex = 0xA;
expect(hex).toBe(10);
});
});
it("as floating points requires 1 number to be after the decimal point", function(){
var fp1 = 2.1;
expect(fp1).toBe(2.1);
var fp2 = 0.1;
expect(fp2).toBe(0.1);
var regularInteger = 1.;
expect(regularInteger).toBe(1);
});
it("as NaN", function(){
var nan = NaN;
// see top of page 38
expect(nan == NaN).toBe(false);
});
});
describe("String data types", function(){
it("page 42 - can use single quotes", function(){
var one = '1';
expect(one).toBe("1");
});
it("page 42 - can use double quotes", function(){
var two = "2";
expect(two).toBe('2');
});
it("page 43 - get the length of a string", function(){
var string_of_3_letters = "abc";
expect(string_of_3_letters.length).toBe(3);
var empty_string = "";
expect(empty_string.length).toBe(0);
});
describe("page 43 - toString() conversions of non Strings", function(){
var number = 11;
it("toString() should return base10 string", function() {
expect(number.toString()).toBe("11");
});
it("toString() with radix 2 should return base2", function() {
expect(number.toString(2)).toBe("1011");
});
it("toString() with radix 11 should return base11", function() {
expect(number.toString(11)).toBe("10");
});
it("toString() with radix 16 should return hexidecimal", function() {
expect(number.toString(16)).toBe("b");
});
});
describe("page 44 - String() conversions", function(){
});
});
describe("Object data type", function() {
describe("page 45 - default object properities", function() {
});
describe("page 45 - default object methods", function() {
});
});
describe("Operators", function() {
describe("Unary operators", function() {
it("page 46: ++ should increment by 1", function() {
var i = 0;
i++;
expect(i).toBe(1);
});
it("page 46: -- should decrement by 1", function() {
var i = 0;
i--;
expect(i).toBe(-1);
});
xit("page 47: ++ increment before", function() {});
xit("page 47: ++ increment after", function() {});
});
describe("Bitwise operators", function() {
});
describe("Boolean operators", function() {
});
describe("Multiplicative operators", function() {
});
describe("Additive operators", function() {
});
describe("Equality operators", function() {
});
describe("Conditional or ternary operators", function() {
xit("should how it's the same as if ... else", function() {});
});
describe("If statement", function() {});
describe("Do-While statement", function() {});
describe("While statement", function() {});
describe("For statement", function() {});
describe("For-In statement", function() {});
describe("Break in loop functions", function() {});
describe("Conintue in loop functions", function() {});
describe("Breaks AND Conintues in loop functions", function() {});
describe("With statement", function() {});
describe("Switch statement", function() {});
describe("Functions", function(){
describe("argments", function() {});
describe("overloading", function() {});
});
});
})
| [professional javascript] change formatting to match other formatting
| resources/professional_javascript-zakas/Chapter03/Chapter03Spec.js | [professional javascript] change formatting to match other formatting | <ide><path>esources/professional_javascript-zakas/Chapter03/Chapter03Spec.js
<ide> });
<ide> });
<ide>
<del> describe("String data types", function(){
<del> it("page 42 - can use single quotes", function(){
<add> describe("page 42 - String data types", function(){
<add> it("can use single quotes", function(){
<ide> var one = '1';
<ide> expect(one).toBe("1");
<ide> });
<del> it("page 42 - can use double quotes", function(){
<add> it("can use double quotes", function(){
<ide> var two = "2";
<ide> expect(two).toBe('2');
<ide> });
<del> it("page 43 - get the length of a string", function(){
<add> it("get the length of a string", function(){
<ide> var string_of_3_letters = "abc";
<ide> expect(string_of_3_letters.length).toBe(3);
<ide> |
|
Java | apache-2.0 | 447534577d16026a88c2da22e5e0449b2675488c | 0 | liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.editors.sql;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.*;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.*;
import org.eclipse.jface.text.rules.FastPartitioner;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.source.*;
import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;
import org.eclipse.jface.text.source.projection.ProjectionSupport;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.texteditor.*;
import org.eclipse.ui.texteditor.templates.ITemplatesPage;
import org.eclipse.ui.themes.IThemeManager;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.*;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.ui.*;
import org.jkiss.dbeaver.ui.editors.EditorUtils;
import org.jkiss.dbeaver.ui.editors.sql.internal.SQLEditorMessages;
import org.jkiss.dbeaver.ui.editors.sql.preferences.*;
import org.jkiss.dbeaver.ui.editors.sql.registry.SQLCommandsRegistry;
import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLCharacterPairMatcher;
import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLPartitionScanner;
import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLRuleManager;
import org.jkiss.dbeaver.ui.editors.sql.syntax.rules.SQLVariableRule;
import org.jkiss.dbeaver.ui.editors.sql.syntax.tokens.SQLControlToken;
import org.jkiss.dbeaver.ui.editors.sql.syntax.tokens.SQLToken;
import org.jkiss.dbeaver.ui.editors.sql.templates.SQLTemplatesPage;
import org.jkiss.dbeaver.ui.editors.sql.util.SQLSymbolInserter;
import org.jkiss.dbeaver.ui.editors.text.BaseTextEditor;
import org.jkiss.dbeaver.ui.editors.text.parser.SQLWordDetector;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import org.jkiss.utils.Pair;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
/**
* SQL Executor
*/
public abstract class SQLEditorBase extends BaseTextEditor implements DBPContextProvider, IErrorVisualizer {
static protected final Log log = Log.getLog(SQLEditorBase.class);
private static final long MAX_FILE_LENGTH_FOR_RULES = 2000000;
public static final String STATS_CATEGORY_SELECTION_STATE = "SelectionState";
protected final static char[] BRACKETS = {'{', '}', '(', ')', '[', ']', '<', '>'};
static {
// SQL editor preferences. Do this here because it initializes display
// (that's why we can't run it in prefs initializer classes which run before workbench creation)
{
IPreferenceStore editorStore = EditorsUI.getPreferenceStore();
editorStore.setDefault(SQLPreferenceConstants.MATCHING_BRACKETS, true);
//editorStore.setDefault(SQLPreferenceConstants.MATCHING_BRACKETS_COLOR, "128,128,128"); //$NON-NLS-1$
}
}
private final Object LOCK_OBJECT = new Object();
@NotNull
private final SQLSyntaxManager syntaxManager;
@NotNull
private final SQLRuleManager ruleManager;
private ProjectionSupport projectionSupport;
private ProjectionAnnotationModel annotationModel;
//private Map<Annotation, Position> curAnnotations;
//private IAnnotationAccess annotationAccess;
private boolean hasVerticalRuler = true;
private SQLTemplatesPage templatesPage;
private IPropertyChangeListener themeListener;
private SQLEditorControl editorControl;
//private ActivationListener activationListener = new ActivationListener();
private EditorSelectionChangedListener selectionChangedListener = new EditorSelectionChangedListener();
private Annotation[] occurrenceAnnotations = null;
private boolean markOccurrencesUnderCursor;
private boolean markOccurrencesForSelection;
private OccurrencesFinderJob occurrencesFinderJob;
private OccurrencesFinderJobCanceler occurrencesFinderJobCanceler;
private ICharacterPairMatcher characterPairMatcher;
public SQLEditorBase() {
super();
syntaxManager = new SQLSyntaxManager();
ruleManager = new SQLRuleManager(syntaxManager);
themeListener = new IPropertyChangeListener() {
long lastUpdateTime = 0;
@Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(IThemeManager.CHANGE_CURRENT_THEME) ||
event.getProperty().startsWith("org.jkiss.dbeaver.sql.editor")) {
if (lastUpdateTime > 0 && System.currentTimeMillis() - lastUpdateTime < 500) {
// Do not update too often (theme change may trigger this hundreds of times)
return;
}
lastUpdateTime = System.currentTimeMillis();
UIUtils.asyncExec(() -> {
ISourceViewer sourceViewer = getSourceViewer();
if (sourceViewer != null) {
reloadSyntaxRules();
// Reconfigure to let comments/strings colors to take effect
sourceViewer.configure(getSourceViewerConfiguration());
}
});
}
}
};
PlatformUI.getWorkbench().getThemeManager().addPropertyChangeListener(themeListener);
//setDocumentProvider(new SQLDocumentProvider());
setSourceViewerConfiguration(new SQLEditorSourceViewerConfiguration(this, getPreferenceStore()));
setKeyBindingScopes(getKeyBindingContexts()); //$NON-NLS-1$
}
public static boolean isBigScript(@Nullable IEditorInput editorInput) {
if (editorInput != null) {
File file = EditorUtils.getLocalFileFromInput(editorInput);
if (file != null && file.length() > MAX_FILE_LENGTH_FOR_RULES) {
return true;
}
}
return false;
}
static boolean isReadEmbeddedBinding() {
return DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.SCRIPT_BIND_EMBEDDED_READ);
}
static boolean isWriteEmbeddedBinding() {
return DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.SCRIPT_BIND_EMBEDDED_WRITE);
}
protected void handleInputChange(IEditorInput input) {
if (isBigScript(input)) {
uninstallOccurrencesFinder();
} else {
setMarkingOccurrences(
DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_UNDER_CURSOR),
DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_FOR_SELECTION));
}
}
@Override
protected void updateSelectionDependentActions() {
super.updateSelectionDependentActions();
updateStatusField(STATS_CATEGORY_SELECTION_STATE);
}
protected String[] getKeyBindingContexts() {
return new String[]{
TEXT_EDITOR_CONTEXT,
SQLEditorContributions.SQL_EDITOR_CONTEXT,
SQLEditorContributions.SQL_EDITOR_SCRIPT_CONTEXT,
SQLEditorContributions.SQL_EDITOR_CONTROL_CONTEXT};
}
@Override
protected void initializeEditor() {
super.initializeEditor();
this.markOccurrencesUnderCursor = DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_UNDER_CURSOR);
this.markOccurrencesForSelection = DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_FOR_SELECTION);
setEditorContextMenuId(SQLEditorContributions.SQL_EDITOR_CONTEXT_MENU_ID);
setRulerContextMenuId(SQLEditorContributions.SQL_RULER_CONTEXT_MENU_ID);
}
public DBPDataSource getDataSource() {
DBCExecutionContext context = getExecutionContext();
return context == null ? null : context.getDataSource();
}
public DBPPreferenceStore getActivePreferenceStore() {
if (this instanceof IDataSourceContainerProvider) {
DBPDataSourceContainer container = ((IDataSourceContainerProvider) this).getDataSourceContainer();
if (container != null) {
return container.getPreferenceStore();
}
}
DBPDataSource dataSource = getDataSource();
return dataSource == null ? DBWorkbench.getPlatform().getPreferenceStore() : dataSource.getContainer().getPreferenceStore();
}
@Override
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
String property = event.getProperty();
if (SQLPreferenceConstants.MARK_OCCURRENCES_UNDER_CURSOR.equals(property) || SQLPreferenceConstants.MARK_OCCURRENCES_FOR_SELECTION.equals(property)) {
setMarkingOccurrences(
DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_UNDER_CURSOR),
DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_FOR_SELECTION));
} else {
super.handlePreferenceStoreChanged(event);
}
}
@NotNull
public SQLDialect getSQLDialect() {
DBPDataSource dataSource = getDataSource();
// Refresh syntax
if (dataSource instanceof SQLDataSource) {
return ((SQLDataSource) dataSource).getSQLDialect();
}
return BasicSQLDialect.INSTANCE;
}
@NotNull
public SQLSyntaxManager getSyntaxManager() {
return syntaxManager;
}
@NotNull
public SQLRuleManager getRuleManager() {
return ruleManager;
}
public ProjectionAnnotationModel getAnnotationModel() {
return annotationModel;
}
public SQLEditorSourceViewerConfiguration getViewerConfiguration() {
return (SQLEditorSourceViewerConfiguration) super.getSourceViewerConfiguration();
}
@Override
public void createPartControl(Composite parent) {
setRangeIndicator(new DefaultRangeIndicator());
editorControl = new SQLEditorControl(parent, this);
super.createPartControl(editorControl);
//this.getEditorSite().getShell().addShellListener(this.activationListener);
this.selectionChangedListener = new EditorSelectionChangedListener();
this.selectionChangedListener.install(this.getSelectionProvider());
if (this.markOccurrencesUnderCursor || this.markOccurrencesForSelection) {
this.installOccurrencesFinder();
}
ProjectionViewer viewer = (ProjectionViewer) getSourceViewer();
projectionSupport = new ProjectionSupport(
viewer,
getAnnotationAccess(),
getSharedColors());
projectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
projectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
projectionSupport.install();
viewer.doOperation(ProjectionViewer.TOGGLE);
annotationModel = viewer.getProjectionAnnotationModel();
// Symbol inserter
{
SQLSymbolInserter symbolInserter = new SQLSymbolInserter(this);
DBPPreferenceStore preferenceStore = getActivePreferenceStore();
boolean closeSingleQuotes = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_SINGLE_QUOTES);
boolean closeDoubleQuotes = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_DOUBLE_QUOTES);
boolean closeBrackets = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_BRACKETS);
symbolInserter.setCloseSingleQuotesEnabled(closeSingleQuotes);
symbolInserter.setCloseDoubleQuotesEnabled(closeDoubleQuotes);
symbolInserter.setCloseBracketsEnabled(closeBrackets);
ISourceViewer sourceViewer = getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension) {
((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(symbolInserter);
}
}
{
// Context listener
EditorUtils.trackControlContext(getSite(), getViewer().getTextWidget(), SQLEditorContributions.SQL_EDITOR_CONTROL_CONTEXT);
}
}
public SQLEditorControl getEditorControlWrapper() {
return editorControl;
}
@Override
public void updatePartControl(IEditorInput input) {
super.updatePartControl(input);
}
protected IOverviewRuler createOverviewRuler(ISharedTextColors sharedColors) {
if (isOverviewRulerVisible()) {
return super.createOverviewRuler(sharedColors);
} else {
return new OverviewRuler(getAnnotationAccess(), 0, sharedColors);
}
}
@Override
protected boolean isOverviewRulerVisible() {
return false;
}
// Most left ruler
@Override
protected IVerticalRulerColumn createAnnotationRulerColumn(CompositeRuler ruler) {
if (isAnnotationRulerVisible()) {
return super.createAnnotationRulerColumn(ruler);
} else {
return new AnnotationRulerColumn(0, getAnnotationAccess());
}
}
protected boolean isAnnotationRulerVisible() {
return false;
}
@Override
protected IVerticalRuler createVerticalRuler() {
return hasVerticalRuler ? super.createVerticalRuler() : new VerticalRuler(0);
}
public void setHasVerticalRuler(boolean hasVerticalRuler) {
this.hasVerticalRuler = hasVerticalRuler;
}
protected ISharedTextColors getSharedColors() {
return UIUtils.getSharedTextColors();
}
@Override
protected void doSetInput(IEditorInput input) throws CoreException {
handleInputChange(input);
super.doSetInput(input);
}
@Override
public void doSave(IProgressMonitor progressMonitor) {
super.doSave(progressMonitor);
handleInputChange(getEditorInput());
}
@Override
protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
fAnnotationAccess = getAnnotationAccess();
fOverviewRuler = createOverviewRuler(getSharedColors());
SQLEditorSourceViewer sourceViewer = createSourceViewer(parent, ruler, styles, fOverviewRuler);
getSourceViewerDecorationSupport(sourceViewer);
return sourceViewer;
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
char[] matchChars = BRACKETS; //which brackets to match
try {
characterPairMatcher = new SQLCharacterPairMatcher(this, matchChars,
SQLPartitionScanner.SQL_PARTITIONING,
true);
} catch (Throwable e) {
// If we below Eclipse 4.2.1
characterPairMatcher = new SQLCharacterPairMatcher(this, matchChars, SQLPartitionScanner.SQL_PARTITIONING);
}
support.setCharacterPairMatcher(characterPairMatcher);
support.setMatchingCharacterPainterPreferenceKeys(SQLPreferenceConstants.MATCHING_BRACKETS, SQLPreferenceConstants.MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
@NotNull
protected SQLEditorSourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles, IOverviewRuler overviewRuler) {
return new SQLEditorSourceViewer(
parent,
ruler,
overviewRuler,
true,
styles);
}
@Override
protected IAnnotationAccess createAnnotationAccess() {
return new SQLMarkerAnnotationAccess();
}
/*
protected void adjustHighlightRange(int offset, int length)
{
ISourceViewer viewer = getSourceViewer();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
extension.exposeModelRange(new Region(offset, length));
}
}
*/
@SuppressWarnings("unchecked")
@Override
public <T> T getAdapter(Class<T> required) {
if (projectionSupport != null) {
Object adapter = projectionSupport.getAdapter(
getSourceViewer(), required);
if (adapter != null)
return (T) adapter;
}
if (ITemplatesPage.class.equals(required)) {
return (T) getTemplatesPage();
}
return super.getAdapter(required);
}
public SQLTemplatesPage getTemplatesPage() {
if (templatesPage == null)
templatesPage = new SQLTemplatesPage(this);
return templatesPage;
}
@Override
public void dispose() {
if (this.selectionChangedListener != null) {
this.selectionChangedListener.uninstall(this.getSelectionProvider());
this.selectionChangedListener = null;
}
/*
if (this.activationListener != null) {
Shell shell = this.getEditorSite().getShell();
if (shell != null && !shell.isDisposed()) {
shell.removeShellListener(this.activationListener);
}
this.activationListener = null;
}
*/
if (themeListener != null) {
PlatformUI.getWorkbench().getThemeManager().removePropertyChangeListener(themeListener);
themeListener = null;
}
super.dispose();
}
@Override
protected void createActions() {
super.createActions();
ResourceBundle bundle = ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME);
IAction a = new TextOperationAction(
bundle,
SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL),
this,
ISourceViewer.CONTENTASSIST_PROPOSALS);
a.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL, a);
a = new TextOperationAction(
bundle,
SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP),
this,
ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION);
a.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP, a);
a = new TextOperationAction(
bundle,
SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION),
this,
ISourceViewer.INFORMATION);
a.setActionDefinitionId(ITextEditorActionDefinitionIds.SHOW_INFORMATION);
setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION, a);
a = new TextOperationAction(
bundle,
SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL),
this,
ISourceViewer.FORMAT);
a.setActionDefinitionId(SQLEditorCommands.CMD_CONTENT_FORMAT);
setAction(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL, a);
setAction(ITextEditorActionConstants.CONTEXT_PREFERENCES, new Action(SQLEditorMessages.editor_sql_preference) { //$NON-NLS-1$
public void run() {
Shell shell = getSourceViewer().getTextWidget().getShell();
String[] preferencePages = collectContextMenuPreferencePages();
if (preferencePages.length > 0 && (shell == null || !shell.isDisposed()))
PreferencesUtil.createPreferenceDialogOn(shell, preferencePages[0], preferencePages, getEditorInput()).open();
}
});
/*
// Add the task action to the Edit pulldown menu (bookmark action is 'free')
ResourceAction ra = new AddTaskAction(bundle, "AddTask.", this);
ra.setHelpContextId(ITextEditorHelpContextIds.ADD_TASK_ACTION);
ra.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(IDEActionFactory.ADD_TASK.getId(), ra);
*/
}
// Exclude input additions. Get rid of tons of crap from debug/team extensions
@Override
protected boolean isEditorInputIncludedInContextMenu() {
return false;
}
@Override
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
//menu.add(new Separator("content"));//$NON-NLS-1$
addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL);
addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP);
addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION);
menu.insertBefore(IWorkbenchActionConstants.MB_ADDITIONS, ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.navigate.object"));
{
MenuManager formatMenu = new MenuManager(SQLEditorMessages.sql_editor_menu_format, "format");
IAction formatAction = getAction(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL);
if (formatAction != null) {
formatMenu.add(formatAction);
}
formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.morph.delimited.list"));
formatMenu.add(getAction(ITextEditorActionConstants.UPPER_CASE));
formatMenu.add(getAction(ITextEditorActionConstants.LOWER_CASE));
formatMenu.add(new Separator());
formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.word.wrap"));
formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.comment.single"));
formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.comment.multi"));
menu.insertAfter(GROUP_SQL_ADDITIONS, formatMenu);
}
//menu.remove(IWorkbenchActionConstants.MB_ADDITIONS);
}
public void reloadSyntaxRules() {
// Refresh syntax
SQLDialect dialect = getSQLDialect();
syntaxManager.init(dialect, getActivePreferenceStore());
ruleManager.refreshRules(getDataSource(), getEditorInput());
Document document = getDocument();
if (document != null) {
IDocumentPartitioner partitioner = new FastPartitioner(
new SQLPartitionScanner(dialect),
SQLPartitionScanner.SQL_CONTENT_TYPES);
partitioner.connect(document);
try {
document.setDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING, partitioner);
} catch (Throwable e) {
log.warn("Error setting SQL partitioner", e); //$NON-NLS-1$
}
ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
if (projectionViewer != null && projectionViewer.getAnnotationModel() != null && document.getLength() > 0) {
// Refresh viewer
//projectionViewer.getTextWidget().redraw();
try {
projectionViewer.reinitializeProjection();
} catch (Throwable ex) {
// We can catch OutOfMemory here for too big/complex documents
log.warn("Can't initialize SQL syntax projection", ex); //$NON-NLS-1$
}
}
}
/*
Color fgColor = ruleManager.getColor(SQLConstants.CONFIG_COLOR_TEXT);
Color bgColor = ruleManager.getColor(getDataSource() == null ?
SQLConstants.CONFIG_COLOR_DISABLED :
SQLConstants.CONFIG_COLOR_BACKGROUND);
final StyledText textWidget = getTextViewer().getTextWidget();
if (fgColor != null) {
textWidget.setForeground(fgColor);
}
textWidget.setBackground(bgColor);
*/
// Update configuration
if (getSourceViewerConfiguration() instanceof SQLEditorSourceViewerConfiguration) {
((SQLEditorSourceViewerConfiguration) getSourceViewerConfiguration()).onDataSourceChange();
}
final IVerticalRuler verticalRuler = getVerticalRuler();
if (verticalRuler != null) {
verticalRuler.update();
}
}
public boolean hasActiveQuery() {
Document document = getDocument();
if (document == null) {
return false;
}
ISelectionProvider selectionProvider = getSelectionProvider();
if (selectionProvider == null) {
return false;
}
ITextSelection selection = (ITextSelection) selectionProvider.getSelection();
String selText = selection.getText();
if (CommonUtils.isEmpty(selText) && selection.getOffset() >= 0 && selection.getOffset() < document.getLength()) {
try {
IRegion lineRegion = document.getLineInformationOfOffset(selection.getOffset());
selText = document.get(lineRegion.getOffset(), lineRegion.getLength());
} catch (BadLocationException e) {
log.warn(e);
return false;
}
}
return !CommonUtils.isEmptyTrimmed(selText);
}
@Nullable
public SQLScriptElement extractActiveQuery() {
SQLScriptElement element;
ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
String selText = selection.getText();
if (getActivePreferenceStore().getBoolean(ModelPreferences.QUERY_REMOVE_TRAILING_DELIMITER)) {
selText = SQLUtils.trimQueryStatement(getSyntaxManager(), selText, !syntaxManager.getDialect().isDelimiterAfterQuery());
}
if (!CommonUtils.isEmpty(selText)) {
SQLScriptElement parsedElement = parseQuery(getDocument(), selection.getOffset(), selection.getOffset() + selection.getLength(), selection.getOffset(), false, false);
if (parsedElement instanceof SQLControlCommand) {
// This is a command
element = parsedElement;
} else {
// Use selected query as is
selText = SQLUtils.fixLineFeeds(selText);
element = new SQLQuery(getDataSource(), selText, selection.getOffset(), selection.getLength());
}
} else if (selection.getOffset() >= 0) {
element = extractQueryAtPos(selection.getOffset());
} else {
element = null;
}
// Check query do not ends with delimiter
// (this may occur if user selected statement including delimiter)
if (element == null || CommonUtils.isEmpty(element.getText())) {
return null;
}
if (element instanceof SQLQuery && getActivePreferenceStore().getBoolean(ModelPreferences.SQL_PARAMETERS_ENABLED)) {
((SQLQuery) element).setParameters(parseParameters(getDocument(), (SQLQuery) element));
}
return element;
}
public SQLScriptElement extractQueryAtPos(int currentPos) {
Document document = getDocument();
if (document == null || document.getLength() == 0) {
return null;
}
final int docLength = document.getLength();
IDocumentPartitioner partitioner = document.getDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING);
if (partitioner != null) {
// Move to default partition. We don't want to be in the middle of multi-line comment or string
while (currentPos < docLength && isMultiCommentPartition(partitioner, currentPos)) {
currentPos++;
}
}
// Extract part of document between empty lines
int startPos = 0;
boolean useBlankLines = syntaxManager.isBlankLineDelimiter();
final String[] statementDelimiters = syntaxManager.getStatementDelimiters();
int lastPos = currentPos >= docLength ? docLength - 1 : currentPos;
try {
int currentLine = document.getLineOfOffset(currentPos);
if (useBlankLines) {
if (TextUtils.isEmptyLine(document, currentLine)) {
if (currentLine == 0) {
return null;
}
currentLine--;
if (TextUtils.isEmptyLine(document, currentLine)) {
// Prev line empty too. No chance.
return null;
}
}
}
int lineOffset = document.getLineOffset(currentLine);
int firstLine = currentLine;
while (firstLine > 0) {
if (useBlankLines) {
if (TextUtils.isEmptyLine(document, firstLine) &&
isDefaultPartition(partitioner, document.getLineOffset(firstLine))) {
break;
}
}
if (currentLine == firstLine) {
for (String delim : statementDelimiters) {
final int offset = TextUtils.getOffsetOf(document, firstLine, delim);
if (offset >= 0 ) {
int delimOffset = document.getLineOffset(firstLine) + offset + delim.length();
if (isDefaultPartition(partitioner, delimOffset)) {
if (currentPos > startPos) {
if (docLength > delimOffset) {
boolean hasValuableChars = false;
for (int i = delimOffset; i <= lastPos; i++) {
if (!Character.isWhitespace(document.getChar(i))) {
hasValuableChars = true;
break;
}
}
if (hasValuableChars) {
startPos = delimOffset;
break;
}
}
}
}
}
}
}
firstLine--;
}
if (startPos == 0) {
startPos = document.getLineOffset(firstLine);
}
// Move currentPos at line begin
currentPos = lineOffset;
} catch (BadLocationException e) {
log.warn(e);
}
return parseQuery(document, startPos, document.getLength(), currentPos, false, false);
}
public SQLScriptElement extractNextQuery(boolean next) {
ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
int offset = selection.getOffset();
SQLScriptElement curElement = extractQueryAtPos(offset);
if (curElement == null) {
return null;
}
Document document = getDocument();
if (document == null) {
return null;
}
try {
int docLength = document.getLength();
int curPos;
if (next) {
final String[] statementDelimiters = syntaxManager.getStatementDelimiters();
curPos = curElement.getOffset() + curElement.getLength();
while (curPos < docLength) {
char c = document.getChar(curPos);
if (!Character.isWhitespace(c)) {
boolean isDelimiter = false;
for (String delim : statementDelimiters) {
if (delim.indexOf(c) != -1) {
isDelimiter = true;
}
}
if (!isDelimiter) {
break;
}
}
curPos++;
}
} else {
curPos = curElement.getOffset() - 1;
while (curPos >= 0) {
char c = document.getChar(curPos);
if (!Character.isWhitespace(c)) {
break;
}
curPos--;
}
}
if (curPos <= 0 || curPos >= docLength) {
return null;
}
return extractQueryAtPos(curPos);
} catch (BadLocationException e) {
log.warn(e);
return null;
}
}
private static boolean isDefaultPartition(IDocumentPartitioner partitioner, int currentPos) {
return partitioner == null || IDocument.DEFAULT_CONTENT_TYPE.equals(partitioner.getContentType(currentPos));
}
private static boolean isMultiCommentPartition(IDocumentPartitioner partitioner, int currentPos) {
return partitioner != null && SQLPartitionScanner.CONTENT_TYPE_SQL_MULTILINE_COMMENT.equals(partitioner.getContentType(currentPos));
}
private void startScriptEvaluation() {
ruleManager.startEval();
}
private void endScriptEvaluation() {
ruleManager.endEval();
}
public List<SQLScriptElement> extractScriptQueries(int startOffset, int length, boolean scriptMode, boolean keepDelimiters, boolean parseParameters) {
List<SQLScriptElement> queryList = new ArrayList<>();
IDocument document = getDocument();
if (document == null) {
return queryList;
}
this.startScriptEvaluation();
try {
for (int queryOffset = startOffset; ; ) {
SQLScriptElement query = parseQuery(document, queryOffset, startOffset + length, queryOffset, scriptMode, keepDelimiters);
if (query == null) {
break;
}
queryList.add(query);
queryOffset = query.getOffset() + query.getLength();
}
} finally {
this.endScriptEvaluation();
}
if (parseParameters && getActivePreferenceStore().getBoolean(ModelPreferences.SQL_PARAMETERS_ENABLED)) {
// Parse parameters
for (SQLScriptElement query : queryList) {
if (query instanceof SQLQuery) {
((SQLQuery) query).setParameters(parseParameters(getDocument(), (SQLQuery) query));
}
}
}
return queryList;
}
protected SQLScriptElement parseQuery(final IDocument document, final int startPos, final int endPos, final int currentPos, final boolean scriptMode, final boolean keepDelimiters) {
if (endPos - startPos <= 0) {
return null;
}
SQLDialect dialect = getSQLDialect();
// Parse range
boolean useBlankLines = !scriptMode && syntaxManager.isBlankLineDelimiter();
ruleManager.setRange(document, startPos, endPos - startPos);
int statementStart = startPos;
int bracketDepth = 0;
boolean hasBlocks = false;
boolean hasValuableTokens = false;
boolean hasBlockHeader = false;
String blockTogglePattern = null;
int lastTokenLineFeeds = 0;
int prevNotEmptyTokenType = SQLToken.T_UNKNOWN;
String firstKeyword = null;
for (; ; ) {
IToken token = ruleManager.nextToken();
int tokenOffset = ruleManager.getTokenOffset();
int tokenLength = ruleManager.getTokenLength();
int tokenType = token instanceof SQLToken ? ((SQLToken) token).getType() : SQLToken.T_UNKNOWN;
if (tokenOffset < startPos) {
// This may happen with EOF tokens (bug in jface?)
return null;
}
boolean isDelimiter = tokenType == SQLToken.T_DELIMITER;
boolean isControl = false;
String delimiterText = null;
try {
if (isDelimiter) {
// Save delimiter text
try {
delimiterText = document.get(tokenOffset, tokenLength);
} catch (BadLocationException e) {
log.debug(e);
}
} else if (useBlankLines && token.isWhitespace() && tokenLength >= 1) {
// Check for blank line delimiter
if (lastTokenLineFeeds + countLineFeeds(document, tokenOffset, tokenLength) >= 2) {
isDelimiter = true;
}
}
lastTokenLineFeeds = 0;
if (tokenLength == 1) {
// Check for bracket block begin/end
try {
char aChar = document.getChar(tokenOffset);
if (aChar == '(' || aChar == '{' || aChar == '[') {
bracketDepth++;
} else if (aChar == ')' || aChar == '}' || aChar == ']') {
bracketDepth--;
}
} catch (BadLocationException e) {
log.warn(e);
}
}
if (tokenType == SQLToken.T_BLOCK_BEGIN && prevNotEmptyTokenType == SQLToken.T_BLOCK_END) {
// This is a tricky thing.
// In some dialects block end looks like END CASE, END LOOP. It is parsed as
// Block end followed by block begin (as CASE and LOOP are block begin tokens)
// So let's ignore block begin if previos token was block end and there were no delimtiers.
tokenType = SQLToken.T_UNKNOWN;
}
if (tokenType == SQLToken.T_BLOCK_HEADER) {
bracketDepth++;
hasBlocks = true;
hasBlockHeader = true;
} else if (tokenType == SQLToken.T_BLOCK_TOGGLE) {
String togglePattern;
try {
togglePattern = document.get(tokenOffset, tokenLength);
} catch (BadLocationException e) {
log.warn(e);
togglePattern = "";
}
// Second toggle pattern must be the same as first one.
// Toggles can be nested (PostgreSQL) and we need to count only outer
if (bracketDepth == 1 && togglePattern.equals(blockTogglePattern)) {
bracketDepth--;
blockTogglePattern = null;
} else if (bracketDepth == 0 && blockTogglePattern == null) {
bracketDepth++;
blockTogglePattern = togglePattern;
} else {
log.debug("Block toggle token inside another block. Can't process it");
}
hasBlocks = true;
} else if (tokenType == SQLToken.T_BLOCK_BEGIN) {
if (!hasBlockHeader) {
bracketDepth++;
}
hasBlocks = true;
hasBlockHeader = false;
} else if (bracketDepth > 0 && tokenType == SQLToken.T_BLOCK_END) {
// Sometimes query contains END clause without BEGIN. E.g. CASE, IF, etc.
// This END doesn't mean block
if (hasBlocks) {
bracketDepth--;
}
hasBlockHeader = false;
} else if (isDelimiter && bracketDepth > 0) {
// Delimiter in some brackets - ignore it
continue;
} else if (tokenType == SQLToken.T_SET_DELIMITER || tokenType == SQLToken.T_CONTROL) {
isDelimiter = true;
isControl = true;
} else if (tokenType == SQLToken.T_COMMENT) {
lastTokenLineFeeds = tokenLength < 2 ? 0 : countLineFeeds(document, tokenOffset + tokenLength - 2, 2);
}
if (firstKeyword == null && tokenLength > 0 && !token.isWhitespace()) {
switch (tokenType) {
case SQLToken.T_BLOCK_BEGIN:
case SQLToken.T_BLOCK_END:
case SQLToken.T_BLOCK_TOGGLE:
case SQLToken.T_BLOCK_HEADER:
case SQLToken.T_UNKNOWN:
try {
firstKeyword = document.get(tokenOffset, tokenLength);
} catch (BadLocationException e) {
log.error("Error getting first keyword", e);
}
break;
}
}
boolean cursorInsideToken = currentPos >= tokenOffset && currentPos < tokenOffset + tokenLength;
if (isControl && (scriptMode || cursorInsideToken) && !hasValuableTokens) {
// Control query
try {
String controlText = document.get(tokenOffset, tokenLength);
String commandId = null;
if (token instanceof SQLControlToken) {
commandId = ((SQLControlToken) token).getCommandId();
}
SQLControlCommand command = new SQLControlCommand(
getDataSource(),
syntaxManager,
controlText.trim(),
commandId,
tokenOffset,
tokenLength,
tokenType == SQLToken.T_SET_DELIMITER);
if (command.isEmptyCommand() ||
(command.getCommandId() != null &&
SQLCommandsRegistry.getInstance().getCommandHandler(command.getCommandId()) != null)) {
return command;
}
// This is not a valid command
isControl = false;
} catch (BadLocationException e) {
log.warn("Can't extract control statement", e); //$NON-NLS-1$
return null;
}
}
if (hasValuableTokens && (token.isEOF() || (isDelimiter && tokenOffset >= currentPos) || tokenOffset > endPos)) {
if (tokenOffset > endPos) {
tokenOffset = endPos;
}
if (tokenOffset >= document.getLength()) {
// Sometimes (e.g. when comment finishing script text)
// last token offset is beyond document range
tokenOffset = document.getLength();
}
assert (tokenOffset >= currentPos);
try {
// remove leading spaces
while (statementStart < tokenOffset && Character.isWhitespace(document.getChar(statementStart))) {
statementStart++;
}
// remove trailing spaces
/*
while (statementStart < tokenOffset && Character.isWhitespace(document.getChar(tokenOffset - 1))) {
tokenOffset--;
tokenLength++;
}
*/
if (tokenOffset == statementStart) {
// Empty statement
if (token.isEOF()) {
return null;
}
statementStart = tokenOffset + tokenLength;
continue;
}
String queryText = document.get(statementStart, tokenOffset - statementStart);
queryText = SQLUtils.fixLineFeeds(queryText);
if (isDelimiter && (keepDelimiters || (hasBlocks ?
dialect.isDelimiterAfterBlock() && firstKeyword != null &&
(SQLUtils.isBlockStartKeyword(dialect, firstKeyword) ||
ArrayUtils.containsIgnoreCase(dialect.getDDLKeywords(), firstKeyword) ||
ArrayUtils.containsIgnoreCase(dialect.getBlockHeaderStrings(), firstKeyword)) :
dialect.isDelimiterAfterQuery()))) {
if (delimiterText != null && delimiterText.equals(SQLConstants.DEFAULT_STATEMENT_DELIMITER)) {
// Add delimiter in the end of query. Do this only for semicolon delimiters.
// For SQL server add it in the end of query. For Oracle only after END clause
// Quite dirty workaround needed for Oracle and SQL Server.
// TODO: move this transformation into SQLDialect
queryText += delimiterText;
}
}
int queryEndPos = tokenOffset;
if (tokenType == SQLToken.T_DELIMITER) {
queryEndPos += tokenLength;
}
// make script line
return new SQLQuery(
getDataSource(),
queryText,
statementStart,
queryEndPos - statementStart);
} catch (BadLocationException ex) {
log.warn("Can't extract query", ex); //$NON-NLS-1$
return null;
}
}
if (isDelimiter) {
statementStart = tokenOffset + tokenLength;
}
if (token.isEOF()) {
return null;
}
if (!hasValuableTokens && !token.isWhitespace() && !isControl) {
if (tokenType == SQLToken.T_COMMENT) {
hasValuableTokens = dialect.supportsCommentQuery();
} else {
hasValuableTokens = true;
}
}
} finally {
if (!token.isWhitespace() && !token.isEOF()) {
prevNotEmptyTokenType = tokenType;
}
}
}
}
private static int countLineFeeds(final IDocument document, final int offset, final int length) {
int lfCount = 0;
try {
for (int i = offset; i < offset + length; i++) {
if (document.getChar(i) == '\n') {
lfCount++;
}
}
} catch (BadLocationException e) {
log.error(e);
}
return lfCount;
}
protected List<SQLQueryParameter> parseParameters(IDocument document, int queryOffset, int queryLength) {
final SQLDialect sqlDialect = getSQLDialect();
boolean supportParamsInDDL = getActivePreferenceStore().getBoolean(ModelPreferences.SQL_PARAMETERS_IN_DDL_ENABLED);
boolean execQuery = false;
List<SQLQueryParameter> parameters = null;
ruleManager.setRange(document, queryOffset, queryLength);
boolean firstKeyword = true;
for (; ; ) {
IToken token = ruleManager.nextToken();
final int tokenOffset = ruleManager.getTokenOffset();
final int tokenLength = ruleManager.getTokenLength();
if (token.isEOF() || tokenOffset > queryOffset + queryLength) {
break;
}
// Handle only parameters which are not in SQL blocks
int tokenType = SQLToken.T_UNKNOWN;
if (token instanceof SQLToken) {
tokenType = ((SQLToken) token).getType();
}
if (token.isWhitespace() || tokenType == SQLToken.T_COMMENT) {
continue;
}
if (!supportParamsInDDL) {
if (firstKeyword) {
// Detect query type
try {
String tokenText = document.get(tokenOffset, tokenLength);
if (ArrayUtils.containsIgnoreCase(sqlDialect.getDDLKeywords(), tokenText)) {
// DDL doesn't support parameters
return null;
}
execQuery = ArrayUtils.containsIgnoreCase(sqlDialect.getExecuteKeywords(), tokenText);
} catch (BadLocationException e) {
log.warn(e);
}
firstKeyword = false;
}
}
if (tokenType == SQLToken.T_PARAMETER && tokenLength > 0) {
try {
String paramName = document.get(tokenOffset, tokenLength);
if (execQuery && paramName.equals(String.valueOf(syntaxManager.getAnonymousParameterMark()))) {
// Skip ? parameters for stored procedures (they have special meaning? [DB2])
continue;
}
if (parameters == null) {
parameters = new ArrayList<>();
}
SQLQueryParameter parameter = new SQLQueryParameter(
syntaxManager,
parameters.size(),
paramName,
tokenOffset - queryOffset,
tokenLength);
SQLQueryParameter previous = null;
if (parameter.isNamed()) {
for (int i = parameters.size(); i > 0; i--) {
if (parameters.get(i - 1).getName().equals(paramName)) {
previous = parameters.get(i - 1);
break;
}
}
}
parameter.setPrevious(previous);
parameters.add(parameter);
} catch (BadLocationException e) {
log.warn("Can't extract query parameter", e);
}
}
}
if (syntaxManager.isVariablesEnabled()) {
try {
// Find variables in strings, comments, etc
// Use regex
String query = document.get(queryOffset, queryLength);
Matcher matcher = SQLVariableRule.VARIABLE_PATTERN.matcher(query);
int position = 0;
while (matcher.find(position)) {
{
int start = matcher.start();
int orderPos = 0;
SQLQueryParameter param = null;
if (parameters != null) {
for (SQLQueryParameter p : parameters) {
if (p.getTokenOffset() == start) {
param = p;
break;
} else if (p.getTokenOffset() < start) {
orderPos++;
}
}
}
if (param == null) {
param = new SQLQueryParameter(syntaxManager, orderPos, matcher.group(0), start, matcher.end() - matcher.start());
if (parameters == null) {
parameters = new ArrayList<>();
}
parameters.add(param.getOrdinalPosition(), param);
}
}
position = matcher.end();
}
} catch (BadLocationException e) {
log.warn("Error parsing variables", e);
}
}
return parameters;
}
protected List<SQLQueryParameter> parseParameters(IDocument document, SQLQuery query) {
return parseParameters(document, query.getOffset(), query.getLength());
}
protected List<SQLQueryParameter> parseParameters(String query) {
return parseParameters(new Document(query), 0, query.length());
}
public boolean isDisposed() {
return
getSourceViewer() == null ||
getSourceViewer().getTextWidget() == null ||
getSourceViewer().getTextWidget().isDisposed();
}
@Nullable
@Override
public ICommentsSupport getCommentsSupport() {
final SQLDialect dialect = getSQLDialect();
return new ICommentsSupport() {
@Nullable
@Override
public Pair<String, String> getMultiLineComments() {
return dialect.getMultiLineComments();
}
@Override
public String[] getSingleLineComments() {
return dialect.getSingleLineComments();
}
};
}
protected String[] collectContextMenuPreferencePages() {
String[] ids = super.collectContextMenuPreferencePages();
String[] more = new String[ids.length + 6];
more[ids.length] = PrefPageSQLEditor.PAGE_ID;
more[ids.length + 1] = PrefPageSQLExecute.PAGE_ID;
more[ids.length + 2] = PrefPageSQLCompletion.PAGE_ID;
more[ids.length + 3] = PrefPageSQLFormat.PAGE_ID;
more[ids.length + 4] = PrefPageSQLResources.PAGE_ID;
more[ids.length + 5] = PrefPageSQLTemplates.PAGE_ID;
System.arraycopy(ids, 0, more, 0, ids.length);
return more;
}
@Override
public boolean visualizeError(@NotNull DBRProgressMonitor monitor, @NotNull Throwable error) {
Document document = getDocument();
SQLQuery query = new SQLQuery(getDataSource(), document.get(), 0, document.getLength());
return scrollCursorToError(monitor, query, error);
}
/**
* Error handling
*/
protected boolean scrollCursorToError(@NotNull DBRProgressMonitor monitor, @NotNull SQLQuery query, @NotNull Throwable error) {
try {
DBCExecutionContext context = getExecutionContext();
boolean scrolled = false;
DBPErrorAssistant errorAssistant = DBUtils.getAdapter(DBPErrorAssistant.class, context.getDataSource());
if (errorAssistant != null) {
DBPErrorAssistant.ErrorPosition[] positions = errorAssistant.getErrorPosition(
monitor, context, query.getText(), error);
if (positions != null && positions.length > 0) {
int queryStartOffset = query.getOffset();
int queryLength = query.getLength();
DBPErrorAssistant.ErrorPosition pos = positions[0];
if (pos.line < 0) {
if (pos.position >= 0) {
// Only position
getSelectionProvider().setSelection(new TextSelection(queryStartOffset + pos.position, 0));
scrolled = true;
}
} else {
// Line + position
Document document = getDocument();
if (document != null) {
int startLine = document.getLineOfOffset(queryStartOffset);
int errorOffset = document.getLineOffset(startLine + pos.line);
int errorLength;
if (pos.position >= 0) {
errorOffset += pos.position;
errorLength = 1;
} else {
errorLength = document.getLineLength(startLine + pos.line);
}
if (errorOffset < queryStartOffset) errorOffset = queryStartOffset;
if (errorLength > queryLength) errorLength = queryLength;
getSelectionProvider().setSelection(new TextSelection(errorOffset, errorLength));
scrolled = true;
}
}
}
}
return scrolled;
// if (!scrolled) {
// // Can't position on error - let's just select entire problem query
// showStatementInEditor(result.getStatement(), true);
// }
} catch (Exception e) {
log.warn("Error positioning on query error", e);
return false;
}
}
public boolean isFoldingEnabled() {
return getActivePreferenceStore().getBoolean(SQLPreferenceConstants.FOLDING_ENABLED);
}
/**
* Updates the status fields for the given category.
*
* @param category the category
* @since 2.0
*/
protected void updateStatusField(String category) {
if (STATS_CATEGORY_SELECTION_STATE.equals(category)) {
IStatusField field = getStatusField(category);
if (field != null) {
StringBuilder txt = new StringBuilder("Sel: ");
ISelection selection = getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
txt.append(textSelection.getLength()).append(" | ");
if (((ITextSelection) selection).getLength() <= 0) {
txt.append(0);
} else {
txt.append(textSelection.getEndLine() - textSelection.getStartLine() + 1);
}
}
field.setText(txt.toString());
}
} else {
super.updateStatusField(category);
}
}
/////////////////////////////////////////////////////////////////
// Occurrences highlight
protected void updateOccurrenceAnnotations(ITextSelection selection) {
if (this.occurrencesFinderJob != null) {
this.occurrencesFinderJob.cancel();
}
if (this.markOccurrencesUnderCursor || this.markOccurrencesForSelection) {
if (selection != null) {
IDocument document = this.getSourceViewer().getDocument();
if (document != null) {
// Get full word
SQLWordDetector wordDetector = new SQLWordDetector();
int startPos = selection.getOffset();
int endPos = startPos + selection.getLength();
try {
int documentLength = document.getLength();
while (startPos > 0 && wordDetector.isWordPart(document.getChar(startPos - 1))) {
startPos--;
}
while (endPos < documentLength && wordDetector.isWordPart(document.getChar(endPos))) {
endPos++;
}
} catch (BadLocationException e) {
log.debug("Error detecting current word: " + e.getMessage());
}
String wordSelected = null;
String wordUnderCursor = null;
if (markOccurrencesUnderCursor) {
try {
wordUnderCursor = document.get(startPos, endPos - startPos).trim();
} catch (BadLocationException e) {
log.debug("Error detecting word under cursor", e);
}
}
if (markOccurrencesForSelection) {
wordSelected = selection.getText();
for (int i = 0; i < wordSelected.length(); i++) {
if (!wordDetector.isWordPart(wordSelected.charAt(i))) {
wordSelected = null;
break;
}
}
}
OccurrencesFinder finder = new OccurrencesFinder(document, wordUnderCursor, wordSelected);
List<OccurrencePosition> positions = finder.perform();
if (!CommonUtils.isEmpty(positions)) {
this.occurrencesFinderJob = new OccurrencesFinderJob(positions);
this.occurrencesFinderJob.run(new NullProgressMonitor());
} else {
this.removeOccurrenceAnnotations();
}
}
}
}
}
private void removeOccurrenceAnnotations() {
IDocumentProvider documentProvider = this.getDocumentProvider();
if (documentProvider != null) {
IAnnotationModel annotationModel = documentProvider.getAnnotationModel(this.getEditorInput());
if (annotationModel != null && this.occurrenceAnnotations != null) {
synchronized (LOCK_OBJECT) {
this.updateAnnotationModelForRemoves(annotationModel);
}
}
}
}
private void updateAnnotationModelForRemoves(IAnnotationModel annotationModel) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension) annotationModel).replaceAnnotations(this.occurrenceAnnotations, null);
} else {
int i = 0;
for (int length = this.occurrenceAnnotations.length; i < length; ++i) {
annotationModel.removeAnnotation(this.occurrenceAnnotations[i]);
}
}
this.occurrenceAnnotations = null;
}
protected void installOccurrencesFinder() {
if (this.getSelectionProvider() != null) {
ISelection selection = this.getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
this.updateOccurrenceAnnotations((ITextSelection) selection);
}
}
if (this.occurrencesFinderJobCanceler == null) {
this.occurrencesFinderJobCanceler = new SQLEditorBase.OccurrencesFinderJobCanceler();
this.occurrencesFinderJobCanceler.install();
}
}
protected void uninstallOccurrencesFinder() {
this.markOccurrencesUnderCursor = false;
this.markOccurrencesForSelection = false;
if (this.occurrencesFinderJob != null) {
this.occurrencesFinderJob.cancel();
this.occurrencesFinderJob = null;
}
if (this.occurrencesFinderJobCanceler != null) {
this.occurrencesFinderJobCanceler.uninstall();
this.occurrencesFinderJobCanceler = null;
}
this.removeOccurrenceAnnotations();
}
public boolean isMarkingOccurrences() {
return this.markOccurrencesUnderCursor;
}
public void setMarkingOccurrences(boolean markUnderCursor, boolean markSelection) {
if (markUnderCursor != this.markOccurrencesUnderCursor || markSelection != this.markOccurrencesForSelection) {
this.markOccurrencesUnderCursor = markUnderCursor;
this.markOccurrencesForSelection = markSelection;
if (this.markOccurrencesUnderCursor || this.markOccurrencesForSelection) {
this.installOccurrencesFinder();
} else {
this.uninstallOccurrencesFinder();
}
}
}
private class EditorSelectionChangedListener implements ISelectionChangedListener {
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider instanceof IPostSelectionProvider) {
((IPostSelectionProvider) selectionProvider).addPostSelectionChangedListener(this);
} else if (selectionProvider != null) {
selectionProvider.addSelectionChangedListener(this);
}
}
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider instanceof IPostSelectionProvider) {
((IPostSelectionProvider) selectionProvider).removePostSelectionChangedListener(this);
} else if (selectionProvider != null) {
selectionProvider.removeSelectionChangedListener(this);
}
}
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection instanceof ITextSelection) {
SQLEditorBase.this.updateOccurrenceAnnotations((ITextSelection) selection);
}
}
}
class OccurrencesFinderJob extends Job {
private boolean isCanceled = false;
private IProgressMonitor progressMonitor;
private List<OccurrencePosition> positions;
public OccurrencesFinderJob(List<OccurrencePosition> positions) {
super("Occurrences Marker");
this.positions = positions;
}
void doCancel() {
this.isCanceled = true;
this.cancel();
}
private boolean isCanceled() {
return this.isCanceled || this.progressMonitor.isCanceled();
}
public IStatus run(IProgressMonitor progressMonitor) {
this.progressMonitor = progressMonitor;
if (!this.isCanceled()) {
ITextViewer textViewer = SQLEditorBase.this.getViewer();
if (textViewer != null) {
IDocument document = textViewer.getDocument();
if (document != null) {
IDocumentProvider documentProvider = SQLEditorBase.this.getDocumentProvider();
if (documentProvider != null) {
IAnnotationModel annotationModel = documentProvider.getAnnotationModel(SQLEditorBase.this.getEditorInput());
if (annotationModel != null) {
Map<Annotation, Position> annotationMap = new LinkedHashMap<>(this.positions.size());
for (OccurrencePosition position : this.positions) {
if (this.isCanceled()) {
break;
}
try {
String message = document.get(position.offset, position.length);
annotationMap.put(
new Annotation(
position.forSelection ?
SQLEditorContributions.OCCURRENCES_FOR_SELECTION_ANNOTATION_ID :
SQLEditorContributions.OCCURRENCES_UNDER_CURSOR_ANNOTATION_ID,
false,
message),
position);
} catch (BadLocationException ex) {
//
}
}
if (!this.isCanceled()) {
synchronized (LOCK_OBJECT) {
this.updateAnnotations(annotationModel, annotationMap);
}
return Status.OK_STATUS;
}
}
}
}
}
}
return Status.CANCEL_STATUS;
}
private void updateAnnotations(IAnnotationModel annotationModel, Map<Annotation, Position> annotationMap) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension) annotationModel).replaceAnnotations(SQLEditorBase.this.occurrenceAnnotations, annotationMap);
} else {
SQLEditorBase.this.removeOccurrenceAnnotations();
for (Map.Entry<Annotation, Position> mapEntry : annotationMap.entrySet()) {
annotationModel.addAnnotation(mapEntry.getKey(), mapEntry.getValue());
}
}
SQLEditorBase.this.occurrenceAnnotations = annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
}
class OccurrencesFinderJobCanceler implements IDocumentListener, ITextInputListener {
public void install() {
ISourceViewer sourceViewer = SQLEditorBase.this.getSourceViewer();
if (sourceViewer != null) {
StyledText text = sourceViewer.getTextWidget();
if (text != null && !text.isDisposed()) {
sourceViewer.addTextInputListener(this);
IDocument document = sourceViewer.getDocument();
if (document != null) {
document.addDocumentListener(this);
}
}
}
}
public void uninstall() {
ISourceViewer sourceViewer = SQLEditorBase.this.getSourceViewer();
if (sourceViewer != null) {
sourceViewer.removeTextInputListener(this);
}
IDocumentProvider documentProvider = SQLEditorBase.this.getDocumentProvider();
if (documentProvider != null) {
IDocument document = documentProvider.getDocument(SQLEditorBase.this.getEditorInput());
if (document != null) {
document.removeDocumentListener(this);
}
}
}
public void documentAboutToBeChanged(DocumentEvent event) {
if (SQLEditorBase.this.occurrencesFinderJob != null) {
SQLEditorBase.this.occurrencesFinderJob.doCancel();
}
}
public void documentChanged(DocumentEvent event) {
}
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput != null) {
oldInput.removeDocumentListener(this);
}
}
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput != null) {
newInput.addDocumentListener(this);
}
}
}
private static class OccurrencePosition extends Position {
boolean forSelection;
OccurrencePosition(int offset, int length, boolean forSelection) {
super(offset, length);
this.forSelection = forSelection;
}
}
private static class OccurrencesFinder {
private IDocument fDocument;
private String wordUnderCursor;
private String wordSelected;
OccurrencesFinder(IDocument document, String wordUnderCursor, String wordSelected) {
this.fDocument = document;
this.wordUnderCursor = wordUnderCursor;
this.wordSelected = wordSelected;
}
public List<OccurrencePosition> perform() {
if (CommonUtils.isEmpty(wordUnderCursor) && CommonUtils.isEmpty(wordSelected)) {
return null;
}
List<OccurrencePosition> positions = new ArrayList<>();
try {
if (CommonUtils.equalObjects(wordUnderCursor, wordSelected)) {
// Search only selected words
findPositions(wordUnderCursor, positions, true);
} else {
findPositions(wordUnderCursor, positions, false);
if (!CommonUtils.isEmpty(wordSelected)) {
findPositions(wordSelected, positions, true);
}
}
} catch (BadLocationException e) {
log.debug("Error finding occurrences: " + e.getMessage());
}
return positions;
}
private void findPositions(String searchFor, List<OccurrencePosition> positions, boolean forSelection) throws BadLocationException {
FindReplaceDocumentAdapter findReplaceDocumentAdapter = new FindReplaceDocumentAdapter(fDocument);
for (int offset = 0; ; ) {
IRegion region = findReplaceDocumentAdapter.find(offset, searchFor, true, false, !forSelection, false);
if (region == null) {
break;
}
positions.add(
new OccurrencePosition(region.getOffset(), region.getLength(), forSelection)
);
offset = region.getOffset() + region.getLength();
}
}
}
////////////////////////////////////////////////////////
// Brackets
// copied from JDT code
public void gotoMatchingBracket() {
ISourceViewer sourceViewer = getSourceViewer();
IDocument document = sourceViewer.getDocument();
if (document == null)
return;
IRegion selection = getSignedSelection(sourceViewer);
IRegion region = characterPairMatcher.match(document, selection.getOffset());
if (region == null) {
return;
}
int offset = region.getOffset();
int length = region.getLength();
if (length < 1)
return;
int anchor = characterPairMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset = (ICharacterPairMatcher.RIGHT == anchor) ? offset + 1 : offset + length - 1;
boolean visible = false;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion = sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible = (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
return;
}
int adjustment = getOffsetAdjustment(document, selection.getOffset() + selection.getLength(), selection.getLength());
targetOffset += adjustment;
int direction = Integer.compare(selection.getLength(), 0);
sourceViewer.setSelectedRange(targetOffset, direction);
sourceViewer.revealRange(targetOffset, direction);
}
// copied from JDT code
private static IRegion getSignedSelection(ISourceViewer sourceViewer) {
Point viewerSelection = sourceViewer.getSelectedRange();
StyledText text = sourceViewer.getTextWidget();
Point selection = text.getSelectionRange();
if (text.getCaretOffset() == selection.x) {
viewerSelection.x = viewerSelection.x + viewerSelection.y;
viewerSelection.y = -viewerSelection.y;
}
return new Region(viewerSelection.x, viewerSelection.y);
}
// copied from JDT code
private static int getOffsetAdjustment(IDocument document, int offset, int length) {
if (length == 0 || Math.abs(length) > 1)
return 0;
try {
if (length < 0) {
if (isOpeningBracket(document.getChar(offset))) {
return 1;
}
} else {
if (isClosingBracket(document.getChar(offset - 1))) {
return -1;
}
}
} catch (BadLocationException e) {
//do nothing
}
return 0;
}
private static boolean isOpeningBracket(char character) {
for (int i = 0; i < BRACKETS.length; i += 2) {
if (character == BRACKETS[i])
return true;
}
return false;
}
private static boolean isClosingBracket(char character) {
for (int i = 1; i < BRACKETS.length; i += 2) {
if (character == BRACKETS[i])
return true;
}
return false;
}
}
| plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditorBase.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.editors.sql;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.*;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.*;
import org.eclipse.jface.text.rules.FastPartitioner;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.source.*;
import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;
import org.eclipse.jface.text.source.projection.ProjectionSupport;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.texteditor.*;
import org.eclipse.ui.texteditor.templates.ITemplatesPage;
import org.eclipse.ui.themes.IThemeManager;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.*;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.ui.*;
import org.jkiss.dbeaver.ui.editors.EditorUtils;
import org.jkiss.dbeaver.ui.editors.sql.internal.SQLEditorMessages;
import org.jkiss.dbeaver.ui.editors.sql.preferences.*;
import org.jkiss.dbeaver.ui.editors.sql.registry.SQLCommandsRegistry;
import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLCharacterPairMatcher;
import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLPartitionScanner;
import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLRuleManager;
import org.jkiss.dbeaver.ui.editors.sql.syntax.rules.SQLVariableRule;
import org.jkiss.dbeaver.ui.editors.sql.syntax.tokens.SQLControlToken;
import org.jkiss.dbeaver.ui.editors.sql.syntax.tokens.SQLToken;
import org.jkiss.dbeaver.ui.editors.sql.templates.SQLTemplatesPage;
import org.jkiss.dbeaver.ui.editors.sql.util.SQLSymbolInserter;
import org.jkiss.dbeaver.ui.editors.text.BaseTextEditor;
import org.jkiss.dbeaver.ui.editors.text.parser.SQLWordDetector;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import org.jkiss.utils.Pair;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
/**
* SQL Executor
*/
public abstract class SQLEditorBase extends BaseTextEditor implements DBPContextProvider, IErrorVisualizer {
static protected final Log log = Log.getLog(SQLEditorBase.class);
private static final long MAX_FILE_LENGTH_FOR_RULES = 2000000;
public static final String STATS_CATEGORY_SELECTION_STATE = "SelectionState";
protected final static char[] BRACKETS = {'{', '}', '(', ')', '[', ']', '<', '>'};
static {
// SQL editor preferences. Do this here because it initializes display
// (that's why we can't run it in prefs initializer classes which run before workbench creation)
{
IPreferenceStore editorStore = EditorsUI.getPreferenceStore();
editorStore.setDefault(SQLPreferenceConstants.MATCHING_BRACKETS, true);
//editorStore.setDefault(SQLPreferenceConstants.MATCHING_BRACKETS_COLOR, "128,128,128"); //$NON-NLS-1$
}
}
private final Object LOCK_OBJECT = new Object();
@NotNull
private final SQLSyntaxManager syntaxManager;
@NotNull
private final SQLRuleManager ruleManager;
private ProjectionSupport projectionSupport;
private ProjectionAnnotationModel annotationModel;
//private Map<Annotation, Position> curAnnotations;
//private IAnnotationAccess annotationAccess;
private boolean hasVerticalRuler = true;
private SQLTemplatesPage templatesPage;
private IPropertyChangeListener themeListener;
private SQLEditorControl editorControl;
//private ActivationListener activationListener = new ActivationListener();
private EditorSelectionChangedListener selectionChangedListener = new EditorSelectionChangedListener();
private Annotation[] occurrenceAnnotations = null;
private boolean markOccurrencesUnderCursor;
private boolean markOccurrencesForSelection;
private OccurrencesFinderJob occurrencesFinderJob;
private OccurrencesFinderJobCanceler occurrencesFinderJobCanceler;
private ICharacterPairMatcher characterPairMatcher;
public SQLEditorBase() {
super();
syntaxManager = new SQLSyntaxManager();
ruleManager = new SQLRuleManager(syntaxManager);
themeListener = new IPropertyChangeListener() {
long lastUpdateTime = 0;
@Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(IThemeManager.CHANGE_CURRENT_THEME) ||
event.getProperty().startsWith("org.jkiss.dbeaver.sql.editor")) {
if (lastUpdateTime > 0 && System.currentTimeMillis() - lastUpdateTime < 500) {
// Do not update too often (theme change may trigger this hundreds of times)
return;
}
lastUpdateTime = System.currentTimeMillis();
UIUtils.asyncExec(() -> {
ISourceViewer sourceViewer = getSourceViewer();
if (sourceViewer != null) {
reloadSyntaxRules();
// Reconfigure to let comments/strings colors to take effect
sourceViewer.configure(getSourceViewerConfiguration());
}
});
}
}
};
PlatformUI.getWorkbench().getThemeManager().addPropertyChangeListener(themeListener);
//setDocumentProvider(new SQLDocumentProvider());
setSourceViewerConfiguration(new SQLEditorSourceViewerConfiguration(this, getPreferenceStore()));
setKeyBindingScopes(getKeyBindingContexts()); //$NON-NLS-1$
}
public static boolean isBigScript(@Nullable IEditorInput editorInput) {
if (editorInput != null) {
File file = EditorUtils.getLocalFileFromInput(editorInput);
if (file != null && file.length() > MAX_FILE_LENGTH_FOR_RULES) {
return true;
}
}
return false;
}
static boolean isReadEmbeddedBinding() {
return DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.SCRIPT_BIND_EMBEDDED_READ);
}
static boolean isWriteEmbeddedBinding() {
return DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.SCRIPT_BIND_EMBEDDED_WRITE);
}
protected void handleInputChange(IEditorInput input) {
if (isBigScript(input)) {
uninstallOccurrencesFinder();
} else {
setMarkingOccurrences(
DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_UNDER_CURSOR),
DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_FOR_SELECTION));
}
}
@Override
protected void updateSelectionDependentActions() {
super.updateSelectionDependentActions();
updateStatusField(STATS_CATEGORY_SELECTION_STATE);
}
protected String[] getKeyBindingContexts() {
return new String[]{
TEXT_EDITOR_CONTEXT,
SQLEditorContributions.SQL_EDITOR_CONTEXT,
SQLEditorContributions.SQL_EDITOR_SCRIPT_CONTEXT,
SQLEditorContributions.SQL_EDITOR_CONTROL_CONTEXT};
}
@Override
protected void initializeEditor() {
super.initializeEditor();
this.markOccurrencesUnderCursor = DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_UNDER_CURSOR);
this.markOccurrencesForSelection = DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_FOR_SELECTION);
setEditorContextMenuId(SQLEditorContributions.SQL_EDITOR_CONTEXT_MENU_ID);
setRulerContextMenuId(SQLEditorContributions.SQL_RULER_CONTEXT_MENU_ID);
}
public DBPDataSource getDataSource() {
DBCExecutionContext context = getExecutionContext();
return context == null ? null : context.getDataSource();
}
public DBPPreferenceStore getActivePreferenceStore() {
if (this instanceof IDataSourceContainerProvider) {
DBPDataSourceContainer container = ((IDataSourceContainerProvider) this).getDataSourceContainer();
if (container != null) {
return container.getPreferenceStore();
}
}
DBPDataSource dataSource = getDataSource();
return dataSource == null ? DBWorkbench.getPlatform().getPreferenceStore() : dataSource.getContainer().getPreferenceStore();
}
@Override
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
String property = event.getProperty();
if (SQLPreferenceConstants.MARK_OCCURRENCES_UNDER_CURSOR.equals(property) || SQLPreferenceConstants.MARK_OCCURRENCES_FOR_SELECTION.equals(property)) {
setMarkingOccurrences(
DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_UNDER_CURSOR),
DBWorkbench.getPlatform().getPreferenceStore().getBoolean(SQLPreferenceConstants.MARK_OCCURRENCES_FOR_SELECTION));
} else {
super.handlePreferenceStoreChanged(event);
}
}
@NotNull
public SQLDialect getSQLDialect() {
DBPDataSource dataSource = getDataSource();
// Refresh syntax
if (dataSource instanceof SQLDataSource) {
return ((SQLDataSource) dataSource).getSQLDialect();
}
return BasicSQLDialect.INSTANCE;
}
@NotNull
public SQLSyntaxManager getSyntaxManager() {
return syntaxManager;
}
@NotNull
public SQLRuleManager getRuleManager() {
return ruleManager;
}
public ProjectionAnnotationModel getAnnotationModel() {
return annotationModel;
}
public SQLEditorSourceViewerConfiguration getViewerConfiguration() {
return (SQLEditorSourceViewerConfiguration) super.getSourceViewerConfiguration();
}
@Override
public void createPartControl(Composite parent) {
setRangeIndicator(new DefaultRangeIndicator());
editorControl = new SQLEditorControl(parent, this);
super.createPartControl(editorControl);
//this.getEditorSite().getShell().addShellListener(this.activationListener);
this.selectionChangedListener = new EditorSelectionChangedListener();
this.selectionChangedListener.install(this.getSelectionProvider());
if (this.markOccurrencesUnderCursor || this.markOccurrencesForSelection) {
this.installOccurrencesFinder();
}
ProjectionViewer viewer = (ProjectionViewer) getSourceViewer();
projectionSupport = new ProjectionSupport(
viewer,
getAnnotationAccess(),
getSharedColors());
projectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
projectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
projectionSupport.install();
viewer.doOperation(ProjectionViewer.TOGGLE);
annotationModel = viewer.getProjectionAnnotationModel();
// Symbol inserter
{
SQLSymbolInserter symbolInserter = new SQLSymbolInserter(this);
DBPPreferenceStore preferenceStore = getActivePreferenceStore();
boolean closeSingleQuotes = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_SINGLE_QUOTES);
boolean closeDoubleQuotes = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_DOUBLE_QUOTES);
boolean closeBrackets = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_BRACKETS);
symbolInserter.setCloseSingleQuotesEnabled(closeSingleQuotes);
symbolInserter.setCloseDoubleQuotesEnabled(closeDoubleQuotes);
symbolInserter.setCloseBracketsEnabled(closeBrackets);
ISourceViewer sourceViewer = getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension) {
((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(symbolInserter);
}
}
{
// Context listener
EditorUtils.trackControlContext(getSite(), getViewer().getTextWidget(), SQLEditorContributions.SQL_EDITOR_CONTROL_CONTEXT);
}
}
public SQLEditorControl getEditorControlWrapper() {
return editorControl;
}
@Override
public void updatePartControl(IEditorInput input) {
super.updatePartControl(input);
}
protected IOverviewRuler createOverviewRuler(ISharedTextColors sharedColors) {
if (isOverviewRulerVisible()) {
return super.createOverviewRuler(sharedColors);
} else {
return new OverviewRuler(getAnnotationAccess(), 0, sharedColors);
}
}
@Override
protected boolean isOverviewRulerVisible() {
return false;
}
// Most left ruler
@Override
protected IVerticalRulerColumn createAnnotationRulerColumn(CompositeRuler ruler) {
if (isAnnotationRulerVisible()) {
return super.createAnnotationRulerColumn(ruler);
} else {
return new AnnotationRulerColumn(0, getAnnotationAccess());
}
}
protected boolean isAnnotationRulerVisible() {
return false;
}
@Override
protected IVerticalRuler createVerticalRuler() {
return hasVerticalRuler ? super.createVerticalRuler() : new VerticalRuler(0);
}
public void setHasVerticalRuler(boolean hasVerticalRuler) {
this.hasVerticalRuler = hasVerticalRuler;
}
protected ISharedTextColors getSharedColors() {
return UIUtils.getSharedTextColors();
}
@Override
protected void doSetInput(IEditorInput input) throws CoreException {
handleInputChange(input);
super.doSetInput(input);
}
@Override
public void doSave(IProgressMonitor progressMonitor) {
super.doSave(progressMonitor);
handleInputChange(getEditorInput());
}
@Override
protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
fAnnotationAccess = getAnnotationAccess();
fOverviewRuler = createOverviewRuler(getSharedColors());
SQLEditorSourceViewer sourceViewer = createSourceViewer(parent, ruler, styles, fOverviewRuler);
getSourceViewerDecorationSupport(sourceViewer);
return sourceViewer;
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
char[] matchChars = BRACKETS; //which brackets to match
try {
characterPairMatcher = new SQLCharacterPairMatcher(this, matchChars,
SQLPartitionScanner.SQL_PARTITIONING,
true);
} catch (Throwable e) {
// If we below Eclipse 4.2.1
characterPairMatcher = new SQLCharacterPairMatcher(this, matchChars, SQLPartitionScanner.SQL_PARTITIONING);
}
support.setCharacterPairMatcher(characterPairMatcher);
support.setMatchingCharacterPainterPreferenceKeys(SQLPreferenceConstants.MATCHING_BRACKETS, SQLPreferenceConstants.MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
@NotNull
protected SQLEditorSourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles, IOverviewRuler overviewRuler) {
return new SQLEditorSourceViewer(
parent,
ruler,
overviewRuler,
true,
styles);
}
@Override
protected IAnnotationAccess createAnnotationAccess() {
return new SQLMarkerAnnotationAccess();
}
/*
protected void adjustHighlightRange(int offset, int length)
{
ISourceViewer viewer = getSourceViewer();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
extension.exposeModelRange(new Region(offset, length));
}
}
*/
@SuppressWarnings("unchecked")
@Override
public <T> T getAdapter(Class<T> required) {
if (projectionSupport != null) {
Object adapter = projectionSupport.getAdapter(
getSourceViewer(), required);
if (adapter != null)
return (T) adapter;
}
if (ITemplatesPage.class.equals(required)) {
return (T) getTemplatesPage();
}
return super.getAdapter(required);
}
public SQLTemplatesPage getTemplatesPage() {
if (templatesPage == null)
templatesPage = new SQLTemplatesPage(this);
return templatesPage;
}
@Override
public void dispose() {
if (this.selectionChangedListener != null) {
this.selectionChangedListener.uninstall(this.getSelectionProvider());
this.selectionChangedListener = null;
}
/*
if (this.activationListener != null) {
Shell shell = this.getEditorSite().getShell();
if (shell != null && !shell.isDisposed()) {
shell.removeShellListener(this.activationListener);
}
this.activationListener = null;
}
*/
if (themeListener != null) {
PlatformUI.getWorkbench().getThemeManager().removePropertyChangeListener(themeListener);
themeListener = null;
}
super.dispose();
}
@Override
protected void createActions() {
super.createActions();
ResourceBundle bundle = ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME);
IAction a = new TextOperationAction(
bundle,
SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL),
this,
ISourceViewer.CONTENTASSIST_PROPOSALS);
a.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL, a);
a = new TextOperationAction(
bundle,
SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP),
this,
ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION);
a.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP, a);
a = new TextOperationAction(
bundle,
SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION),
this,
ISourceViewer.INFORMATION);
a.setActionDefinitionId(ITextEditorActionDefinitionIds.SHOW_INFORMATION);
setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION, a);
a = new TextOperationAction(
bundle,
SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL),
this,
ISourceViewer.FORMAT);
a.setActionDefinitionId(SQLEditorCommands.CMD_CONTENT_FORMAT);
setAction(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL, a);
setAction(ITextEditorActionConstants.CONTEXT_PREFERENCES, new Action(SQLEditorMessages.editor_sql_preference) { //$NON-NLS-1$
public void run() {
Shell shell = getSourceViewer().getTextWidget().getShell();
String[] preferencePages = collectContextMenuPreferencePages();
if (preferencePages.length > 0 && (shell == null || !shell.isDisposed()))
PreferencesUtil.createPreferenceDialogOn(shell, preferencePages[0], preferencePages, getEditorInput()).open();
}
});
/*
// Add the task action to the Edit pulldown menu (bookmark action is 'free')
ResourceAction ra = new AddTaskAction(bundle, "AddTask.", this);
ra.setHelpContextId(ITextEditorHelpContextIds.ADD_TASK_ACTION);
ra.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(IDEActionFactory.ADD_TASK.getId(), ra);
*/
}
// Exclude input additions. Get rid of tons of crap from debug/team extensions
@Override
protected boolean isEditorInputIncludedInContextMenu() {
return false;
}
@Override
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
//menu.add(new Separator("content"));//$NON-NLS-1$
addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL);
addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP);
addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION);
menu.insertBefore(IWorkbenchActionConstants.MB_ADDITIONS, ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.navigate.object"));
{
MenuManager formatMenu = new MenuManager(SQLEditorMessages.sql_editor_menu_format, "format");
IAction formatAction = getAction(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL);
if (formatAction != null) {
formatMenu.add(formatAction);
}
formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.morph.delimited.list"));
formatMenu.add(getAction(ITextEditorActionConstants.UPPER_CASE));
formatMenu.add(getAction(ITextEditorActionConstants.LOWER_CASE));
formatMenu.add(new Separator());
formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.word.wrap"));
formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.comment.single"));
formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.comment.multi"));
menu.insertAfter(GROUP_SQL_ADDITIONS, formatMenu);
}
//menu.remove(IWorkbenchActionConstants.MB_ADDITIONS);
}
public void reloadSyntaxRules() {
// Refresh syntax
SQLDialect dialect = getSQLDialect();
syntaxManager.init(dialect, getActivePreferenceStore());
ruleManager.refreshRules(getDataSource(), getEditorInput());
Document document = getDocument();
if (document != null) {
IDocumentPartitioner partitioner = new FastPartitioner(
new SQLPartitionScanner(dialect),
SQLPartitionScanner.SQL_CONTENT_TYPES);
partitioner.connect(document);
try {
document.setDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING, partitioner);
} catch (Throwable e) {
log.warn("Error setting SQL partitioner", e); //$NON-NLS-1$
}
ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
if (projectionViewer != null && projectionViewer.getAnnotationModel() != null && document.getLength() > 0) {
// Refresh viewer
//projectionViewer.getTextWidget().redraw();
try {
projectionViewer.reinitializeProjection();
} catch (Throwable ex) {
// We can catch OutOfMemory here for too big/complex documents
log.warn("Can't initialize SQL syntax projection", ex); //$NON-NLS-1$
}
}
}
/*
Color fgColor = ruleManager.getColor(SQLConstants.CONFIG_COLOR_TEXT);
Color bgColor = ruleManager.getColor(getDataSource() == null ?
SQLConstants.CONFIG_COLOR_DISABLED :
SQLConstants.CONFIG_COLOR_BACKGROUND);
final StyledText textWidget = getTextViewer().getTextWidget();
if (fgColor != null) {
textWidget.setForeground(fgColor);
}
textWidget.setBackground(bgColor);
*/
// Update configuration
if (getSourceViewerConfiguration() instanceof SQLEditorSourceViewerConfiguration) {
((SQLEditorSourceViewerConfiguration) getSourceViewerConfiguration()).onDataSourceChange();
}
final IVerticalRuler verticalRuler = getVerticalRuler();
if (verticalRuler != null) {
verticalRuler.update();
}
}
public boolean hasActiveQuery() {
Document document = getDocument();
if (document == null) {
return false;
}
ISelectionProvider selectionProvider = getSelectionProvider();
if (selectionProvider == null) {
return false;
}
ITextSelection selection = (ITextSelection) selectionProvider.getSelection();
String selText = selection.getText();
if (CommonUtils.isEmpty(selText) && selection.getOffset() >= 0 && selection.getOffset() < document.getLength()) {
try {
IRegion lineRegion = document.getLineInformationOfOffset(selection.getOffset());
selText = document.get(lineRegion.getOffset(), lineRegion.getLength());
} catch (BadLocationException e) {
log.warn(e);
return false;
}
}
return !CommonUtils.isEmptyTrimmed(selText);
}
@Nullable
public SQLScriptElement extractActiveQuery() {
SQLScriptElement element;
ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
String selText = selection.getText();
if (getActivePreferenceStore().getBoolean(ModelPreferences.QUERY_REMOVE_TRAILING_DELIMITER)) {
selText = SQLUtils.trimQueryStatement(getSyntaxManager(), selText, !syntaxManager.getDialect().isDelimiterAfterQuery());
}
if (!CommonUtils.isEmpty(selText)) {
SQLScriptElement parsedElement = parseQuery(getDocument(), selection.getOffset(), selection.getOffset() + selection.getLength(), selection.getOffset(), false, false);
if (parsedElement instanceof SQLControlCommand) {
// This is a command
element = parsedElement;
} else {
// Use selected query as is
selText = SQLUtils.fixLineFeeds(selText);
element = new SQLQuery(getDataSource(), selText, selection.getOffset(), selection.getLength());
}
} else if (selection.getOffset() >= 0) {
element = extractQueryAtPos(selection.getOffset());
} else {
element = null;
}
// Check query do not ends with delimiter
// (this may occur if user selected statement including delimiter)
if (element == null || CommonUtils.isEmpty(element.getText())) {
return null;
}
if (element instanceof SQLQuery && getActivePreferenceStore().getBoolean(ModelPreferences.SQL_PARAMETERS_ENABLED)) {
((SQLQuery) element).setParameters(parseParameters(getDocument(), (SQLQuery) element));
}
return element;
}
public SQLScriptElement extractQueryAtPos(int currentPos) {
Document document = getDocument();
if (document == null || document.getLength() == 0) {
return null;
}
final int docLength = document.getLength();
IDocumentPartitioner partitioner = document.getDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING);
if (partitioner != null) {
// Move to default partition. We don't want to be in the middle of multi-line comment or string
while (currentPos < docLength && isMultiCommentPartition(partitioner, currentPos)) {
currentPos++;
}
}
// Extract part of document between empty lines
int startPos = 0;
boolean useBlankLines = syntaxManager.isBlankLineDelimiter();
final String[] statementDelimiters = syntaxManager.getStatementDelimiters();
int lastPos = currentPos >= docLength ? docLength - 1 : currentPos;
try {
int currentLine = document.getLineOfOffset(currentPos);
if (useBlankLines) {
if (TextUtils.isEmptyLine(document, currentLine)) {
if (currentLine == 0) {
return null;
}
currentLine--;
if (TextUtils.isEmptyLine(document, currentLine)) {
// Prev line empty too. No chance.
return null;
}
}
}
int lineOffset = document.getLineOffset(currentLine);
int firstLine = currentLine;
while (firstLine > 0) {
if (useBlankLines) {
if (TextUtils.isEmptyLine(document, firstLine) &&
isDefaultPartition(partitioner, document.getLineOffset(firstLine))) {
break;
}
}
if (currentLine == firstLine) {
for (String delim : statementDelimiters) {
final int offset = TextUtils.getOffsetOf(document, firstLine, delim);
if (offset >= 0 && isDefaultPartition(partitioner, offset)) {
int delimOffset = document.getLineOffset(firstLine) + offset + delim.length();
if (currentPos > startPos) {
if (docLength > delimOffset) {
boolean hasValuableChars = false;
for (int i = delimOffset; i <= lastPos; i++) {
if (!Character.isWhitespace(document.getChar(i))) {
hasValuableChars = true;
break;
}
}
if (hasValuableChars) {
startPos = delimOffset;
break;
}
}
}
}
}
}
firstLine--;
}
if (startPos == 0) {
startPos = document.getLineOffset(firstLine);
}
// Move currentPos at line begin
currentPos = lineOffset;
} catch (BadLocationException e) {
log.warn(e);
}
return parseQuery(document, startPos, document.getLength(), currentPos, false, false);
}
public SQLScriptElement extractNextQuery(boolean next) {
ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
int offset = selection.getOffset();
SQLScriptElement curElement = extractQueryAtPos(offset);
if (curElement == null) {
return null;
}
Document document = getDocument();
if (document == null) {
return null;
}
try {
int docLength = document.getLength();
int curPos;
if (next) {
final String[] statementDelimiters = syntaxManager.getStatementDelimiters();
curPos = curElement.getOffset() + curElement.getLength();
while (curPos < docLength) {
char c = document.getChar(curPos);
if (!Character.isWhitespace(c)) {
boolean isDelimiter = false;
for (String delim : statementDelimiters) {
if (delim.indexOf(c) != -1) {
isDelimiter = true;
}
}
if (!isDelimiter) {
break;
}
}
curPos++;
}
} else {
curPos = curElement.getOffset() - 1;
while (curPos >= 0) {
char c = document.getChar(curPos);
if (!Character.isWhitespace(c)) {
break;
}
curPos--;
}
}
if (curPos <= 0 || curPos >= docLength) {
return null;
}
return extractQueryAtPos(curPos);
} catch (BadLocationException e) {
log.warn(e);
return null;
}
}
private static boolean isDefaultPartition(IDocumentPartitioner partitioner, int currentPos) {
return partitioner == null || IDocument.DEFAULT_CONTENT_TYPE.equals(partitioner.getContentType(currentPos));
}
private static boolean isMultiCommentPartition(IDocumentPartitioner partitioner, int currentPos) {
return partitioner != null && SQLPartitionScanner.CONTENT_TYPE_SQL_MULTILINE_COMMENT.equals(partitioner.getContentType(currentPos));
}
private void startScriptEvaluation() {
ruleManager.startEval();
}
private void endScriptEvaluation() {
ruleManager.endEval();
}
public List<SQLScriptElement> extractScriptQueries(int startOffset, int length, boolean scriptMode, boolean keepDelimiters, boolean parseParameters) {
List<SQLScriptElement> queryList = new ArrayList<>();
IDocument document = getDocument();
if (document == null) {
return queryList;
}
this.startScriptEvaluation();
try {
for (int queryOffset = startOffset; ; ) {
SQLScriptElement query = parseQuery(document, queryOffset, startOffset + length, queryOffset, scriptMode, keepDelimiters);
if (query == null) {
break;
}
queryList.add(query);
queryOffset = query.getOffset() + query.getLength();
}
} finally {
this.endScriptEvaluation();
}
if (parseParameters && getActivePreferenceStore().getBoolean(ModelPreferences.SQL_PARAMETERS_ENABLED)) {
// Parse parameters
for (SQLScriptElement query : queryList) {
if (query instanceof SQLQuery) {
((SQLQuery) query).setParameters(parseParameters(getDocument(), (SQLQuery) query));
}
}
}
return queryList;
}
protected SQLScriptElement parseQuery(final IDocument document, final int startPos, final int endPos, final int currentPos, final boolean scriptMode, final boolean keepDelimiters) {
if (endPos - startPos <= 0) {
return null;
}
SQLDialect dialect = getSQLDialect();
// Parse range
boolean useBlankLines = !scriptMode && syntaxManager.isBlankLineDelimiter();
ruleManager.setRange(document, startPos, endPos - startPos);
int statementStart = startPos;
int bracketDepth = 0;
boolean hasBlocks = false;
boolean hasValuableTokens = false;
boolean hasBlockHeader = false;
String blockTogglePattern = null;
int lastTokenLineFeeds = 0;
int prevNotEmptyTokenType = SQLToken.T_UNKNOWN;
String firstKeyword = null;
for (; ; ) {
IToken token = ruleManager.nextToken();
int tokenOffset = ruleManager.getTokenOffset();
int tokenLength = ruleManager.getTokenLength();
int tokenType = token instanceof SQLToken ? ((SQLToken) token).getType() : SQLToken.T_UNKNOWN;
if (tokenOffset < startPos) {
// This may happen with EOF tokens (bug in jface?)
return null;
}
boolean isDelimiter = tokenType == SQLToken.T_DELIMITER;
boolean isControl = false;
String delimiterText = null;
try {
if (isDelimiter) {
// Save delimiter text
try {
delimiterText = document.get(tokenOffset, tokenLength);
} catch (BadLocationException e) {
log.debug(e);
}
} else if (useBlankLines && token.isWhitespace() && tokenLength >= 1) {
// Check for blank line delimiter
if (lastTokenLineFeeds + countLineFeeds(document, tokenOffset, tokenLength) >= 2) {
isDelimiter = true;
}
}
lastTokenLineFeeds = 0;
if (tokenLength == 1) {
// Check for bracket block begin/end
try {
char aChar = document.getChar(tokenOffset);
if (aChar == '(' || aChar == '{' || aChar == '[') {
bracketDepth++;
} else if (aChar == ')' || aChar == '}' || aChar == ']') {
bracketDepth--;
}
} catch (BadLocationException e) {
log.warn(e);
}
}
if (tokenType == SQLToken.T_BLOCK_BEGIN && prevNotEmptyTokenType == SQLToken.T_BLOCK_END) {
// This is a tricky thing.
// In some dialects block end looks like END CASE, END LOOP. It is parsed as
// Block end followed by block begin (as CASE and LOOP are block begin tokens)
// So let's ignore block begin if previos token was block end and there were no delimtiers.
tokenType = SQLToken.T_UNKNOWN;
}
if (tokenType == SQLToken.T_BLOCK_HEADER) {
bracketDepth++;
hasBlocks = true;
hasBlockHeader = true;
} else if (tokenType == SQLToken.T_BLOCK_TOGGLE) {
String togglePattern;
try {
togglePattern = document.get(tokenOffset, tokenLength);
} catch (BadLocationException e) {
log.warn(e);
togglePattern = "";
}
// Second toggle pattern must be the same as first one.
// Toggles can be nested (PostgreSQL) and we need to count only outer
if (bracketDepth == 1 && togglePattern.equals(blockTogglePattern)) {
bracketDepth--;
blockTogglePattern = null;
} else if (bracketDepth == 0 && blockTogglePattern == null) {
bracketDepth++;
blockTogglePattern = togglePattern;
} else {
log.debug("Block toggle token inside another block. Can't process it");
}
hasBlocks = true;
} else if (tokenType == SQLToken.T_BLOCK_BEGIN) {
if (!hasBlockHeader) {
bracketDepth++;
}
hasBlocks = true;
hasBlockHeader = false;
} else if (bracketDepth > 0 && tokenType == SQLToken.T_BLOCK_END) {
// Sometimes query contains END clause without BEGIN. E.g. CASE, IF, etc.
// This END doesn't mean block
if (hasBlocks) {
bracketDepth--;
}
hasBlockHeader = false;
} else if (isDelimiter && bracketDepth > 0) {
// Delimiter in some brackets - ignore it
continue;
} else if (tokenType == SQLToken.T_SET_DELIMITER || tokenType == SQLToken.T_CONTROL) {
isDelimiter = true;
isControl = true;
} else if (tokenType == SQLToken.T_COMMENT) {
lastTokenLineFeeds = tokenLength < 2 ? 0 : countLineFeeds(document, tokenOffset + tokenLength - 2, 2);
}
if (firstKeyword == null && tokenLength > 0 && !token.isWhitespace()) {
switch (tokenType) {
case SQLToken.T_BLOCK_BEGIN:
case SQLToken.T_BLOCK_END:
case SQLToken.T_BLOCK_TOGGLE:
case SQLToken.T_BLOCK_HEADER:
case SQLToken.T_UNKNOWN:
try {
firstKeyword = document.get(tokenOffset, tokenLength);
} catch (BadLocationException e) {
log.error("Error getting first keyword", e);
}
break;
}
}
boolean cursorInsideToken = currentPos >= tokenOffset && currentPos < tokenOffset + tokenLength;
if (isControl && (scriptMode || cursorInsideToken) && !hasValuableTokens) {
// Control query
try {
String controlText = document.get(tokenOffset, tokenLength);
String commandId = null;
if (token instanceof SQLControlToken) {
commandId = ((SQLControlToken) token).getCommandId();
}
SQLControlCommand command = new SQLControlCommand(
getDataSource(),
syntaxManager,
controlText.trim(),
commandId,
tokenOffset,
tokenLength,
tokenType == SQLToken.T_SET_DELIMITER);
if (command.isEmptyCommand() ||
(command.getCommandId() != null &&
SQLCommandsRegistry.getInstance().getCommandHandler(command.getCommandId()) != null)) {
return command;
}
// This is not a valid command
isControl = false;
} catch (BadLocationException e) {
log.warn("Can't extract control statement", e); //$NON-NLS-1$
return null;
}
}
if (hasValuableTokens && (token.isEOF() || (isDelimiter && tokenOffset >= currentPos) || tokenOffset > endPos)) {
if (tokenOffset > endPos) {
tokenOffset = endPos;
}
if (tokenOffset >= document.getLength()) {
// Sometimes (e.g. when comment finishing script text)
// last token offset is beyond document range
tokenOffset = document.getLength();
}
assert (tokenOffset >= currentPos);
try {
// remove leading spaces
while (statementStart < tokenOffset && Character.isWhitespace(document.getChar(statementStart))) {
statementStart++;
}
// remove trailing spaces
/*
while (statementStart < tokenOffset && Character.isWhitespace(document.getChar(tokenOffset - 1))) {
tokenOffset--;
tokenLength++;
}
*/
if (tokenOffset == statementStart) {
// Empty statement
if (token.isEOF()) {
return null;
}
statementStart = tokenOffset + tokenLength;
continue;
}
String queryText = document.get(statementStart, tokenOffset - statementStart);
queryText = SQLUtils.fixLineFeeds(queryText);
if (isDelimiter && (keepDelimiters || (hasBlocks ?
dialect.isDelimiterAfterBlock() && firstKeyword != null &&
(SQLUtils.isBlockStartKeyword(dialect, firstKeyword) ||
ArrayUtils.containsIgnoreCase(dialect.getDDLKeywords(), firstKeyword) ||
ArrayUtils.containsIgnoreCase(dialect.getBlockHeaderStrings(), firstKeyword)) :
dialect.isDelimiterAfterQuery()))) {
if (delimiterText != null && delimiterText.equals(SQLConstants.DEFAULT_STATEMENT_DELIMITER)) {
// Add delimiter in the end of query. Do this only for semicolon delimiters.
// For SQL server add it in the end of query. For Oracle only after END clause
// Quite dirty workaround needed for Oracle and SQL Server.
// TODO: move this transformation into SQLDialect
queryText += delimiterText;
}
}
int queryEndPos = tokenOffset;
if (tokenType == SQLToken.T_DELIMITER) {
queryEndPos += tokenLength;
}
// make script line
return new SQLQuery(
getDataSource(),
queryText,
statementStart,
queryEndPos - statementStart);
} catch (BadLocationException ex) {
log.warn("Can't extract query", ex); //$NON-NLS-1$
return null;
}
}
if (isDelimiter) {
statementStart = tokenOffset + tokenLength;
}
if (token.isEOF()) {
return null;
}
if (!hasValuableTokens && !token.isWhitespace() && !isControl) {
if (tokenType == SQLToken.T_COMMENT) {
hasValuableTokens = dialect.supportsCommentQuery();
} else {
hasValuableTokens = true;
}
}
} finally {
if (!token.isWhitespace() && !token.isEOF()) {
prevNotEmptyTokenType = tokenType;
}
}
}
}
private static int countLineFeeds(final IDocument document, final int offset, final int length) {
int lfCount = 0;
try {
for (int i = offset; i < offset + length; i++) {
if (document.getChar(i) == '\n') {
lfCount++;
}
}
} catch (BadLocationException e) {
log.error(e);
}
return lfCount;
}
protected List<SQLQueryParameter> parseParameters(IDocument document, int queryOffset, int queryLength) {
final SQLDialect sqlDialect = getSQLDialect();
boolean supportParamsInDDL = getActivePreferenceStore().getBoolean(ModelPreferences.SQL_PARAMETERS_IN_DDL_ENABLED);
boolean execQuery = false;
List<SQLQueryParameter> parameters = null;
ruleManager.setRange(document, queryOffset, queryLength);
boolean firstKeyword = true;
for (; ; ) {
IToken token = ruleManager.nextToken();
final int tokenOffset = ruleManager.getTokenOffset();
final int tokenLength = ruleManager.getTokenLength();
if (token.isEOF() || tokenOffset > queryOffset + queryLength) {
break;
}
// Handle only parameters which are not in SQL blocks
int tokenType = SQLToken.T_UNKNOWN;
if (token instanceof SQLToken) {
tokenType = ((SQLToken) token).getType();
}
if (token.isWhitespace() || tokenType == SQLToken.T_COMMENT) {
continue;
}
if (!supportParamsInDDL) {
if (firstKeyword) {
// Detect query type
try {
String tokenText = document.get(tokenOffset, tokenLength);
if (ArrayUtils.containsIgnoreCase(sqlDialect.getDDLKeywords(), tokenText)) {
// DDL doesn't support parameters
return null;
}
execQuery = ArrayUtils.containsIgnoreCase(sqlDialect.getExecuteKeywords(), tokenText);
} catch (BadLocationException e) {
log.warn(e);
}
firstKeyword = false;
}
}
if (tokenType == SQLToken.T_PARAMETER && tokenLength > 0) {
try {
String paramName = document.get(tokenOffset, tokenLength);
if (execQuery && paramName.equals(String.valueOf(syntaxManager.getAnonymousParameterMark()))) {
// Skip ? parameters for stored procedures (they have special meaning? [DB2])
continue;
}
if (parameters == null) {
parameters = new ArrayList<>();
}
SQLQueryParameter parameter = new SQLQueryParameter(
syntaxManager,
parameters.size(),
paramName,
tokenOffset - queryOffset,
tokenLength);
SQLQueryParameter previous = null;
if (parameter.isNamed()) {
for (int i = parameters.size(); i > 0; i--) {
if (parameters.get(i - 1).getName().equals(paramName)) {
previous = parameters.get(i - 1);
break;
}
}
}
parameter.setPrevious(previous);
parameters.add(parameter);
} catch (BadLocationException e) {
log.warn("Can't extract query parameter", e);
}
}
}
if (syntaxManager.isVariablesEnabled()) {
try {
// Find variables in strings, comments, etc
// Use regex
String query = document.get(queryOffset, queryLength);
Matcher matcher = SQLVariableRule.VARIABLE_PATTERN.matcher(query);
int position = 0;
while (matcher.find(position)) {
{
int start = matcher.start();
int orderPos = 0;
SQLQueryParameter param = null;
if (parameters != null) {
for (SQLQueryParameter p : parameters) {
if (p.getTokenOffset() == start) {
param = p;
break;
} else if (p.getTokenOffset() < start) {
orderPos++;
}
}
}
if (param == null) {
param = new SQLQueryParameter(syntaxManager, orderPos, matcher.group(0), start, matcher.end() - matcher.start());
if (parameters == null) {
parameters = new ArrayList<>();
}
parameters.add(param.getOrdinalPosition(), param);
}
}
position = matcher.end();
}
} catch (BadLocationException e) {
log.warn("Error parsing variables", e);
}
}
return parameters;
}
protected List<SQLQueryParameter> parseParameters(IDocument document, SQLQuery query) {
return parseParameters(document, query.getOffset(), query.getLength());
}
protected List<SQLQueryParameter> parseParameters(String query) {
return parseParameters(new Document(query), 0, query.length());
}
public boolean isDisposed() {
return
getSourceViewer() == null ||
getSourceViewer().getTextWidget() == null ||
getSourceViewer().getTextWidget().isDisposed();
}
@Nullable
@Override
public ICommentsSupport getCommentsSupport() {
final SQLDialect dialect = getSQLDialect();
return new ICommentsSupport() {
@Nullable
@Override
public Pair<String, String> getMultiLineComments() {
return dialect.getMultiLineComments();
}
@Override
public String[] getSingleLineComments() {
return dialect.getSingleLineComments();
}
};
}
protected String[] collectContextMenuPreferencePages() {
String[] ids = super.collectContextMenuPreferencePages();
String[] more = new String[ids.length + 6];
more[ids.length] = PrefPageSQLEditor.PAGE_ID;
more[ids.length + 1] = PrefPageSQLExecute.PAGE_ID;
more[ids.length + 2] = PrefPageSQLCompletion.PAGE_ID;
more[ids.length + 3] = PrefPageSQLFormat.PAGE_ID;
more[ids.length + 4] = PrefPageSQLResources.PAGE_ID;
more[ids.length + 5] = PrefPageSQLTemplates.PAGE_ID;
System.arraycopy(ids, 0, more, 0, ids.length);
return more;
}
@Override
public boolean visualizeError(@NotNull DBRProgressMonitor monitor, @NotNull Throwable error) {
Document document = getDocument();
SQLQuery query = new SQLQuery(getDataSource(), document.get(), 0, document.getLength());
return scrollCursorToError(monitor, query, error);
}
/**
* Error handling
*/
protected boolean scrollCursorToError(@NotNull DBRProgressMonitor monitor, @NotNull SQLQuery query, @NotNull Throwable error) {
try {
DBCExecutionContext context = getExecutionContext();
boolean scrolled = false;
DBPErrorAssistant errorAssistant = DBUtils.getAdapter(DBPErrorAssistant.class, context.getDataSource());
if (errorAssistant != null) {
DBPErrorAssistant.ErrorPosition[] positions = errorAssistant.getErrorPosition(
monitor, context, query.getText(), error);
if (positions != null && positions.length > 0) {
int queryStartOffset = query.getOffset();
int queryLength = query.getLength();
DBPErrorAssistant.ErrorPosition pos = positions[0];
if (pos.line < 0) {
if (pos.position >= 0) {
// Only position
getSelectionProvider().setSelection(new TextSelection(queryStartOffset + pos.position, 0));
scrolled = true;
}
} else {
// Line + position
Document document = getDocument();
if (document != null) {
int startLine = document.getLineOfOffset(queryStartOffset);
int errorOffset = document.getLineOffset(startLine + pos.line);
int errorLength;
if (pos.position >= 0) {
errorOffset += pos.position;
errorLength = 1;
} else {
errorLength = document.getLineLength(startLine + pos.line);
}
if (errorOffset < queryStartOffset) errorOffset = queryStartOffset;
if (errorLength > queryLength) errorLength = queryLength;
getSelectionProvider().setSelection(new TextSelection(errorOffset, errorLength));
scrolled = true;
}
}
}
}
return scrolled;
// if (!scrolled) {
// // Can't position on error - let's just select entire problem query
// showStatementInEditor(result.getStatement(), true);
// }
} catch (Exception e) {
log.warn("Error positioning on query error", e);
return false;
}
}
public boolean isFoldingEnabled() {
return getActivePreferenceStore().getBoolean(SQLPreferenceConstants.FOLDING_ENABLED);
}
/**
* Updates the status fields for the given category.
*
* @param category the category
* @since 2.0
*/
protected void updateStatusField(String category) {
if (STATS_CATEGORY_SELECTION_STATE.equals(category)) {
IStatusField field = getStatusField(category);
if (field != null) {
StringBuilder txt = new StringBuilder("Sel: ");
ISelection selection = getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
txt.append(textSelection.getLength()).append(" | ");
if (((ITextSelection) selection).getLength() <= 0) {
txt.append(0);
} else {
txt.append(textSelection.getEndLine() - textSelection.getStartLine() + 1);
}
}
field.setText(txt.toString());
}
} else {
super.updateStatusField(category);
}
}
/////////////////////////////////////////////////////////////////
// Occurrences highlight
protected void updateOccurrenceAnnotations(ITextSelection selection) {
if (this.occurrencesFinderJob != null) {
this.occurrencesFinderJob.cancel();
}
if (this.markOccurrencesUnderCursor || this.markOccurrencesForSelection) {
if (selection != null) {
IDocument document = this.getSourceViewer().getDocument();
if (document != null) {
// Get full word
SQLWordDetector wordDetector = new SQLWordDetector();
int startPos = selection.getOffset();
int endPos = startPos + selection.getLength();
try {
int documentLength = document.getLength();
while (startPos > 0 && wordDetector.isWordPart(document.getChar(startPos - 1))) {
startPos--;
}
while (endPos < documentLength && wordDetector.isWordPart(document.getChar(endPos))) {
endPos++;
}
} catch (BadLocationException e) {
log.debug("Error detecting current word: " + e.getMessage());
}
String wordSelected = null;
String wordUnderCursor = null;
if (markOccurrencesUnderCursor) {
try {
wordUnderCursor = document.get(startPos, endPos - startPos).trim();
} catch (BadLocationException e) {
log.debug("Error detecting word under cursor", e);
}
}
if (markOccurrencesForSelection) {
wordSelected = selection.getText();
for (int i = 0; i < wordSelected.length(); i++) {
if (!wordDetector.isWordPart(wordSelected.charAt(i))) {
wordSelected = null;
break;
}
}
}
OccurrencesFinder finder = new OccurrencesFinder(document, wordUnderCursor, wordSelected);
List<OccurrencePosition> positions = finder.perform();
if (!CommonUtils.isEmpty(positions)) {
this.occurrencesFinderJob = new OccurrencesFinderJob(positions);
this.occurrencesFinderJob.run(new NullProgressMonitor());
} else {
this.removeOccurrenceAnnotations();
}
}
}
}
}
private void removeOccurrenceAnnotations() {
IDocumentProvider documentProvider = this.getDocumentProvider();
if (documentProvider != null) {
IAnnotationModel annotationModel = documentProvider.getAnnotationModel(this.getEditorInput());
if (annotationModel != null && this.occurrenceAnnotations != null) {
synchronized (LOCK_OBJECT) {
this.updateAnnotationModelForRemoves(annotationModel);
}
}
}
}
private void updateAnnotationModelForRemoves(IAnnotationModel annotationModel) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension) annotationModel).replaceAnnotations(this.occurrenceAnnotations, null);
} else {
int i = 0;
for (int length = this.occurrenceAnnotations.length; i < length; ++i) {
annotationModel.removeAnnotation(this.occurrenceAnnotations[i]);
}
}
this.occurrenceAnnotations = null;
}
protected void installOccurrencesFinder() {
if (this.getSelectionProvider() != null) {
ISelection selection = this.getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
this.updateOccurrenceAnnotations((ITextSelection) selection);
}
}
if (this.occurrencesFinderJobCanceler == null) {
this.occurrencesFinderJobCanceler = new SQLEditorBase.OccurrencesFinderJobCanceler();
this.occurrencesFinderJobCanceler.install();
}
}
protected void uninstallOccurrencesFinder() {
this.markOccurrencesUnderCursor = false;
this.markOccurrencesForSelection = false;
if (this.occurrencesFinderJob != null) {
this.occurrencesFinderJob.cancel();
this.occurrencesFinderJob = null;
}
if (this.occurrencesFinderJobCanceler != null) {
this.occurrencesFinderJobCanceler.uninstall();
this.occurrencesFinderJobCanceler = null;
}
this.removeOccurrenceAnnotations();
}
public boolean isMarkingOccurrences() {
return this.markOccurrencesUnderCursor;
}
public void setMarkingOccurrences(boolean markUnderCursor, boolean markSelection) {
if (markUnderCursor != this.markOccurrencesUnderCursor || markSelection != this.markOccurrencesForSelection) {
this.markOccurrencesUnderCursor = markUnderCursor;
this.markOccurrencesForSelection = markSelection;
if (this.markOccurrencesUnderCursor || this.markOccurrencesForSelection) {
this.installOccurrencesFinder();
} else {
this.uninstallOccurrencesFinder();
}
}
}
private class EditorSelectionChangedListener implements ISelectionChangedListener {
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider instanceof IPostSelectionProvider) {
((IPostSelectionProvider) selectionProvider).addPostSelectionChangedListener(this);
} else if (selectionProvider != null) {
selectionProvider.addSelectionChangedListener(this);
}
}
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider instanceof IPostSelectionProvider) {
((IPostSelectionProvider) selectionProvider).removePostSelectionChangedListener(this);
} else if (selectionProvider != null) {
selectionProvider.removeSelectionChangedListener(this);
}
}
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection instanceof ITextSelection) {
SQLEditorBase.this.updateOccurrenceAnnotations((ITextSelection) selection);
}
}
}
class OccurrencesFinderJob extends Job {
private boolean isCanceled = false;
private IProgressMonitor progressMonitor;
private List<OccurrencePosition> positions;
public OccurrencesFinderJob(List<OccurrencePosition> positions) {
super("Occurrences Marker");
this.positions = positions;
}
void doCancel() {
this.isCanceled = true;
this.cancel();
}
private boolean isCanceled() {
return this.isCanceled || this.progressMonitor.isCanceled();
}
public IStatus run(IProgressMonitor progressMonitor) {
this.progressMonitor = progressMonitor;
if (!this.isCanceled()) {
ITextViewer textViewer = SQLEditorBase.this.getViewer();
if (textViewer != null) {
IDocument document = textViewer.getDocument();
if (document != null) {
IDocumentProvider documentProvider = SQLEditorBase.this.getDocumentProvider();
if (documentProvider != null) {
IAnnotationModel annotationModel = documentProvider.getAnnotationModel(SQLEditorBase.this.getEditorInput());
if (annotationModel != null) {
Map<Annotation, Position> annotationMap = new LinkedHashMap<>(this.positions.size());
for (OccurrencePosition position : this.positions) {
if (this.isCanceled()) {
break;
}
try {
String message = document.get(position.offset, position.length);
annotationMap.put(
new Annotation(
position.forSelection ?
SQLEditorContributions.OCCURRENCES_FOR_SELECTION_ANNOTATION_ID :
SQLEditorContributions.OCCURRENCES_UNDER_CURSOR_ANNOTATION_ID,
false,
message),
position);
} catch (BadLocationException ex) {
//
}
}
if (!this.isCanceled()) {
synchronized (LOCK_OBJECT) {
this.updateAnnotations(annotationModel, annotationMap);
}
return Status.OK_STATUS;
}
}
}
}
}
}
return Status.CANCEL_STATUS;
}
private void updateAnnotations(IAnnotationModel annotationModel, Map<Annotation, Position> annotationMap) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension) annotationModel).replaceAnnotations(SQLEditorBase.this.occurrenceAnnotations, annotationMap);
} else {
SQLEditorBase.this.removeOccurrenceAnnotations();
for (Map.Entry<Annotation, Position> mapEntry : annotationMap.entrySet()) {
annotationModel.addAnnotation(mapEntry.getKey(), mapEntry.getValue());
}
}
SQLEditorBase.this.occurrenceAnnotations = annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
}
class OccurrencesFinderJobCanceler implements IDocumentListener, ITextInputListener {
public void install() {
ISourceViewer sourceViewer = SQLEditorBase.this.getSourceViewer();
if (sourceViewer != null) {
StyledText text = sourceViewer.getTextWidget();
if (text != null && !text.isDisposed()) {
sourceViewer.addTextInputListener(this);
IDocument document = sourceViewer.getDocument();
if (document != null) {
document.addDocumentListener(this);
}
}
}
}
public void uninstall() {
ISourceViewer sourceViewer = SQLEditorBase.this.getSourceViewer();
if (sourceViewer != null) {
sourceViewer.removeTextInputListener(this);
}
IDocumentProvider documentProvider = SQLEditorBase.this.getDocumentProvider();
if (documentProvider != null) {
IDocument document = documentProvider.getDocument(SQLEditorBase.this.getEditorInput());
if (document != null) {
document.removeDocumentListener(this);
}
}
}
public void documentAboutToBeChanged(DocumentEvent event) {
if (SQLEditorBase.this.occurrencesFinderJob != null) {
SQLEditorBase.this.occurrencesFinderJob.doCancel();
}
}
public void documentChanged(DocumentEvent event) {
}
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput != null) {
oldInput.removeDocumentListener(this);
}
}
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput != null) {
newInput.addDocumentListener(this);
}
}
}
private static class OccurrencePosition extends Position {
boolean forSelection;
OccurrencePosition(int offset, int length, boolean forSelection) {
super(offset, length);
this.forSelection = forSelection;
}
}
private static class OccurrencesFinder {
private IDocument fDocument;
private String wordUnderCursor;
private String wordSelected;
OccurrencesFinder(IDocument document, String wordUnderCursor, String wordSelected) {
this.fDocument = document;
this.wordUnderCursor = wordUnderCursor;
this.wordSelected = wordSelected;
}
public List<OccurrencePosition> perform() {
if (CommonUtils.isEmpty(wordUnderCursor) && CommonUtils.isEmpty(wordSelected)) {
return null;
}
List<OccurrencePosition> positions = new ArrayList<>();
try {
if (CommonUtils.equalObjects(wordUnderCursor, wordSelected)) {
// Search only selected words
findPositions(wordUnderCursor, positions, true);
} else {
findPositions(wordUnderCursor, positions, false);
if (!CommonUtils.isEmpty(wordSelected)) {
findPositions(wordSelected, positions, true);
}
}
} catch (BadLocationException e) {
log.debug("Error finding occurrences: " + e.getMessage());
}
return positions;
}
private void findPositions(String searchFor, List<OccurrencePosition> positions, boolean forSelection) throws BadLocationException {
FindReplaceDocumentAdapter findReplaceDocumentAdapter = new FindReplaceDocumentAdapter(fDocument);
for (int offset = 0; ; ) {
IRegion region = findReplaceDocumentAdapter.find(offset, searchFor, true, false, !forSelection, false);
if (region == null) {
break;
}
positions.add(
new OccurrencePosition(region.getOffset(), region.getLength(), forSelection)
);
offset = region.getOffset() + region.getLength();
}
}
}
////////////////////////////////////////////////////////
// Brackets
// copied from JDT code
public void gotoMatchingBracket() {
ISourceViewer sourceViewer = getSourceViewer();
IDocument document = sourceViewer.getDocument();
if (document == null)
return;
IRegion selection = getSignedSelection(sourceViewer);
IRegion region = characterPairMatcher.match(document, selection.getOffset());
if (region == null) {
return;
}
int offset = region.getOffset();
int length = region.getLength();
if (length < 1)
return;
int anchor = characterPairMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset = (ICharacterPairMatcher.RIGHT == anchor) ? offset + 1 : offset + length - 1;
boolean visible = false;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion = sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible = (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
return;
}
int adjustment = getOffsetAdjustment(document, selection.getOffset() + selection.getLength(), selection.getLength());
targetOffset += adjustment;
int direction = Integer.compare(selection.getLength(), 0);
sourceViewer.setSelectedRange(targetOffset, direction);
sourceViewer.revealRange(targetOffset, direction);
}
// copied from JDT code
private static IRegion getSignedSelection(ISourceViewer sourceViewer) {
Point viewerSelection = sourceViewer.getSelectedRange();
StyledText text = sourceViewer.getTextWidget();
Point selection = text.getSelectionRange();
if (text.getCaretOffset() == selection.x) {
viewerSelection.x = viewerSelection.x + viewerSelection.y;
viewerSelection.y = -viewerSelection.y;
}
return new Region(viewerSelection.x, viewerSelection.y);
}
// copied from JDT code
private static int getOffsetAdjustment(IDocument document, int offset, int length) {
if (length == 0 || Math.abs(length) > 1)
return 0;
try {
if (length < 0) {
if (isOpeningBracket(document.getChar(offset))) {
return 1;
}
} else {
if (isClosingBracket(document.getChar(offset - 1))) {
return -1;
}
}
} catch (BadLocationException e) {
//do nothing
}
return 0;
}
private static boolean isOpeningBracket(char character) {
for (int i = 0; i < BRACKETS.length; i += 2) {
if (character == BRACKETS[i])
return true;
}
return false;
}
private static boolean isClosingBracket(char character) {
for (int i = 1; i < BRACKETS.length; i += 2) {
if (character == BRACKETS[i])
return true;
}
return false;
}
}
| #5222 SQL parser: delimiter detection fix (partition check)
| plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditorBase.java | #5222 SQL parser: delimiter detection fix (partition check) | <ide><path>lugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditorBase.java
<ide> if (currentLine == firstLine) {
<ide> for (String delim : statementDelimiters) {
<ide> final int offset = TextUtils.getOffsetOf(document, firstLine, delim);
<del> if (offset >= 0 && isDefaultPartition(partitioner, offset)) {
<add> if (offset >= 0 ) {
<ide> int delimOffset = document.getLineOffset(firstLine) + offset + delim.length();
<del> if (currentPos > startPos) {
<del> if (docLength > delimOffset) {
<del> boolean hasValuableChars = false;
<del> for (int i = delimOffset; i <= lastPos; i++) {
<del> if (!Character.isWhitespace(document.getChar(i))) {
<del> hasValuableChars = true;
<add> if (isDefaultPartition(partitioner, delimOffset)) {
<add> if (currentPos > startPos) {
<add> if (docLength > delimOffset) {
<add> boolean hasValuableChars = false;
<add> for (int i = delimOffset; i <= lastPos; i++) {
<add> if (!Character.isWhitespace(document.getChar(i))) {
<add> hasValuableChars = true;
<add> break;
<add> }
<add> }
<add> if (hasValuableChars) {
<add> startPos = delimOffset;
<ide> break;
<ide> }
<del> }
<del> if (hasValuableChars) {
<del> startPos = delimOffset;
<del> break;
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | c0b975f8a09801da589cf5ecd72301b2e7631e3a | 0 | opendatakit/androidcommon | /*
* Copyright (C) 2015 University of Washington
*
* 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.opendatakit.views;
import android.content.ContentValues;
import com.fasterxml.jackson.core.type.TypeReference;
import org.opendatakit.aggregate.odktables.rest.ElementDataType;
import org.opendatakit.aggregate.odktables.rest.KeyValueStoreConstants;
import org.opendatakit.database.data.*;
import org.opendatakit.exception.ActionNotAuthorizedException;
import org.opendatakit.exception.ServicesAvailabilityException;
import org.opendatakit.provider.DataTableColumns;
import org.opendatakit.data.utilities.ColumnUtil;
import org.opendatakit.utilities.DataHelper;
import org.opendatakit.utilities.ODKFileUtils;
import org.opendatakit.logging.WebLogger;
import org.opendatakit.database.service.UserDbInterface;
import org.opendatakit.database.service.DbHandle;
import org.opendatakit.database.queries.ResumableQuery;
import org.sqlite.database.sqlite.SQLiteException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
/**
* @author [email protected]
*/
public abstract class ExecutorProcessor implements Runnable {
private static final String TAG = "ExecutorProcessor";
// Changed this to protected so that extended
// ExecutorProcessors can make use of this
protected static final List<String> ADMIN_COLUMNS;
static {
// everything is a STRING except for
// CONFLICT_TYPE which is an INTEGER
// see OdkDatabaseImplUtils.getUserDefinedTableCreationStatement()
ArrayList<String> adminColumns = new ArrayList<String>();
adminColumns.add(DataTableColumns.ID);
adminColumns.add(DataTableColumns.ROW_ETAG);
adminColumns.add(DataTableColumns.SYNC_STATE); // not exportable
adminColumns.add(DataTableColumns.CONFLICT_TYPE); // not exportable
adminColumns.add(DataTableColumns.DEFAULT_ACCESS);
adminColumns.add(DataTableColumns.ROW_OWNER);
adminColumns.add(DataTableColumns.GROUP_READ_ONLY);
adminColumns.add(DataTableColumns.GROUP_MODIFY);
adminColumns.add(DataTableColumns.GROUP_PRIVILEGED);
adminColumns.add(DataTableColumns.FORM_ID);
adminColumns.add(DataTableColumns.LOCALE);
adminColumns.add(DataTableColumns.SAVEPOINT_TYPE);
adminColumns.add(DataTableColumns.SAVEPOINT_TIMESTAMP);
adminColumns.add(DataTableColumns.SAVEPOINT_CREATOR);
Collections.sort(adminColumns);
ADMIN_COLUMNS = Collections.unmodifiableList(adminColumns);
}
private ExecutorContext context;
private ExecutorRequest request;
private UserDbInterface dbInterface;
private String transId;
private DbHandle dbHandle;
protected ExecutorProcessor(ExecutorContext context) {
this.context = context;
}
@Override public void run() {
this.request = context.peekRequest();
if (request == null) {
// no work to do...
return;
}
dbInterface = context.getDatabase();
if (dbInterface == null) {
// no database to do the work...
return;
}
try {
// we have a request and a viable database interface...
dbHandle = dbInterface.openDatabase(context.getAppName());
if (dbHandle == null) {
context.reportError(request.callbackJSON, request.callerID, null,
IllegalStateException.class.getName() + ": Unable to open database connection");
context.popRequest(true);
return;
}
transId = UUID.randomUUID().toString();
context.registerActiveConnection(transId, dbHandle);
switch (request.executorRequestType) {
case UPDATE_EXECUTOR_CONTEXT:
updateExecutorContext();
break;
case GET_ROLES_LIST:
getRolesList();
break;
case GET_DEFAULT_GROUP:
getDefaultGroup();
break;
case GET_USERS_LIST:
getUsersList();
break;
case GET_ALL_TABLE_IDS:
getAllTableIds();
break;
case ARBITRARY_QUERY:
arbitraryQuery();
break;
case USER_TABLE_QUERY:
userTableQuery();
break;
case USER_TABLE_GET_ROWS:
getRows();
break;
case USER_TABLE_GET_MOST_RECENT_ROW:
getMostRecentRow();
break;
case USER_TABLE_UPDATE_ROW:
updateRow();
break;
case USER_TABLE_CHANGE_ACCESS_FILTER_ROW:
changeAccessFilterRow();
break;
case USER_TABLE_DELETE_ROW:
deleteRow();
break;
case USER_TABLE_ADD_ROW:
addRow();
break;
case USER_TABLE_ADD_CHECKPOINT:
addCheckpoint();
break;
case USER_TABLE_SAVE_CHECKPOINT_AS_INCOMPLETE:
saveCheckpointAsIncomplete();
break;
case USER_TABLE_SAVE_CHECKPOINT_AS_COMPLETE:
saveCheckpointAsComplete();
break;
case USER_TABLE_DELETE_ALL_CHECKPOINTS:
deleteAllCheckpoints();
break;
case USER_TABLE_DELETE_LAST_CHECKPOINT:
deleteLastCheckpoint();
break;
default:
reportErrorAndCleanUp(IllegalStateException.class.getName() +
": ExecutorProcessor has not implemented this request type!");
}
} catch (ActionNotAuthorizedException ex) {
reportErrorAndCleanUp(ActionNotAuthorizedException.class.getName() +
": Not Authorized - " + ex.getMessage());
} catch (ServicesAvailabilityException e) {
reportErrorAndCleanUp(ServicesAvailabilityException.class.getName() +
": " + e.getMessage());
} catch (SQLiteException e) {
reportErrorAndCleanUp(SQLiteException.class.getName() +
": " + e.getMessage());
} catch (IllegalStateException e) {
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": " + e.getMessage());
} catch (Throwable t) {
WebLogger.getLogger(context.getAppName()).printStackTrace(t);
reportErrorAndCleanUp(IllegalStateException.class.getName() +
": ExecutorProcessor unexpected exception " + t.toString());
}
}
/**
* Handle the open/close transaction treatment for the database and report an error.
*
* @param errorMessage
*/
private void reportErrorAndCleanUp(String errorMessage) {
try {
if ( dbHandle != null ) {
dbInterface.closeDatabase(context.getAppName(), dbHandle);
}
} catch (Throwable t) {
// ignore this -- favor first reported error
WebLogger.getLogger(context.getAppName()).printStackTrace(t);
WebLogger.getLogger(context.getAppName()).w(TAG, "error while releasing database conneciton");
} finally {
context.removeActiveConnection(transId);
context.reportError(request.callbackJSON, request.callerID, null, errorMessage);
context.popRequest(true);
}
}
/**
* Handle the open/close transaction treatment for the database and report a success.
*
* @param data
* @param metadata
*/
private void reportSuccessAndCleanUp(ArrayList<List<Object>> data, Map<String, Object> metadata) {
boolean successful = false;
String exceptionString = null;
try {
dbInterface.closeDatabase(context.getAppName(), dbHandle);
successful = true;
} catch (ServicesAvailabilityException e) {
exceptionString = e.getClass().getName() +
": error while closing database: " + e.toString();
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
WebLogger.getLogger(context.getAppName()).w(TAG, exceptionString);
} catch (Throwable e) {
String msg = e.getMessage();
if ( msg == null ) {
msg = e.toString();
}
exceptionString = IllegalStateException.class.getName() +
": unexpected exception " + e.getClass().getName() +
" while closing database: " + msg;
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
WebLogger.getLogger(context.getAppName()).w(TAG, exceptionString);
} finally {
context.removeActiveConnection(transId);
if (successful) {
context.reportSuccess(request.callbackJSON, request.callerID, null, data, metadata);
} else {
context.reportError(request.callbackJSON, request.callerID, null, exceptionString);
}
context.popRequest(true);
}
}
/**
* Assumes incoming stringifiedJSON map only contains integers, doubles, strings, booleans
* and arrays or string-value maps.
*
* @param columns
* @param stringifiedJSON
* @return ContentValues object drawn from stringifiedJSON
*/
private ContentValues convertJSON(OrderedColumns columns, String stringifiedJSON) {
ContentValues cvValues = new ContentValues();
if (stringifiedJSON == null) {
return cvValues;
}
try {
HashMap map = ODKFileUtils.mapper.readValue(stringifiedJSON, HashMap.class);
// populate cvValues from the map...
for (Object okey : map.keySet()) {
String key = (String) okey;
// the only 3 metadata fields that the user should update are formId, locale, and creator
// and administrators or super-users can modify the filter type and filter value
if ( !key.equals(DataTableColumns.FORM_ID) &&
!key.equals(DataTableColumns.LOCALE) &&
!key.equals(DataTableColumns.SAVEPOINT_CREATOR) &&
!key.equals(DataTableColumns.DEFAULT_ACCESS) &&
!key.equals(DataTableColumns.ROW_OWNER) &&
!key.equals(DataTableColumns.GROUP_READ_ONLY) &&
!key.equals(DataTableColumns.GROUP_MODIFY) &&
!key.equals(DataTableColumns.GROUP_PRIVILEGED)) {
ColumnDefinition cd = columns.find(key);
if (!cd.isUnitOfRetention()) {
throw new IllegalStateException("key is not a database column name: " + key);
}
}
// the only types are integer/long, float/double, string, boolean
// complex types (array, object) should come across the interface as strings
Object value = map.get(key);
if (value == null) {
cvValues.putNull(key);
} else if (value instanceof Long) {
cvValues.put(key, (Long) value);
} else if (value instanceof Integer) {
cvValues.put(key, (Integer) value);
} else if (value instanceof Float) {
cvValues.put(key, (Float) value);
} else if (value instanceof Double) {
cvValues.put(key, (Double) value);
} else if (value instanceof String) {
cvValues.put(key, (String) value);
} else if (value instanceof Boolean) {
cvValues.put(key, (Boolean) value);
} else {
throw new IllegalStateException("unimplemented case");
}
}
return cvValues;
} catch (IOException e) {
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
throw new IllegalStateException("should never be reached");
}
}
private void updateExecutorContext() {
request.oldContext.releaseResources("switching to new WebFragment");
context.popRequest(false);
}
private void getRolesList() throws ServicesAvailabilityException {
String rolesList = dbInterface.getRolesList(context.getAppName());
reportRolesListSuccessAndCleanUp(rolesList);
}
private void getDefaultGroup() throws ServicesAvailabilityException {
String defaultGroup = dbInterface.getDefaultGroup(context.getAppName());
reportDefaultGroupSuccessAndCleanUp(defaultGroup);
}
private void getUsersList() throws ServicesAvailabilityException {
String usersList = dbInterface.getUsersList(context.getAppName());
reportUsersListSuccessAndCleanUp(usersList);
}
private void getAllTableIds() throws ServicesAvailabilityException {
List<String> tableIds = dbInterface.getAllTableIds(context.getAppName(), dbHandle);
if (tableIds == null) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to obtain list of all tableIds");
} else {
reportListOfTableIdsSuccessAndCleanUp(tableIds);
}
}
private void arbitraryQuery() throws ServicesAvailabilityException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
BaseTable baseTable = dbInterface
.arbitrarySqlQuery(context.getAppName(), dbHandle, request.tableId, request.sqlCommand,
request.sqlBindParams, request.limit, request.offset);
if ( baseTable == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to rawQuery against: " + request.tableId +
" sql: " + request.sqlCommand );
} else {
reportArbitraryQuerySuccessAndCleanUp(columns, baseTable);
}
}
private void populateKeyValueStoreList(Map<String, Object> metadata,
List<KeyValueStoreEntry> entries) throws ServicesAvailabilityException {
// keyValueStoreList
if (entries != null) {
Map<String,String> choiceMap = new HashMap<String,String>();
// It is unclear how to most easily represent the KVS for access.
// We use the convention in ODK Survey, which is a list of maps,
// one per KVS row, with integer, number and boolean resolved to JS
// types. objects and arrays are left unchanged.
List<Map<String, Object>> kvsArray = new ArrayList<Map<String, Object>>();
for (KeyValueStoreEntry entry : entries) {
Object value = null;
try {
ElementDataType type = ElementDataType.valueOf(entry.type);
if (entry.value != null) {
if (type == ElementDataType.integer) {
value = Long.parseLong(entry.value);
} else if (type == ElementDataType.bool) {
// This is broken - a value
// of "TRUE" is returned some times
value = entry.value;
if (value != null) {
try {
value = DataHelper.intToBool(Integer.parseInt(entry.value));
} catch (Exception e) {
WebLogger.getLogger(context.getAppName()).e(TAG,
"ElementDataType: " + entry.type + " could not be converted from int");
try {
value = DataHelper.stringToBool(entry.value);
} catch (Exception e2) {
WebLogger.getLogger(context.getAppName()).e(TAG,
"ElementDataType: " + entry.type + " could not be converted from string");
e2.printStackTrace();
}
}
}
} else if (type == ElementDataType.number) {
value = Double.parseDouble(entry.value);
} else {
// string, array, object, rowpath, configpath and
// anything else -- do not attempt to convert.
// Leave as string.
value = entry.value;
}
}
} catch (IllegalArgumentException e) {
// ignore?
value = entry.value;
WebLogger.getLogger(context.getAppName())
.e(TAG, "Unrecognized ElementDataType: " + entry.type);
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
}
Map<String, Object> anEntry = new HashMap<String, Object>();
anEntry.put("partition", entry.partition);
anEntry.put("aspect", entry.aspect);
anEntry.put("key", entry.key);
anEntry.put("type", entry.type);
anEntry.put("value", value);
kvsArray.add(anEntry);
// and resolve the choice values
// this may explode the size of the KVS going back to the JS layer.
if ( entry.partition.equals(KeyValueStoreConstants.PARTITION_COLUMN) &&
entry.key.equals(KeyValueStoreConstants.COLUMN_DISPLAY_CHOICES_LIST) &&
!choiceMap.containsKey(entry.value)) {
String choiceList = dbInterface.getChoiceList(context.getAppName(), dbHandle, entry.value);
choiceMap.put(entry.value, choiceList);
}
}
metadata.put("keyValueStoreList", kvsArray);
metadata.put("choiceListMap", choiceMap);
}
}
private void reportArbitraryQuerySuccessAndCleanUp(OrderedColumns columnDefinitions,
BaseTable userTable) throws ServicesAvailabilityException {
TableMetaDataEntries metaDataEntries =
dbInterface
.getTableMetadata(context.getAppName(), dbHandle, request.tableId, null, null, null,
null);
TableDefinitionEntry tdef = dbInterface
.getTableDefinitionEntry(context.getAppName(), dbHandle, request.tableId);
HashMap<String, Integer> elementKeyToIndexMap = new HashMap<String, Integer>();
ArrayList<List<Object>> data = new ArrayList<List<Object>>();
if ( userTable != null ) {
int idx;
// resolve the data types of all of the columns in the result set.
Class<?>[] classes = new Class<?>[userTable.getWidth()];
for ( idx = 0 ; idx < userTable.getWidth(); ++idx ) {
// String is the default
classes[idx] = String.class;
// clean up the column name...
String colName = userTable.getElementKey(idx);
// set up the map -- use full column name here
elementKeyToIndexMap.put(colName, idx);
// remove any table alias qualifier from the name (assumes no quoting of column names)
if ( colName.lastIndexOf('.') != -1 ) {
colName = colName.substring(colName.lastIndexOf('.')+1);
}
// and try to deduce what type it should be...
// we keep object and array as String
// integer
if ( colName.equals(DataTableColumns.CONFLICT_TYPE) ) {
classes[idx] = Integer.class;
} else {
try {
ColumnDefinition defn = columnDefinitions.find(colName);
ElementDataType dataType = defn.getType().getDataType();
Class<?> clazz = ColumnUtil.get().getOdkDataIfType(dataType);
classes[idx] = clazz;
} catch ( Exception e ) {
// ignore
}
}
}
// assemble the data array
for (int i = 0; i < userTable.getNumberOfRows(); ++i) {
Row r = userTable.getRowAtIndex(i);
Object[] values = new Object[userTable.getWidth()];
for ( idx = 0 ; idx < userTable.getWidth() ; ++idx ) {
values[idx] = r.getDataType(idx, classes[idx]);
}
data.add(Arrays.asList(values));
}
}
Map<String, Object> metadata = new HashMap<String, Object>();
ResumableQuery q = userTable.getQuery();
if ( q != null ) {
metadata.put("limit", q.getSqlLimit());
metadata.put("offset", q.getSqlOffset());
}
metadata.put("canCreateRow", userTable.getEffectiveAccessCreateRow());
metadata.put("tableId", columnDefinitions.getTableId());
metadata.put("schemaETag", tdef.getSchemaETag());
metadata.put("lastDataETag", tdef.getLastDataETag());
metadata.put("lastSyncTime", tdef.getLastSyncTime());
// elementKey -> index in row within row list
metadata.put("elementKeyMap", elementKeyToIndexMap);
// include metadata only if requested and if the existing metadata version is out-of-date.
if ( request.tableId != null && request.includeFullMetadata &&
(request.metaDataRev == null ||
!request.metaDataRev.equals(metaDataEntries.getRevId())) ) {
Map<String, Object> cachedMetadata = new HashMap<String, Object>();
cachedMetadata.put("metaDataRev", metaDataEntries.getRevId());
// dataTableModel -- JS nested schema struct { elementName : extended_JS_schema_struct, ...}
TreeMap<String, Object> dataTableModel = columnDefinitions.getExtendedDataModel();
cachedMetadata.put("dataTableModel", dataTableModel);
// keyValueStoreList
populateKeyValueStoreList(cachedMetadata, metaDataEntries.getEntries());
metadata.put("cachedMetadata", cachedMetadata);
}
// raw queries are not extended.
reportSuccessAndCleanUp(data, metadata);
}
private void reportRolesListSuccessAndCleanUp(String rolesList) throws
ServicesAvailabilityException {
ArrayList<String> roles = null;
if ( rolesList != null ) {
TypeReference<ArrayList<String>> type = new TypeReference<ArrayList<String>>() {};
try {
roles = ODKFileUtils.mapper.readValue(rolesList, type);
} catch (IOException e) {
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
}
}
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("roles", roles);
reportSuccessAndCleanUp(null, metadata);
}
private void reportDefaultGroupSuccessAndCleanUp(String defaultGroup) throws
ServicesAvailabilityException {
Map<String, Object> metadata = new HashMap<String, Object>();
if ( defaultGroup != null && defaultGroup.length() != 0 ) {
metadata.put("defaultGroup", defaultGroup);
}
reportSuccessAndCleanUp(null, metadata);
}
private void reportUsersListSuccessAndCleanUp(String usersList) throws
ServicesAvailabilityException {
ArrayList<HashMap<String,Object>> users = null;
if ( usersList != null ) {
TypeReference<ArrayList<HashMap<String,Object>>> type = new
TypeReference<ArrayList<HashMap<String,Object>>>() {};
try {
users = ODKFileUtils.mapper.readValue(usersList, type);
} catch (IOException e) {
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
}
}
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("users", users);
reportSuccessAndCleanUp(null, metadata);
}
private void reportListOfTableIdsSuccessAndCleanUp(List<String> tableIds) throws ServicesAvailabilityException {
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("tableIds", tableIds);
// raw queries are not extended.
reportSuccessAndCleanUp(null, metadata);
}
private void userTableQuery() throws ServicesAvailabilityException {
String[] emptyArray = {};
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.simpleQuery(context.getAppName(), dbHandle, request.tableId, columns, request.whereClause,
request.sqlBindParams, request.groupBy, request.having,
(request.orderByElementKey == null) ?
emptyArray :
new String[] { request.orderByElementKey }, (request.orderByDirection == null) ?
emptyArray :
new String[] { request.orderByDirection }, request.limit, request.offset);
if (t == null) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to query " + request.tableId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void reportSuccessAndCleanUp(UserTable userTable) throws ServicesAvailabilityException {
TableMetaDataEntries metaDataEntries =
dbInterface
.getTableMetadata(context.getAppName(), dbHandle, request.tableId, null, null, null,
null);
TableDefinitionEntry tdef = dbInterface
.getTableDefinitionEntry(context.getAppName(), dbHandle, request.tableId);
// assemble the data and metadata objects
ArrayList<List<Object>> data = new ArrayList<List<Object>>();
Map<String, Integer> elementKeyToIndexMap = userTable.getElementKeyToIndex();
Integer idxEffectiveAccessColumn =
elementKeyToIndexMap.get(DataTableColumns.EFFECTIVE_ACCESS);
OrderedColumns columnDefinitions = userTable.getColumnDefinitions();
for (int i = 0; i < userTable.getNumberOfRows(); ++i) {
Row r = userTable.getRowAtIndex(i);
Object[] typedValues = new Object[elementKeyToIndexMap.size()];
List<Object> typedValuesAsList = Arrays.asList(typedValues);
data.add(typedValuesAsList);
for (String name : ADMIN_COLUMNS) {
int idx = elementKeyToIndexMap.get(name);
if (name.equals(DataTableColumns.CONFLICT_TYPE)) {
Integer value = r.getDataType(name, Integer.class);
typedValues[idx] = value;
} else {
String value = r.getDataType(name, String.class);
typedValues[idx] = value;
}
}
ArrayList<String> elementKeys = columnDefinitions.getRetentionColumnNames();
for (String name : elementKeys) {
int idx = elementKeyToIndexMap.get(name);
ColumnDefinition defn = columnDefinitions.find(name);
ElementDataType dataType = defn.getType().getDataType();
Class<?> clazz = ColumnUtil.get().getOdkDataIfType(dataType);
Object value = r.getDataType(name, clazz);
typedValues[idx] = value;
}
if ( idxEffectiveAccessColumn != null ) {
typedValues[idxEffectiveAccessColumn] =
r.getDataType(DataTableColumns.EFFECTIVE_ACCESS, String.class);
}
}
Map<String, Object> metadata = new HashMap<String, Object>();
ResumableQuery q = userTable.getQuery();
if ( q != null ) {
metadata.put("limit", q.getSqlLimit());
metadata.put("offset", q.getSqlOffset());
}
metadata.put("canCreateRow", userTable.getEffectiveAccessCreateRow());
metadata.put("tableId", userTable.getTableId());
metadata.put("schemaETag", tdef.getSchemaETag());
metadata.put("lastDataETag", tdef.getLastDataETag());
metadata.put("lastSyncTime", tdef.getLastSyncTime());
// elementKey -> index in row within row list
metadata.put("elementKeyMap", elementKeyToIndexMap);
// include metadata only if requested and if the existing metadata version is out-of-date.
if ( request.tableId != null && request.includeFullMetadata &&
(request.metaDataRev == null ||
!request.metaDataRev.equals(metaDataEntries.getRevId())) ) {
Map<String, Object> cachedMetadata = new HashMap<String, Object>();
cachedMetadata.put("metaDataRev", metaDataEntries.getRevId());
// dataTableModel -- JS nested schema struct { elementName : extended_JS_schema_struct, ...}
TreeMap<String, Object> dataTableModel = columnDefinitions.getExtendedDataModel();
cachedMetadata.put("dataTableModel", dataTableModel);
// keyValueStoreList
populateKeyValueStoreList(cachedMetadata, metaDataEntries.getEntries());
metadata.put("cachedMetadata", cachedMetadata);
}
// Always include tool-specific metadata if we are including metadata.
// The tool-specific metadata, such as cell, row, status and column colors
// varies with the content of the individual rows and therefore must always
// be returned.
if ( request.includeFullMetadata ) {
// extend the metadata with whatever else this app needs....
// e.g., row and column color maps
extendQueryMetadata(dbInterface, dbHandle, metaDataEntries.getEntries(), userTable, metadata);
}
reportSuccessAndCleanUp(data, metadata);
}
protected abstract void extendQueryMetadata(UserDbInterface dbInterface, DbHandle dbHandle,
List<KeyValueStoreEntry> entries, UserTable userTable, Map<String, Object> metadata);
private void getRows() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.getRowsWithId(context.getAppName(), dbHandle, request.tableId, columns, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to getRows for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void getMostRecentRow() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.getMostRecentRowWithId(context.getAppName(), dbHandle, request.tableId, columns,
request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to getMostRecentRow for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void updateRow() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
UserTable t = dbInterface
.updateRowWithId(context.getAppName(), dbHandle, request.tableId, columns, cvValues,
request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to updateRow for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void changeAccessFilterRow() throws ServicesAvailabilityException,
ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
String defaultAccess = cvValues.getAsString(DataTableColumns.DEFAULT_ACCESS);
String owner = cvValues.getAsString(DataTableColumns.ROW_OWNER);
String groupReadOnly = cvValues.getAsString(DataTableColumns.GROUP_READ_ONLY);
String groupModify = cvValues.getAsString(DataTableColumns.GROUP_MODIFY);
String groupPrivileged = cvValues.getAsString(DataTableColumns.GROUP_PRIVILEGED);
UserTable t = dbInterface
.changeRowFilterWithId(context.getAppName(), dbHandle, request.tableId,
columns, defaultAccess, owner, groupReadOnly, groupModify, groupPrivileged, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to changeAccessFilterRow for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void deleteRow() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.deleteRowWithId(context.getAppName(), dbHandle, request.tableId, columns, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to deleteRow for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void addRow() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
UserTable t = dbInterface
.insertRowWithId(context.getAppName(), dbHandle, request.tableId, columns, cvValues,
request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to addRow for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void addCheckpoint() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if ( request.tableId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if ( request.rowId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if ( columns == null ) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
UserTable t = dbInterface
.insertCheckpointRowWithId(context.getAppName(), dbHandle, request.tableId, columns,
cvValues, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to addCheckpoint for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void saveCheckpointAsIncomplete() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
if ( request.stringifiedJSON != null ) {
ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
if (!cvValues.keySet().isEmpty()) {
dbInterface
.insertCheckpointRowWithId(context.getAppName(), dbHandle, request.tableId, columns,
cvValues, request.rowId);
}
}
UserTable t = dbInterface
.saveAsIncompleteMostRecentCheckpointRowWithId(context.getAppName(), dbHandle,
request.tableId, columns, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to saveCheckpointAsIncomplete for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void saveCheckpointAsComplete() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
if ( request.stringifiedJSON != null ) {
ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
if (!cvValues.keySet().isEmpty()) {
dbInterface
.insertCheckpointRowWithId(context.getAppName(), dbHandle, request.tableId, columns,
cvValues, request.rowId);
}
}
UserTable t = dbInterface
.saveAsCompleteMostRecentCheckpointRowWithId(context.getAppName(), dbHandle,
request.tableId, columns, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to saveCheckpointAsComplete for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void deleteLastCheckpoint() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if ( request.tableId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if ( request.rowId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.deleteLastCheckpointRowWithId(context.getAppName(), dbHandle, request.tableId, columns,
request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to deleteLastCheckpoint for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void deleteAllCheckpoints() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if ( request.tableId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if ( request.rowId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
//ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
UserTable t = dbInterface
.deleteAllCheckpointRowsWithId(context.getAppName(), dbHandle, request.tableId, columns,
request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to deleteAllCheckpoints for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
}
| androidcommon_lib/src/main/java/org/opendatakit/views/ExecutorProcessor.java | /*
* Copyright (C) 2015 University of Washington
*
* 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.opendatakit.views;
import android.content.ContentValues;
import com.fasterxml.jackson.core.type.TypeReference;
import org.opendatakit.aggregate.odktables.rest.ElementDataType;
import org.opendatakit.aggregate.odktables.rest.KeyValueStoreConstants;
import org.opendatakit.database.data.*;
import org.opendatakit.exception.ActionNotAuthorizedException;
import org.opendatakit.exception.ServicesAvailabilityException;
import org.opendatakit.provider.DataTableColumns;
import org.opendatakit.data.utilities.ColumnUtil;
import org.opendatakit.utilities.DataHelper;
import org.opendatakit.utilities.ODKFileUtils;
import org.opendatakit.logging.WebLogger;
import org.opendatakit.database.service.UserDbInterface;
import org.opendatakit.database.service.DbHandle;
import org.opendatakit.database.queries.ResumableQuery;
import org.sqlite.database.sqlite.SQLiteException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
/**
* @author [email protected]
*/
public abstract class ExecutorProcessor implements Runnable {
private static final String TAG = "ExecutorProcessor";
// Changed this to protected so that extended
// ExecutorProcessors can make use of this
protected static final List<String> ADMIN_COLUMNS;
static {
// everything is a STRING except for
// CONFLICT_TYPE which is an INTEGER
// see OdkDatabaseImplUtils.getUserDefinedTableCreationStatement()
ArrayList<String> adminColumns = new ArrayList<String>();
adminColumns.add(DataTableColumns.ID);
adminColumns.add(DataTableColumns.ROW_ETAG);
adminColumns.add(DataTableColumns.SYNC_STATE); // not exportable
adminColumns.add(DataTableColumns.CONFLICT_TYPE); // not exportable
adminColumns.add(DataTableColumns.DEFAULT_ACCESS);
adminColumns.add(DataTableColumns.ROW_OWNER);
adminColumns.add(DataTableColumns.GROUP_READ_ONLY);
adminColumns.add(DataTableColumns.GROUP_MODIFY);
adminColumns.add(DataTableColumns.GROUP_PRIVILEGED);
adminColumns.add(DataTableColumns.FORM_ID);
adminColumns.add(DataTableColumns.LOCALE);
adminColumns.add(DataTableColumns.SAVEPOINT_TYPE);
adminColumns.add(DataTableColumns.SAVEPOINT_TIMESTAMP);
adminColumns.add(DataTableColumns.SAVEPOINT_CREATOR);
Collections.sort(adminColumns);
ADMIN_COLUMNS = Collections.unmodifiableList(adminColumns);
}
private ExecutorContext context;
private ExecutorRequest request;
private UserDbInterface dbInterface;
private String transId;
private DbHandle dbHandle;
protected ExecutorProcessor(ExecutorContext context) {
this.context = context;
}
@Override public void run() {
this.request = context.peekRequest();
if (request == null) {
// no work to do...
return;
}
dbInterface = context.getDatabase();
if (dbInterface == null) {
// no database to do the work...
return;
}
try {
// we have a request and a viable database interface...
dbHandle = dbInterface.openDatabase(context.getAppName());
if (dbHandle == null) {
context.reportError(request.callbackJSON, request.callerID, null,
IllegalStateException.class.getName() + ": Unable to open database connection");
context.popRequest(true);
return;
}
transId = UUID.randomUUID().toString();
context.registerActiveConnection(transId, dbHandle);
switch (request.executorRequestType) {
case UPDATE_EXECUTOR_CONTEXT:
updateExecutorContext();
break;
case GET_ROLES_LIST:
getRolesList();
break;
case GET_DEFAULT_GROUP:
getDefaultGroup();
break;
case GET_USERS_LIST:
getUsersList();
break;
case GET_ALL_TABLE_IDS:
getAllTableIds();
break;
case ARBITRARY_QUERY:
arbitraryQuery();
break;
case USER_TABLE_QUERY:
userTableQuery();
break;
case USER_TABLE_GET_ROWS:
getRows();
break;
case USER_TABLE_GET_MOST_RECENT_ROW:
getMostRecentRow();
break;
case USER_TABLE_UPDATE_ROW:
updateRow();
break;
case USER_TABLE_CHANGE_ACCESS_FILTER_ROW:
changeAccessFilterRow();
break;
case USER_TABLE_DELETE_ROW:
deleteRow();
break;
case USER_TABLE_ADD_ROW:
addRow();
break;
case USER_TABLE_ADD_CHECKPOINT:
addCheckpoint();
break;
case USER_TABLE_SAVE_CHECKPOINT_AS_INCOMPLETE:
saveCheckpointAsIncomplete();
break;
case USER_TABLE_SAVE_CHECKPOINT_AS_COMPLETE:
saveCheckpointAsComplete();
break;
case USER_TABLE_DELETE_ALL_CHECKPOINTS:
deleteAllCheckpoints();
break;
case USER_TABLE_DELETE_LAST_CHECKPOINT:
deleteLastCheckpoint();
break;
default:
reportErrorAndCleanUp(IllegalStateException.class.getName() +
": ExecutorProcessor has not implemented this request type!");
}
} catch (ActionNotAuthorizedException ex) {
reportErrorAndCleanUp(ActionNotAuthorizedException.class.getName() +
": Not Authorized - " + ex.getMessage());
} catch (ServicesAvailabilityException e) {
reportErrorAndCleanUp(ServicesAvailabilityException.class.getName() +
": " + e.getMessage());
} catch (SQLiteException e) {
reportErrorAndCleanUp(SQLiteException.class.getName() +
": " + e.getMessage());
} catch (IllegalStateException e) {
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": " + e.getMessage());
} catch (Throwable t) {
WebLogger.getLogger(context.getAppName()).printStackTrace(t);
reportErrorAndCleanUp(IllegalStateException.class.getName() +
": ExecutorProcessor unexpected exception " + t.toString());
}
}
/**
* Handle the open/close transaction treatment for the database and report an error.
*
* @param errorMessage
*/
private void reportErrorAndCleanUp(String errorMessage) {
try {
if ( dbHandle != null ) {
dbInterface.closeDatabase(context.getAppName(), dbHandle);
}
} catch (Throwable t) {
// ignore this -- favor first reported error
WebLogger.getLogger(context.getAppName()).printStackTrace(t);
WebLogger.getLogger(context.getAppName()).w(TAG, "error while releasing database conneciton");
} finally {
context.removeActiveConnection(transId);
context.reportError(request.callbackJSON, request.callerID, null, errorMessage);
context.popRequest(true);
}
}
/**
* Handle the open/close transaction treatment for the database and report a success.
*
* @param data
* @param metadata
*/
private void reportSuccessAndCleanUp(ArrayList<List<Object>> data, Map<String, Object> metadata) {
boolean successful = false;
String exceptionString = null;
try {
dbInterface.closeDatabase(context.getAppName(), dbHandle);
successful = true;
} catch (ServicesAvailabilityException e) {
exceptionString = e.getClass().getName() +
": error while closing database: " + e.toString();
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
WebLogger.getLogger(context.getAppName()).w(TAG, exceptionString);
} catch (Throwable e) {
String msg = e.getMessage();
if ( msg == null ) {
msg = e.toString();
}
exceptionString = IllegalStateException.class.getName() +
": unexpected exception " + e.getClass().getName() +
" while closing database: " + msg;
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
WebLogger.getLogger(context.getAppName()).w(TAG, exceptionString);
} finally {
context.removeActiveConnection(transId);
if (successful) {
context.reportSuccess(request.callbackJSON, request.callerID, null, data, metadata);
} else {
context.reportError(request.callbackJSON, request.callerID, null, exceptionString);
}
context.popRequest(true);
}
}
/**
* Assumes incoming stringifiedJSON map only contains integers, doubles, strings, booleans
* and arrays or string-value maps.
*
* @param columns
* @param stringifiedJSON
* @return ContentValues object drawn from stringifiedJSON
*/
private ContentValues convertJSON(OrderedColumns columns, String stringifiedJSON) {
ContentValues cvValues = new ContentValues();
if (stringifiedJSON == null) {
return cvValues;
}
try {
HashMap map = ODKFileUtils.mapper.readValue(stringifiedJSON, HashMap.class);
// populate cvValues from the map...
for (Object okey : map.keySet()) {
String key = (String) okey;
// the only 3 metadata fields that the user should update are formId, locale, and creator
// and administrators or super-users can modify the filter type and filter value
if ( !key.equals(DataTableColumns.FORM_ID) &&
!key.equals(DataTableColumns.LOCALE) &&
!key.equals(DataTableColumns.SAVEPOINT_CREATOR) &&
!key.equals(DataTableColumns.DEFAULT_ACCESS) &&
!key.equals(DataTableColumns.ROW_OWNER) &&
!key.equals(DataTableColumns.GROUP_READ_ONLY) &&
!key.equals(DataTableColumns.GROUP_MODIFY) &&
!key.equals(DataTableColumns.GROUP_PRIVILEGED)) {
ColumnDefinition cd = columns.find(key);
if (!cd.isUnitOfRetention()) {
throw new IllegalStateException("key is not a database column name: " + key);
}
}
// the only types are integer/long, float/double, string, boolean
// complex types (array, object) should come across the interface as strings
Object value = map.get(key);
if (value == null) {
cvValues.putNull(key);
} else if (value instanceof Long) {
cvValues.put(key, (Long) value);
} else if (value instanceof Integer) {
cvValues.put(key, (Integer) value);
} else if (value instanceof Float) {
cvValues.put(key, (Float) value);
} else if (value instanceof Double) {
cvValues.put(key, (Double) value);
} else if (value instanceof String) {
cvValues.put(key, (String) value);
} else if (value instanceof Boolean) {
cvValues.put(key, (Boolean) value);
} else {
throw new IllegalStateException("unimplemented case");
}
}
return cvValues;
} catch (IOException e) {
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
throw new IllegalStateException("should never be reached");
}
}
private void updateExecutorContext() {
request.oldContext.releaseResources("switching to new WebFragment");
context.popRequest(false);
}
private void getRolesList() throws ServicesAvailabilityException {
String rolesList = dbInterface.getRolesList(context.getAppName());
reportRolesListSuccessAndCleanUp(rolesList);
}
private void getDefaultGroup() throws ServicesAvailabilityException {
String defaultGroup = dbInterface.getDefaultGroup(context.getAppName());
reportDefaultGroupSuccessAndCleanUp(defaultGroup);
}
private void getUsersList() throws ServicesAvailabilityException {
String usersList = dbInterface.getUsersList(context.getAppName());
reportUsersListSuccessAndCleanUp(usersList);
}
private void getAllTableIds() throws ServicesAvailabilityException {
List<String> tableIds = dbInterface.getAllTableIds(context.getAppName(), dbHandle);
if (tableIds == null) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to obtain list of all tableIds");
} else {
reportListOfTableIdsSuccessAndCleanUp(tableIds);
}
}
private void arbitraryQuery() throws ServicesAvailabilityException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
BaseTable baseTable = dbInterface
.arbitrarySqlQuery(context.getAppName(), dbHandle, request.tableId, request.sqlCommand,
request.sqlBindParams, request.limit, request.offset);
if ( baseTable == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to rawQuery against: " + request.tableId +
" sql: " + request.sqlCommand );
} else {
reportArbitraryQuerySuccessAndCleanUp(columns, baseTable);
}
}
private void populateKeyValueStoreList(Map<String, Object> metadata,
List<KeyValueStoreEntry> entries) throws ServicesAvailabilityException {
// keyValueStoreList
if (entries != null) {
Map<String,String> choiceMap = new HashMap<String,String>();
// It is unclear how to most easily represent the KVS for access.
// We use the convention in ODK Survey, which is a list of maps,
// one per KVS row, with integer, number and boolean resolved to JS
// types. objects and arrays are left unchanged.
List<Map<String, Object>> kvsArray = new ArrayList<Map<String, Object>>();
for (KeyValueStoreEntry entry : entries) {
Object value = null;
try {
ElementDataType type = ElementDataType.valueOf(entry.type);
if (entry.value != null) {
if (type == ElementDataType.integer) {
value = Long.parseLong(entry.value);
} else if (type == ElementDataType.bool) {
// This is broken - a value
// of "TRUE" is returned some times
value = entry.value;
if (value != null) {
try {
value = DataHelper.intToBool(Integer.parseInt(entry.value));
} catch (Exception e) {
WebLogger.getLogger(context.getAppName()).e(TAG,
"ElementDataType: " + entry.type + " could not be converted from int");
try {
value = DataHelper.stringToBool(entry.value);
} catch (Exception e2) {
WebLogger.getLogger(context.getAppName()).e(TAG,
"ElementDataType: " + entry.type + " could not be converted from string");
e2.printStackTrace();
}
}
}
} else if (type == ElementDataType.number) {
value = Double.parseDouble(entry.value);
} else {
// string, array, object, rowpath, configpath and
// anything else -- do not attempt to convert.
// Leave as string.
value = entry.value;
}
}
} catch (IllegalArgumentException e) {
// ignore?
value = entry.value;
WebLogger.getLogger(context.getAppName())
.e(TAG, "Unrecognized ElementDataType: " + entry.type);
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
}
Map<String, Object> anEntry = new HashMap<String, Object>();
anEntry.put("partition", entry.partition);
anEntry.put("aspect", entry.aspect);
anEntry.put("key", entry.key);
anEntry.put("type", entry.type);
anEntry.put("value", value);
kvsArray.add(anEntry);
// and resolve the choice values
// this may explode the size of the KVS going back to the JS layer.
if ( entry.partition.equals(KeyValueStoreConstants.PARTITION_COLUMN) &&
entry.key.equals(KeyValueStoreConstants.COLUMN_DISPLAY_CHOICES_LIST) &&
!choiceMap.containsKey(entry.value)) {
String choiceList = dbInterface.getChoiceList(context.getAppName(), dbHandle, entry.value);
choiceMap.put(entry.value, choiceList);
}
}
metadata.put("keyValueStoreList", kvsArray);
metadata.put("choiceListMap", choiceMap);
}
}
private void reportArbitraryQuerySuccessAndCleanUp(OrderedColumns columnDefinitions,
BaseTable userTable) throws ServicesAvailabilityException {
TableMetaDataEntries metaDataEntries =
dbInterface
.getTableMetadata(context.getAppName(), dbHandle, request.tableId, null, null, null,
null);
TableDefinitionEntry tdef = dbInterface
.getTableDefinitionEntry(context.getAppName(), dbHandle, request.tableId);
HashMap<String, Integer> elementKeyToIndexMap = new HashMap<String, Integer>();
ArrayList<List<Object>> data = new ArrayList<List<Object>>();
if ( userTable != null ) {
int idx;
// resolve the data types of all of the columns in the result set.
Class<?>[] classes = new Class<?>[userTable.getWidth()];
for ( idx = 0 ; idx < userTable.getWidth(); ++idx ) {
// String is the default
classes[idx] = String.class;
// clean up the column name...
String colName = userTable.getElementKey(idx);
// set up the map -- use full column name here
elementKeyToIndexMap.put(colName, idx);
// remove any table alias qualifier from the name (assumes no quoting of column names)
if ( colName.lastIndexOf('.') != -1 ) {
colName = colName.substring(colName.lastIndexOf('.')+1);
}
// and try to deduce what type it should be...
// we keep object and array as String
// integer
if ( colName.equals(DataTableColumns.CONFLICT_TYPE) ) {
classes[idx] = Integer.class;
} else {
try {
ColumnDefinition defn = columnDefinitions.find(colName);
ElementDataType dataType = defn.getType().getDataType();
Class<?> clazz = ColumnUtil.get().getOdkDataIfType(dataType);
classes[idx] = clazz;
} catch ( Exception e ) {
// ignore
}
}
}
// assemble the data array
for (int i = 0; i < userTable.getNumberOfRows(); ++i) {
Row r = userTable.getRowAtIndex(i);
Object[] values = new Object[userTable.getWidth()];
for ( idx = 0 ; idx < userTable.getWidth() ; ++idx ) {
values[idx] = r.getDataType(idx, classes[idx]);
}
data.add(Arrays.asList(values));
}
}
Map<String, Object> metadata = new HashMap<String, Object>();
ResumableQuery q = userTable.getQuery();
if ( q != null ) {
metadata.put("limit", q.getSqlLimit());
metadata.put("offset", q.getSqlOffset());
}
metadata.put("canCreateRow", userTable.getEffectiveAccessCreateRow());
metadata.put("tableId", columnDefinitions.getTableId());
metadata.put("schemaETag", tdef.getSchemaETag());
metadata.put("lastDataETag", tdef.getLastDataETag());
metadata.put("lastSyncTime", tdef.getLastSyncTime());
// elementKey -> index in row within row list
metadata.put("elementKeyMap", elementKeyToIndexMap);
// include metadata only if requested and if the existing metadata version is out-of-date.
if ( request.tableId != null && request.includeFullMetadata &&
(request.metaDataRev == null ||
!request.metaDataRev.equals(metaDataEntries.getRevId())) ) {
Map<String, Object> cachedMetadata = new HashMap<String, Object>();
cachedMetadata.put("metaDataRev", metaDataEntries.getRevId());
// dataTableModel -- JS nested schema struct { elementName : extended_JS_schema_struct, ...}
TreeMap<String, Object> dataTableModel = columnDefinitions.getExtendedDataModel();
cachedMetadata.put("dataTableModel", dataTableModel);
// keyValueStoreList
populateKeyValueStoreList(cachedMetadata, metaDataEntries.getEntries());
metadata.put("cachedMetadata", cachedMetadata);
}
// raw queries are not extended.
reportSuccessAndCleanUp(data, metadata);
}
private void reportRolesListSuccessAndCleanUp(String rolesList) throws
ServicesAvailabilityException {
ArrayList<String> roles = null;
if ( rolesList != null ) {
TypeReference<ArrayList<String>> type = new TypeReference<ArrayList<String>>() {};
try {
roles = ODKFileUtils.mapper.readValue(rolesList, type);
} catch (IOException e) {
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
}
}
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("roles", roles);
reportSuccessAndCleanUp(null, metadata);
}
private void reportDefaultGroupSuccessAndCleanUp(String defaultGroup) throws
ServicesAvailabilityException {
Map<String, Object> metadata = new HashMap<String, Object>();
if ( defaultGroup != null && defaultGroup.length() != 0 ) {
metadata.put("defaultGroup", defaultGroup);
}
reportSuccessAndCleanUp(null, metadata);
}
private void reportUsersListSuccessAndCleanUp(String usersList) throws
ServicesAvailabilityException {
ArrayList<HashMap<String,Object>> users = null;
if ( usersList != null ) {
TypeReference<ArrayList<HashMap<String,Object>>> type = new
TypeReference<ArrayList<HashMap<String,Object>>>() {};
try {
users = ODKFileUtils.mapper.readValue(usersList, type);
} catch (IOException e) {
WebLogger.getLogger(context.getAppName()).printStackTrace(e);
}
}
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("users", users);
reportSuccessAndCleanUp(null, metadata);
}
private void reportListOfTableIdsSuccessAndCleanUp(List<String> tableIds) throws ServicesAvailabilityException {
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("tableIds", tableIds);
// raw queries are not extended.
reportSuccessAndCleanUp(null, metadata);
}
private void userTableQuery() throws ServicesAvailabilityException {
String[] emptyArray = {};
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.simpleQuery(context.getAppName(), dbHandle, request.tableId, columns, request.whereClause,
request.sqlBindParams, request.groupBy, request.having,
(request.orderByElementKey == null) ?
emptyArray :
new String[] { request.orderByElementKey }, (request.orderByDirection == null) ?
emptyArray :
new String[] { request.orderByDirection }, request.limit, request.offset);
if (t == null) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to query " + request.tableId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void reportSuccessAndCleanUp(UserTable userTable) throws ServicesAvailabilityException {
TableMetaDataEntries metaDataEntries =
dbInterface
.getTableMetadata(context.getAppName(), dbHandle, request.tableId, null, null, null,
null);
TableDefinitionEntry tdef = dbInterface
.getTableDefinitionEntry(context.getAppName(), dbHandle, request.tableId);
// assemble the data and metadata objects
ArrayList<List<Object>> data = new ArrayList<List<Object>>();
Map<String, Integer> elementKeyToIndexMap = userTable.getElementKeyToIndex();
Integer idxEffectiveAccessColumn =
elementKeyToIndexMap.get(DataTableColumns.EFFECTIVE_ACCESS);
OrderedColumns columnDefinitions = userTable.getColumnDefinitions();
for (int i = 0; i < userTable.getNumberOfRows(); ++i) {
Row r = userTable.getRowAtIndex(i);
Object[] typedValues = new Object[elementKeyToIndexMap.size()];
List<Object> typedValuesAsList = Arrays.asList(typedValues);
data.add(typedValuesAsList);
for (String name : ADMIN_COLUMNS) {
int idx = elementKeyToIndexMap.get(name);
if (name.equals(DataTableColumns.CONFLICT_TYPE)) {
Integer value = r.getDataType(name, Integer.class);
typedValues[idx] = value;
} else {
String value = r.getDataType(name, String.class);
typedValues[idx] = value;
}
}
ArrayList<String> elementKeys = columnDefinitions.getRetentionColumnNames();
for (String name : elementKeys) {
int idx = elementKeyToIndexMap.get(name);
ColumnDefinition defn = columnDefinitions.find(name);
ElementDataType dataType = defn.getType().getDataType();
Class<?> clazz = ColumnUtil.get().getOdkDataIfType(dataType);
Object value = r.getDataType(name, clazz);
typedValues[idx] = value;
}
if ( idxEffectiveAccessColumn != null ) {
typedValues[idxEffectiveAccessColumn] =
r.getDataType(DataTableColumns.EFFECTIVE_ACCESS, String.class);
}
}
Map<String, Object> metadata = new HashMap<String, Object>();
ResumableQuery q = userTable.getQuery();
if ( q != null ) {
metadata.put("limit", q.getSqlLimit());
metadata.put("offset", q.getSqlOffset());
}
metadata.put("canCreateRow", userTable.getEffectiveAccessCreateRow());
metadata.put("tableId", userTable.getTableId());
metadata.put("schemaETag", tdef.getSchemaETag());
metadata.put("lastDataETag", tdef.getLastDataETag());
metadata.put("lastSyncTime", tdef.getLastSyncTime());
// elementKey -> index in row within row list
metadata.put("elementKeyMap", elementKeyToIndexMap);
// include metadata only if requested and if the existing metadata version is out-of-date.
if ( request.tableId != null && request.includeFullMetadata &&
(request.metaDataRev == null ||
!request.metaDataRev.equals(metaDataEntries.getRevId())) ) {
Map<String, Object> cachedMetadata = new HashMap<String, Object>();
cachedMetadata.put("metaDataRev", metaDataEntries.getRevId());
// dataTableModel -- JS nested schema struct { elementName : extended_JS_schema_struct, ...}
TreeMap<String, Object> dataTableModel = columnDefinitions.getExtendedDataModel();
cachedMetadata.put("dataTableModel", dataTableModel);
// keyValueStoreList
populateKeyValueStoreList(cachedMetadata, metaDataEntries.getEntries());
metadata.put("cachedMetadata", cachedMetadata);
}
// Always include tool-specific metadata if we are including metadata.
// The tool-specific metadata, such as cell, row, status and column colors
// varies with the content of the individual rows and therefore must always
// be returned.
if ( request.includeFullMetadata ) {
// extend the metadata with whatever else this app needs....
// e.g., row and column color maps
extendQueryMetadata(dbInterface, dbHandle, metaDataEntries.getEntries(), userTable, metadata);
}
reportSuccessAndCleanUp(data, metadata);
}
protected abstract void extendQueryMetadata(UserDbInterface dbInterface, DbHandle dbHandle,
List<KeyValueStoreEntry> entries, UserTable userTable, Map<String, Object> metadata);
private void getRows() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.getRowsWithId(context.getAppName(), dbHandle, request.tableId, columns, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to getRows for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void getMostRecentRow() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.getMostRecentRowWithId(context.getAppName(), dbHandle, request.tableId, columns,
request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to getMostRecentRow for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void updateRow() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
UserTable t = dbInterface
.updateRowWithId(context.getAppName(), dbHandle, request.tableId, columns, cvValues,
request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to updateRow for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void changeAccessFilterRow() throws ServicesAvailabilityException,
ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
String defaultAccess = cvValues.getAsString(DataTableColumns.DEFAULT_ACCESS);
String owner = cvValues.getAsString(DataTableColumns.ROW_OWNER);
String groupReadOnly = cvValues.getAsString(DataTableColumns.GROUP_READ_ONLY);
String groupModify = cvValues.getAsString(DataTableColumns.GROUP_MODIFY);
String groupPrivileged = cvValues.getAsString(DataTableColumns.GROUP_PRIVILEGED);
UserTable t = dbInterface
.changeRowFilterWithId(context.getAppName(), dbHandle, request.tableId,
columns, defaultAccess, owner, groupReadOnly, groupModify, groupPrivileged, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to changeAccessFilterRow for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void deleteRow() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.deleteRowWithId(context.getAppName(), dbHandle, request.tableId, columns, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to deleteRow for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void addRow() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
UserTable t = dbInterface
.insertRowWithId(context.getAppName(), dbHandle, request.tableId, columns, cvValues,
request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to addRow for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void addCheckpoint() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if ( request.tableId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if ( request.rowId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if ( columns == null ) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
UserTable t = dbInterface
.insertCheckpointRowWithId(context.getAppName(), dbHandle, request.tableId, columns,
cvValues, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to addCheckpoint for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void saveCheckpointAsIncomplete() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.saveAsIncompleteMostRecentCheckpointRowWithId(context.getAppName(), dbHandle,
request.tableId, columns, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to saveCheckpointAsIncomplete for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void saveCheckpointAsComplete() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if (request.tableId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if (request.rowId == null) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.saveAsCompleteMostRecentCheckpointRowWithId(context.getAppName(), dbHandle,
request.tableId, columns, request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to saveCheckpointAsComplete for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void deleteLastCheckpoint() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if ( request.tableId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if ( request.rowId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
UserTable t = dbInterface
.deleteLastCheckpointRowWithId(context.getAppName(), dbHandle, request.tableId, columns,
request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to deleteLastCheckpoint for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
private void deleteAllCheckpoints() throws ServicesAvailabilityException, ActionNotAuthorizedException {
if ( request.tableId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": tableId cannot be null");
return;
}
if ( request.rowId == null ) {
reportErrorAndCleanUp(IllegalArgumentException.class.getName() + ": rowId cannot be null");
return;
}
OrderedColumns columns = context.getOrderedColumns(request.tableId);
if (columns == null) {
columns = dbInterface.getUserDefinedColumns(context.getAppName(), dbHandle, request.tableId);
context.putOrderedColumns(request.tableId, columns);
}
//ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
UserTable t = dbInterface
.deleteAllCheckpointRowsWithId(context.getAppName(), dbHandle, request.tableId, columns,
request.rowId);
if ( t == null ) {
reportErrorAndCleanUp(IllegalStateException.class.getName() + ": Unable to deleteAllCheckpoints for " +
request.tableId + "._id = " + request.rowId);
} else {
reportSuccessAndCleanUp(t);
}
}
}
| fix: 1338 - ODK Survey save-and-exit does not save current changes
| androidcommon_lib/src/main/java/org/opendatakit/views/ExecutorProcessor.java | fix: 1338 - ODK Survey save-and-exit does not save current changes | <ide><path>ndroidcommon_lib/src/main/java/org/opendatakit/views/ExecutorProcessor.java
<ide> context.putOrderedColumns(request.tableId, columns);
<ide> }
<ide>
<add> if ( request.stringifiedJSON != null ) {
<add> ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
<add> if (!cvValues.keySet().isEmpty()) {
<add> dbInterface
<add> .insertCheckpointRowWithId(context.getAppName(), dbHandle, request.tableId, columns,
<add> cvValues, request.rowId);
<add> }
<add> }
<add>
<ide> UserTable t = dbInterface
<ide> .saveAsIncompleteMostRecentCheckpointRowWithId(context.getAppName(), dbHandle,
<ide> request.tableId, columns, request.rowId);
<ide> context.putOrderedColumns(request.tableId, columns);
<ide> }
<ide>
<add> if ( request.stringifiedJSON != null ) {
<add> ContentValues cvValues = convertJSON(columns, request.stringifiedJSON);
<add> if (!cvValues.keySet().isEmpty()) {
<add> dbInterface
<add> .insertCheckpointRowWithId(context.getAppName(), dbHandle, request.tableId, columns,
<add> cvValues, request.rowId);
<add> }
<add> }
<add>
<ide> UserTable t = dbInterface
<ide> .saveAsCompleteMostRecentCheckpointRowWithId(context.getAppName(), dbHandle,
<ide> request.tableId, columns, request.rowId); |
|
Java | apache-2.0 | 07cd9338dc730aa00a57e1384b03fdde3e480b88 | 0 | orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb | /*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.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.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.storage.impl.local;
import com.orientechnologies.common.concur.ONeedRetryException;
import com.orientechnologies.common.concur.lock.OLockManager;
import com.orientechnologies.common.concur.lock.OModificationOperationProhibitedException;
import com.orientechnologies.common.concur.lock.ONotThreadRWLockManager;
import com.orientechnologies.common.concur.lock.OPartitionedLockManager;
import com.orientechnologies.common.concur.lock.OSimpleRWLockManager;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.exception.OHighLevelException;
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.profiler.AtomicLongOProfilerHookValue;
import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.common.serialization.types.OBinarySerializer;
import com.orientechnologies.common.serialization.types.OUTF8Serializer;
import com.orientechnologies.common.thread.OScheduledThreadPoolExecutorWithLogging;
import com.orientechnologies.common.types.OModifiableBoolean;
import com.orientechnologies.common.util.OCallable;
import com.orientechnologies.common.util.OCommonConst;
import com.orientechnologies.common.util.OPair;
import com.orientechnologies.common.util.OUncaughtExceptionHandler;
import com.orientechnologies.orient.core.OConstants;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.config.OContextConfiguration;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.config.OStorageClusterConfiguration;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.orientechnologies.orient.core.config.OStorageConfigurationImpl;
import com.orientechnologies.orient.core.config.OStorageConfigurationUpdateListener;
import com.orientechnologies.orient.core.conflict.ORecordConflictStrategy;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseListener;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.OrientDBConfig;
import com.orientechnologies.orient.core.db.record.OCurrentStorageComponentsFactory;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordOperation;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBagDeleter;
import com.orientechnologies.orient.core.encryption.OEncryption;
import com.orientechnologies.orient.core.encryption.OEncryptionFactory;
import com.orientechnologies.orient.core.encryption.impl.ONothingEncryption;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.exception.OConcurrentCreateException;
import com.orientechnologies.orient.core.exception.OConcurrentModificationException;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.exception.OFastConcurrentModificationException;
import com.orientechnologies.orient.core.exception.OInvalidIndexEngineIdException;
import com.orientechnologies.orient.core.exception.OJVMErrorException;
import com.orientechnologies.orient.core.exception.OLowDiskSpaceException;
import com.orientechnologies.orient.core.exception.OPageIsBrokenException;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import com.orientechnologies.orient.core.exception.ORetryQueryException;
import com.orientechnologies.orient.core.exception.OStorageException;
import com.orientechnologies.orient.core.exception.OStorageExistsException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexAbstract;
import com.orientechnologies.orient.core.index.OIndexCursor;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexEngine;
import com.orientechnologies.orient.core.index.OIndexException;
import com.orientechnologies.orient.core.index.OIndexInternal;
import com.orientechnologies.orient.core.index.OIndexKeyCursor;
import com.orientechnologies.orient.core.index.OIndexKeyUpdater;
import com.orientechnologies.orient.core.index.OIndexManager;
import com.orientechnologies.orient.core.index.OIndexes;
import com.orientechnologies.orient.core.index.ORuntimeKeyIndexDefinition;
import com.orientechnologies.orient.core.metadata.OMetadataDefault;
import com.orientechnologies.orient.core.metadata.schema.OImmutableClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.metadata.security.OSecurityUser;
import com.orientechnologies.orient.core.metadata.security.OToken;
import com.orientechnologies.orient.core.query.OQueryAbstract;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordVersionHelper;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentInternal;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.index.OCompositeKeySerializer;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.index.OSimpleKeySerializer;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OIdentifiableStorage;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.ORecordCallback;
import com.orientechnologies.orient.core.storage.ORecordMetadata;
import com.orientechnologies.orient.core.storage.OStorageAbstract;
import com.orientechnologies.orient.core.storage.OStorageOperationResult;
import com.orientechnologies.orient.core.storage.cache.OCacheEntry;
import com.orientechnologies.orient.core.storage.cache.OPageDataVerificationError;
import com.orientechnologies.orient.core.storage.cache.OReadCache;
import com.orientechnologies.orient.core.storage.cache.OWriteCache;
import com.orientechnologies.orient.core.storage.cache.local.OBackgroundExceptionListener;
import com.orientechnologies.orient.core.storage.cluster.OOfflineCluster;
import com.orientechnologies.orient.core.storage.cluster.OPaginatedCluster;
import com.orientechnologies.orient.core.storage.impl.local.paginated.ORecordOperationMetadata;
import com.orientechnologies.orient.core.storage.impl.local.paginated.ORecordSerializationContext;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OStorageTransaction;
import com.orientechnologies.orient.core.storage.impl.local.paginated.atomicoperations.OAtomicOperation;
import com.orientechnologies.orient.core.storage.impl.local.paginated.atomicoperations.OAtomicOperationsManager;
import com.orientechnologies.orient.core.storage.impl.local.paginated.base.ODurablePage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OAbstractCheckPointStartRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OAtomicUnitEndRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OAtomicUnitStartRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OCheckpointEndRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OFileCreatedWALRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OFileDeletedWALRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OFullCheckpointStartRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OFuzzyCheckpointEndRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OFuzzyCheckpointStartRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OLogSequenceNumber;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.ONonTxOperationPerformedWALRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OOperationUnitId;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OOperationUnitRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OPaginatedClusterFactory;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OUpdatePageRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWALPageBrokenException;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWALRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWriteAheadLog;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.cas.OCASDiskWriteAheadLog;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.cas.OWriteableWALRecord;
import com.orientechnologies.orient.core.storage.impl.local.statistic.OPerformanceStatisticManager;
import com.orientechnologies.orient.core.storage.impl.local.statistic.OSessionStoragePerformanceStatistic;
import com.orientechnologies.orient.core.storage.index.engine.OHashTableIndexEngine;
import com.orientechnologies.orient.core.storage.index.engine.OPrefixBTreeIndexEngine;
import com.orientechnologies.orient.core.storage.index.engine.OSBTreeIndexEngine;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OIndexRIDContainerSBTree;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OSBTreeCollectionManager;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OSBTreeCollectionManagerAbstract;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OSBTreeCollectionManagerShared;
import com.orientechnologies.orient.core.tx.OTransactionAbstract;
import com.orientechnologies.orient.core.tx.OTransactionIndexChanges;
import com.orientechnologies.orient.core.tx.OTransactionInternal;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.locks.Lock;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author Andrey Lomakin (a.lomakin-at-orientdb.com)
* @since 28.03.13
*/
public abstract class OAbstractPaginatedStorage extends OStorageAbstract
implements OLowDiskSpaceListener, OCheckpointRequestListener, OIdentifiableStorage, OBackgroundExceptionListener,
OFreezableStorageComponent, OPageIsBrokenListener {
private static final int WAL_RESTORE_REPORT_INTERVAL = 30 * 1000; // milliseconds
private static final Comparator<ORecordOperation> COMMIT_RECORD_OPERATION_COMPARATOR = Comparator
.comparing(o -> o.getRecord().getIdentity());
protected static final OScheduledThreadPoolExecutorWithLogging fuzzyCheckpointExecutor;
static {
fuzzyCheckpointExecutor = new OScheduledThreadPoolExecutorWithLogging(1, new FuzzyCheckpointThreadFactory());
fuzzyCheckpointExecutor.setMaximumPoolSize(1);
}
private final OSimpleRWLockManager<ORID> lockManager;
/**
* Lock is used to atomically update record versions.
*/
private final OLockManager<ORID> recordVersionManager;
private final Map<String, OCluster> clusterMap = new HashMap<>();
private final List<OCluster> clusters = new ArrayList<>();
private volatile ThreadLocal<OStorageTransaction> transaction;
private final AtomicBoolean checkpointInProgress = new AtomicBoolean();
private final AtomicBoolean walVacuumInProgress = new AtomicBoolean();
/**
* Error which happened inside of storage or during data processing related to this storage.
*/
private final AtomicReference<Error> jvmError = new AtomicReference<>();
@SuppressWarnings("WeakerAccess")
protected final OSBTreeCollectionManagerShared sbTreeCollectionManager;
private final OPerformanceStatisticManager performanceStatisticManager = new OPerformanceStatisticManager(this,
OGlobalConfiguration.STORAGE_PROFILER_SNAPSHOT_INTERVAL.getValueAsInteger() * 1000000L,
OGlobalConfiguration.STORAGE_PROFILER_CLEANUP_INTERVAL.getValueAsInteger() * 1000000L);
protected volatile OWriteAheadLog writeAheadLog;
private OStorageRecoverListener recoverListener;
protected volatile OReadCache readCache;
protected volatile OWriteCache writeCache;
private volatile ORecordConflictStrategy recordConflictStrategy = Orient.instance().getRecordConflictStrategy()
.getDefaultImplementation();
private volatile int defaultClusterId = -1;
@SuppressWarnings("WeakerAccess")
protected volatile OAtomicOperationsManager atomicOperationsManager;
private volatile boolean wereNonTxOperationsPerformedInPreviousOpen = false;
private volatile OLowDiskSpaceInformation lowDiskSpace = null;
private volatile boolean modificationLock = false;
private volatile boolean readLock = false;
/**
* Set of pages which were detected as broken and need to be repaired.
*/
private final Set<OPair<String, Long>> brokenPages = Collections
.newSetFromMap(new ConcurrentHashMap<>());
private volatile Throwable dataFlushException = null;
private final int id;
private final Map<String, OIndexEngine> indexEngineNameMap = new HashMap<>();
private final List<OIndexEngine> indexEngines = new ArrayList<>();
private boolean wereDataRestoredAfterOpen = false;
private final LongAdder fullCheckpointCount = new LongAdder();
private final AtomicLong recordCreated = new AtomicLong(0);
private final AtomicLong recordUpdated = new AtomicLong(0);
private final AtomicLong recordRead = new AtomicLong(0);
private final AtomicLong recordDeleted = new AtomicLong(0);
private final AtomicLong recordScanned = new AtomicLong(0);
private final AtomicLong recordRecycled = new AtomicLong(0);
private final AtomicLong recordConflict = new AtomicLong(0);
private final AtomicLong txBegun = new AtomicLong(0);
private final AtomicLong txCommit = new AtomicLong(0);
private final AtomicLong txRollback = new AtomicLong(0);
public OAbstractPaginatedStorage(String name, String filePath, String mode, int id) {
super(name, filePath, mode);
this.id = id;
lockManager = new ONotThreadRWLockManager<>();
recordVersionManager = new OPartitionedLockManager<>();
registerProfilerHooks();
sbTreeCollectionManager = new OSBTreeCollectionManagerShared(this);
}
@Override
public final void open(final String iUserName, final String iUserPassword, final OContextConfiguration contextConfiguration) {
open(contextConfiguration);
}
public final void open(final OContextConfiguration contextConfiguration) {
try {
stateLock.acquireReadLock();
try {
if (status == STATUS.OPEN)
// ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS
// REUSED
{
return;
}
} finally {
stateLock.releaseReadLock();
}
stateLock.acquireWriteLock();
try {
if (status == STATUS.OPEN)
// ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS
// REUSED
{
return;
}
if (!exists()) {
throw new OStorageException("Cannot open the storage '" + name + "' because it does not exist in path: " + url);
}
initLockingStrategy(contextConfiguration);
transaction = new ThreadLocal<>();
((OStorageConfigurationImpl) configuration).load(contextConfiguration);
checkPageSizeAndRelatedParameters();
componentsFactory = new OCurrentStorageComponentsFactory(getConfiguration());
preOpenSteps();
initWalAndDiskCache(contextConfiguration);
atomicOperationsManager = new OAtomicOperationsManager(this);
recoverIfNeeded();
openClusters();
openIndexes();
status = STATUS.OPEN;
final String cs = configuration.getConflictStrategy();
if (cs != null) {
// SET THE CONFLICT STORAGE STRATEGY FROM THE LOADED CONFIGURATION
setConflictStrategy(Orient.instance().getRecordConflictStrategy().getStrategy(cs));
}
readCache.loadCacheState(writeCache);
} catch (OStorageException e) {
throw e;
} catch (Exception e) {
for (OCluster c : clusters) {
try {
if (c != null) {
c.close(false);
}
} catch (IOException e1) {
OLogManager.instance().error(this, "Cannot close cluster after exception on open", e1);
}
}
try {
status = STATUS.OPEN;
close(true, false);
} catch (RuntimeException re) {
OLogManager.instance().error(this, "Error during storage close", re);
}
status = STATUS.CLOSED;
throw OException.wrapException(new OStorageException("Cannot open local storage '" + url + "' with mode=" + mode), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
OLogManager.instance()
.infoNoDb(this, "Storage '%s' is opened under OrientDB distribution : %s", getURL(), OConstants.getVersion());
}
private void initLockingStrategy(OContextConfiguration contextConfiguration) {
String lockKind = contextConfiguration.getValueAsString(OGlobalConfiguration.STORAGE_PESSIMISTIC_LOCKING);
if (OrientDBConfig.LOCK_TYPE_MODIFICATION.equals(lockKind)) {
modificationLock = true;
} else if (OrientDBConfig.LOCK_TYPE_READWRITE.equals(lockKind)) {
modificationLock = true;
readLock = true;
}
}
/**
* That is internal method which is called once we encounter any error inside of JVM. In such case we need to restart JVM to avoid
* any data corruption. Till JVM is not restarted storage will be put in read-only state.
*/
public final void handleJVMError(Error e) {
if (jvmError.compareAndSet(null, e)) {
OLogManager.instance().errorNoDb(this, "JVM error was thrown", e);
}
}
/**
* This method is called by distributed storage during initialization to indicate that database is used in distributed cluster
* configuration
*/
public void underDistributedStorage() {
sbTreeCollectionManager.prohibitAccess();
}
/**
* @inheritDoc
*/
@Override
public final String getCreatedAtVersion() {
return getConfiguration().getCreatedAtVersion();
}
@SuppressWarnings("WeakerAccess")
protected final void openIndexes() {
OCurrentStorageComponentsFactory cf = componentsFactory;
if (cf == null) {
throw new OStorageException("Storage '" + name + "' is not properly initialized");
}
final Set<String> indexNames = getConfiguration().indexEngines();
for (String indexName : indexNames) {
final OStorageConfigurationImpl.IndexEngineData engineData = getConfiguration().getIndexEngine(indexName);
final OIndexEngine engine = OIndexes
.createIndexEngine(engineData.getName(), engineData.getAlgorithm(), engineData.getIndexType(),
engineData.getDurableInNonTxMode(), this, engineData.getVersion(), engineData.getEngineProperties(), null);
try {
OEncryption encryption;
if (engineData.getEncryption() == null || engineData.getEncryption().toLowerCase(configuration.getLocaleInstance())
.equals(ONothingEncryption.NAME)) {
encryption = null;
} else {
encryption = OEncryptionFactory.INSTANCE.getEncryption(engineData.getEncryption(), engineData.getEncryptionOptions());
}
engine.load(engineData.getName(), cf.binarySerializerFactory.getObjectSerializer(engineData.getValueSerializerId()),
engineData.isAutomatic(), cf.binarySerializerFactory.getObjectSerializer(engineData.getKeySerializedId()),
engineData.getKeyTypes(), engineData.isNullValuesSupport(), engineData.getKeySize(), engineData.getEngineProperties(),
encryption);
indexEngineNameMap.put(engineData.getName(), engine);
indexEngines.add(engine);
} catch (RuntimeException e) {
OLogManager.instance()
.error(this, "Index '" + engineData.getName() + "' cannot be created and will be removed from configuration", e);
try {
engine.deleteWithoutLoad(engineData.getName());
} catch (IOException ioe) {
OLogManager.instance().error(this, "Can not delete index " + engineData.getName(), ioe);
}
}
}
}
@SuppressWarnings("WeakerAccess")
protected final void openClusters() throws IOException {
// OPEN BASIC SEGMENTS
int pos;
// REGISTER CLUSTER
final List<OStorageClusterConfiguration> configurationClusters = configuration.getClusters();
for (int i = 0; i < configurationClusters.size(); ++i) {
final OStorageClusterConfiguration clusterConfig = configurationClusters.get(i);
if (clusterConfig != null) {
pos = createClusterFromConfig(clusterConfig);
try {
if (pos == -1) {
clusters.get(i).open();
} else {
if (clusterConfig.getName().equals(CLUSTER_DEFAULT_NAME)) {
defaultClusterId = pos;
}
clusters.get(pos).open();
}
} catch (FileNotFoundException e) {
OLogManager.instance().warn(this, "Error on loading cluster '" + configurationClusters.get(i).getName() + "' (" + i
+ "): file not found. It will be excluded from current database '" + getName() + "'.", e);
clusterMap.remove(configurationClusters.get(i).getName().toLowerCase(configuration.getLocaleInstance()));
setCluster(i, null);
}
} else {
setCluster(i, null);
}
}
}
@SuppressWarnings("unused")
public void open(final OToken iToken, final OContextConfiguration configuration) {
open(iToken.getUserName(), "", configuration);
}
@Override
public void create(OContextConfiguration contextConfiguration) throws IOException {
checkPageSizeAndRelatedParametersInGlobalConfiguration();
try {
stateLock.acquireWriteLock();
try {
if (status != STATUS.CLOSED) {
throw new OStorageExistsException("Cannot create new storage '" + getURL() + "' because it is not closed");
}
if (exists()) {
throw new OStorageExistsException("Cannot create new storage '" + getURL() + "' because it already exists");
}
initLockingStrategy(contextConfiguration);
((OStorageConfigurationImpl) configuration).initConfiguration(contextConfiguration);
componentsFactory = new OCurrentStorageComponentsFactory(getConfiguration());
transaction = new ThreadLocal<>();
initWalAndDiskCache(contextConfiguration);
atomicOperationsManager = new OAtomicOperationsManager(this);
preCreateSteps();
status = STATUS.OPEN;
// ADD THE METADATA CLUSTER TO STORE INTERNAL STUFF
doAddCluster(OMetadataDefault.CLUSTER_INTERNAL_NAME, null);
((OStorageConfigurationImpl) configuration).create();
((OStorageConfigurationImpl) configuration).setCreationVersion(OConstants.getVersion());
((OStorageConfigurationImpl) configuration)
.setPageSize(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
((OStorageConfigurationImpl) configuration)
.setFreeListBoundary(OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getValueAsInteger() * 1024);
((OStorageConfigurationImpl) configuration).setMaxKeySize(OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getValueAsInteger());
// ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF
// INDEXING
doAddCluster(OMetadataDefault.CLUSTER_INDEX_NAME, null);
// ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF
// INDEXING
doAddCluster(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME, null);
// ADD THE DEFAULT CLUSTER
defaultClusterId = doAddCluster(CLUSTER_DEFAULT_NAME, null);
if (jvmError.get() == null) {
clearStorageDirty();
}
if (contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_MAKE_FULL_CHECKPOINT_AFTER_CREATE)) {
makeFullCheckpoint();
}
postCreateSteps();
} catch (InterruptedException e) {
throw OException.wrapException(new OStorageException("Storage creation was interrupted"), e);
} catch (OStorageException e) {
close();
throw e;
} catch (IOException e) {
close();
throw OException.wrapException(new OStorageException("Error on creation of storage '" + name + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
OLogManager.instance()
.infoNoDb(this, "Storage '%s' is created under OrientDB distribution : %s", getURL(), OConstants.getVersion());
}
private static void checkPageSizeAndRelatedParametersInGlobalConfiguration() {
final int pageSize = OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024;
final int freeListBoundary = OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getValueAsInteger() * 1024;
final int maxKeySize = OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getValueAsInteger();
if (freeListBoundary > pageSize / 2) {
throw new OStorageException("Value of parameter " + OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getKey()
+ " should be at least 2 times bigger than value of parameter "
+ OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getKey() + " but real values are :"
+ OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getKey() + " = " + pageSize + " , "
+ OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getKey() + " = " + freeListBoundary);
}
if (maxKeySize > pageSize / 4) {
throw new OStorageException("Value of parameter " + OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getKey()
+ " should be at least 4 times bigger than value of parameter " + OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getKey()
+ " but real values are :" + OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getKey() + " = " + pageSize + " , "
+ OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getKey() + " = " + maxKeySize);
}
}
private void checkPageSizeAndRelatedParameters() {
final int pageSize = OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024;
final int freeListBoundary = OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getValueAsInteger() * 1024;
final int maxKeySize = OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getValueAsInteger();
if (configuration.getPageSize() != -1 && configuration.getPageSize() != pageSize) {
throw new OStorageException(
"Storage is created with value of " + OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getKey() + " parameter equal to "
+ configuration.getPageSize() + " but current value is " + pageSize);
}
if (configuration.getFreeListBoundary() != -1 && configuration.getFreeListBoundary() != freeListBoundary) {
throw new OStorageException(
"Storage is created with value of " + OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getKey()
+ " parameter equal to " + configuration.getFreeListBoundary() + " but current value is " + freeListBoundary);
}
if (configuration.getMaxKeySize() != -1 && configuration.getMaxKeySize() != maxKeySize) {
throw new OStorageException(
"Storage is created with value of " + OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getKey() + " parameter equal to "
+ configuration.getMaxKeySize() + " but current value is " + maxKeySize);
}
}
@Override
public final boolean isClosed() {
try {
stateLock.acquireReadLock();
try {
return super.isClosed();
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final void close(final boolean force, boolean onDelete) {
try {
doClose(force, onDelete);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final void delete() {
try {
final long timer = Orient.instance().getProfiler().startChrono();
stateLock.acquireWriteLock();
try {
try {
// CLOSE THE DATABASE BY REMOVING THE CURRENT USER
close(true, true);
if (writeCache != null) {
if (readCache != null) {
readCache.deleteStorage(writeCache);
} else {
writeCache.delete();
}
}
postDeleteSteps();
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot delete database '" + name + "'"), e);
}
} finally {
stateLock.releaseWriteLock();
//noinspection ResultOfMethodCallIgnored
Orient.instance().getProfiler().stopChrono("db." + name + ".drop", "Drop a database", timer, "db.*.drop");
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public boolean check(final boolean verbose, final OCommandOutputListener listener) {
try {
listener.onMessage("Check of storage is started...");
checkOpenness();
stateLock.acquireReadLock();
try {
final long lockId = atomicOperationsManager.freezeAtomicOperations(null, null);
try {
checkOpenness();
final long start = System.currentTimeMillis();
OPageDataVerificationError[] pageErrors = writeCache.checkStoredPages(verbose ? listener : null);
listener.onMessage(
"Check of storage completed in " + (System.currentTimeMillis() - start) + "ms. " + (pageErrors.length > 0 ?
pageErrors.length + " with errors." :
" without errors."));
return pageErrors.length == 0;
} finally {
atomicOperationsManager.releaseAtomicOperations(lockId);
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int addCluster(String clusterName, final Object... parameters) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
stateLock.acquireWriteLock();
try {
checkOpenness();
makeStorageDirty();
return doAddCluster(clusterName, parameters);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error in creation of new cluster '" + clusterName), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int addCluster(String clusterName, int requestedId, Object... parameters) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
stateLock.acquireWriteLock();
try {
checkOpenness();
if (requestedId < 0) {
throw new OConfigurationException("Cluster id must be positive!");
}
if (requestedId < clusters.size() && clusters.get(requestedId) != null) {
throw new OConfigurationException(
"Requested cluster ID [" + requestedId + "] is occupied by cluster with name [" + clusters.get(requestedId).getName()
+ "]");
}
makeStorageDirty();
return addClusterInternal(clusterName, requestedId, parameters);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error in creation of new cluster '" + clusterName + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final boolean dropCluster(final int clusterId, final boolean iTruncate) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
stateLock.acquireWriteLock();
try {
checkOpenness();
if (clusterId < 0 || clusterId >= clusters.size()) {
throw new IllegalArgumentException(
"Cluster id '" + clusterId + "' is outside the of range of configured clusters (0-" + (clusters.size() - 1)
+ ") in database '" + name + "'");
}
final OCluster cluster = clusters.get(clusterId);
if (cluster == null) {
return false;
}
if (iTruncate) {
cluster.truncate();
}
cluster.delete();
makeStorageDirty();
clusterMap.remove(cluster.getName().toLowerCase(configuration.getLocaleInstance()));
clusters.set(clusterId, null);
// UPDATE CONFIGURATION
getConfiguration().dropCluster(clusterId);
return true;
} catch (Exception e) {
throw OException.wrapException(new OStorageException("Error while removing cluster '" + clusterId + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int getId() {
return id;
}
public boolean setClusterStatus(final int clusterId, final OStorageClusterConfiguration.STATUS iStatus) {
try {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
if (clusterId < 0 || clusterId >= clusters.size()) {
throw new IllegalArgumentException(
"Cluster id '" + clusterId + "' is outside the of range of configured clusters (0-" + (clusters.size() - 1)
+ ") in database '" + name + "'");
}
final OCluster cluster = clusters.get(clusterId);
if (cluster == null) {
return false;
}
if (iStatus == OStorageClusterConfiguration.STATUS.OFFLINE && cluster instanceof OOfflineCluster
|| iStatus == OStorageClusterConfiguration.STATUS.ONLINE && !(cluster instanceof OOfflineCluster)) {
return false;
}
final OCluster newCluster;
if (iStatus == OStorageClusterConfiguration.STATUS.OFFLINE) {
cluster.close(true);
newCluster = new OOfflineCluster(this, clusterId, cluster.getName());
boolean configured = false;
for (OStorageClusterConfiguration clusterConfiguration : configuration.getClusters()) {
if (clusterConfiguration.getId() == cluster.getId()) {
newCluster.configure(this, clusterConfiguration);
configured = true;
break;
}
}
if (!configured) {
throw new OStorageException("Can not configure offline cluster with id " + clusterId);
}
} else {
newCluster = OPaginatedClusterFactory
.createCluster(cluster.getName(), configuration.getVersion(), cluster.getBinaryVersion(), this);
newCluster.configure(this, clusterId, cluster.getName());
newCluster.open();
}
clusterMap.put(cluster.getName().toLowerCase(configuration.getLocaleInstance()), newCluster);
clusters.set(clusterId, newCluster);
// UPDATE CONFIGURATION
makeStorageDirty();
((OStorageConfigurationImpl) configuration).setClusterStatus(clusterId, iStatus);
makeFullCheckpoint();
return true;
} catch (Exception e) {
throw OException.wrapException(new OStorageException("Error while removing cluster '" + clusterId + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OSBTreeCollectionManager getSBtreeCollectionManager() {
return sbTreeCollectionManager;
}
public OReadCache getReadCache() {
return readCache;
}
public OWriteCache getWriteCache() {
return writeCache;
}
@Override
public final long count(final int iClusterId) {
return count(iClusterId, false);
}
@Override
public final long count(int clusterId, boolean countTombstones) {
try {
if (clusterId == -1) {
throw new OStorageException("Cluster Id " + clusterId + " is invalid in database '" + name + "'");
}
// COUNT PHYSICAL CLUSTER IF ANY
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = clusters.get(clusterId);
if (cluster == null) {
return 0;
}
if (countTombstones) {
return cluster.getEntries();
}
return cluster.getEntries() - cluster.getTombstonesCount();
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final long[] getClusterDataRange(final int iClusterId) {
try {
if (iClusterId == -1) {
return new long[] { ORID.CLUSTER_POS_INVALID, ORID.CLUSTER_POS_INVALID };
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return clusters.get(iClusterId) != null ?
new long[] { clusters.get(iClusterId).getFirstPosition(), clusters.get(iClusterId).getLastPosition() } :
OCommonConst.EMPTY_LONG_ARRAY;
} catch (IOException ioe) {
throw OException.wrapException(new OStorageException("Cannot retrieve information about data range"), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public OLogSequenceNumber getLSN() {
try {
if (writeAheadLog == null) {
return null;
}
return writeAheadLog.end();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final long count(final int[] iClusterIds) {
return count(iClusterIds, false);
}
@Override
public final void onException(Throwable e) {
dataFlushException = e;
}
/**
* This method finds all the records which were updated starting from (but not including) current LSN and write result in provided
* output stream. In output stream will be included all thw records which were updated/deleted/created since passed in LSN till
* the current moment. Deleted records are written in output stream first, then created/updated records. All records are sorted by
* record id. Data format: <ol> <li>Amount of records (single entry) - 8 bytes</li> <li>Record's cluster id - 4 bytes</li>
* <li>Record's cluster position - 8 bytes</li> <li>Delete flag, 1 if record is deleted - 1 byte</li> <li>Record version , only
* if record is not deleted - 4 bytes</li> <li>Record type, only if record is not deleted - 1 byte</li> <li>Length of binary
* presentation of record, only if record is not deleted - 4 bytes</li> <li>Binary presentation of the record, only if record is
* not deleted - length of content is provided in above entity</li> </ol>
*
* @param lsn LSN from which we should find changed records
* @param stream Stream which will contain found records
*
* @return Last LSN processed during examination of changed records, or <code>null</code> if it was impossible to find changed
* records: write ahead log is absent, record with start LSN was not found in WAL, etc.
*
* @see OGlobalConfiguration#STORAGE_TRACK_CHANGED_RECORDS_IN_WAL
*/
public OLogSequenceNumber recordsChangedAfterLSN(final OLogSequenceNumber lsn, final OutputStream stream,
final OCommandOutputListener outputListener) {
try {
if (!getConfiguration().getContextConfiguration()
.getValueAsBoolean(OGlobalConfiguration.STORAGE_TRACK_CHANGED_RECORDS_IN_WAL)) {
throw new IllegalStateException(
"Cannot find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, "
+ "to switch it on please set property " + OGlobalConfiguration.STORAGE_TRACK_CHANGED_RECORDS_IN_WAL.getKey()
+ " to the true value, please note that only records"
+ " which are stored after this property was set will be retrieved");
}
stateLock.acquireReadLock();
try {
if (writeAheadLog == null) {
return null;
}
// we iterate till the last record is contained in wal at the moment when we call this method
final OLogSequenceNumber endLsn = writeAheadLog.end();
if (endLsn == null || lsn.compareTo(endLsn) > 0) {
OLogManager.instance()
.warn(this, "Cannot find requested LSN=%s for database sync operation. Last available LSN is %s", lsn, endLsn);
return null;
}
if (lsn.equals(endLsn)) {
// nothing has changed
return endLsn;
}
// container of rids of changed records
final SortedSet<ORID> sortedRids = new TreeSet<>();
List<OWriteableWALRecord> records = writeAheadLog.next(lsn, 1);
if (records.isEmpty()) {
OLogManager.instance()
.info(this, "Cannot find requested LSN=%s for database sync operation (last available LSN is %s)", lsn, endLsn);
return null;
}
final OLogSequenceNumber freezeLsn = records.get(0).getLsn();
writeAheadLog.addCutTillLimit(freezeLsn);
try {
records = writeAheadLog.next(lsn, 1_000);
if (records.isEmpty()) {
OLogManager.instance()
.info(this, "Cannot find requested LSN=%s for database sync operation (last available LSN is %s)", lsn, endLsn);
return null;
}
// all information about changed records is contained in atomic operation metadata
long read = 0;
readLoop:
while (!records.isEmpty()) {
for (OWALRecord record : records) {
final OLogSequenceNumber recordLSN = record.getLsn();
if (endLsn.compareTo(recordLSN) >= 0) {
if (record instanceof OFileCreatedWALRecord) {
throw new ODatabaseException(
"Cannot execute delta-sync because a new file has been added. Filename: '" + ((OFileCreatedWALRecord) record)
.getFileName() + "' (id=" + ((OFileCreatedWALRecord) record).getFileId() + ")");
}
if (record instanceof OFileDeletedWALRecord) {
throw new ODatabaseException(
"Cannot execute delta-sync because a file has been deleted. File id: " + ((OFileDeletedWALRecord) record)
.getFileId());
}
if (record instanceof OAtomicUnitEndRecord) {
final OAtomicUnitEndRecord atomicUnitEndRecord = (OAtomicUnitEndRecord) record;
if (atomicUnitEndRecord.getAtomicOperationMetadata().containsKey(ORecordOperationMetadata.RID_METADATA_KEY)) {
final ORecordOperationMetadata recordOperationMetadata = (ORecordOperationMetadata) atomicUnitEndRecord
.getAtomicOperationMetadata().get(ORecordOperationMetadata.RID_METADATA_KEY);
final Set<ORID> rids = recordOperationMetadata.getValue();
sortedRids.addAll(rids);
}
}
read++;
if (outputListener != null) {
outputListener.onMessage("read " + read + " records from WAL and collected " + sortedRids.size() + " records");
}
} else {
break readLoop;
}
}
records = writeAheadLog.next(records.get(records.size() - 1).getLsn(), 1_000);
}
} finally {
writeAheadLog.removeCutTillLimit(freezeLsn);
}
final int totalRecords = sortedRids.size();
OLogManager.instance().info(this, "Exporting records after LSN=%s. Found %d records", lsn, totalRecords);
// records may be deleted after we flag them as existing and as result rule of sorting of records
// (deleted records go first will be broken), so we prohibit any modifications till we do not complete method execution
final long lockId = atomicOperationsManager.freezeAtomicOperations(null, null);
try {
try (DataOutputStream dataOutputStream = new DataOutputStream(stream)) {
dataOutputStream.writeLong(sortedRids.size());
long exportedRecord = 1;
Iterator<ORID> ridIterator = sortedRids.iterator();
while (ridIterator.hasNext()) {
final ORID rid = ridIterator.next();
final OCluster cluster = clusters.get(rid.getClusterId());
// we do not need to load record only check it's presence
if (cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition())) == null) {
dataOutputStream.writeInt(rid.getClusterId());
dataOutputStream.writeLong(rid.getClusterPosition());
dataOutputStream.write(1);
OLogManager.instance().debug(this, "Exporting deleted record %s", rid);
if (outputListener != null) {
outputListener.onMessage("exporting record " + exportedRecord + "/" + totalRecords);
}
// delete to avoid duplication
ridIterator.remove();
exportedRecord++;
}
}
ridIterator = sortedRids.iterator();
while (ridIterator.hasNext()) {
final ORID rid = ridIterator.next();
final OCluster cluster = clusters.get(rid.getClusterId());
dataOutputStream.writeInt(rid.getClusterId());
dataOutputStream.writeLong(rid.getClusterPosition());
if (cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition())) == null) {
dataOutputStream.writeBoolean(true);
OLogManager.instance().debug(this, "Exporting deleted record %s", rid);
} else {
final ORawBuffer rawBuffer = cluster.readRecord(rid.getClusterPosition(), false);
assert rawBuffer != null;
dataOutputStream.writeBoolean(false);
dataOutputStream.writeInt(rawBuffer.version);
dataOutputStream.write(rawBuffer.recordType);
dataOutputStream.writeInt(rawBuffer.buffer.length);
dataOutputStream.write(rawBuffer.buffer);
OLogManager.instance().debug(this, "Exporting modified record rid=%s type=%d size=%d v=%d - buffer size=%d", rid,
rawBuffer.recordType, rawBuffer.buffer.length, rawBuffer.version, dataOutputStream.size());
}
if (outputListener != null) {
outputListener.onMessage("exporting record " + exportedRecord + "/" + totalRecords);
}
exportedRecord++;
}
}
} finally {
atomicOperationsManager.releaseAtomicOperations(lockId);
}
return endLsn;
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error of reading of records changed after LSN " + lsn), e);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException e) {
throw logAndPrepareForRethrow(e);
} catch (Error e) {
throw logAndPrepareForRethrow(e);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* This method finds all the records changed in the last X transactions.
*
* @param maxEntries Maximum number of entries to check back from last log.
*
* @return A set of record ids of the changed records
*
* @see OGlobalConfiguration#STORAGE_TRACK_CHANGED_RECORDS_IN_WAL
*/
public Set<ORecordId> recordsChangedRecently(final int maxEntries) {
final SortedSet<ORecordId> result = new TreeSet<>();
try {
if (!OGlobalConfiguration.STORAGE_TRACK_CHANGED_RECORDS_IN_WAL.getValueAsBoolean()) {
throw new IllegalStateException(
"Cannot find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, "
+ "to switch it on please set property " + OGlobalConfiguration.STORAGE_TRACK_CHANGED_RECORDS_IN_WAL.getKey()
+ " to the true value, please note that only records"
+ " which are stored after this property was set will be retrieved");
}
stateLock.acquireReadLock();
try {
if (writeAheadLog == null) {
OLogManager.instance().warn(this, "No WAL found for database '%s'", name);
return null;
}
OLogSequenceNumber startLsn = writeAheadLog.begin();
if (startLsn == null) {
OLogManager.instance().warn(this, "The WAL is empty for database '%s'", name);
return result;
}
final OLogSequenceNumber freezeLSN = startLsn;
writeAheadLog.addCutTillLimit(freezeLSN);
try {
//reread because log may be already truncated
startLsn = writeAheadLog.begin();
if (startLsn == null) {
OLogManager.instance().warn(this, "The WAL is empty for database '%s'", name);
return result;
}
final OLogSequenceNumber endLsn = writeAheadLog.end();
if (endLsn == null) {
OLogManager.instance().warn(this, "The WAL is empty for database '%s'", name);
return result;
}
List<OWriteableWALRecord> walRecords = writeAheadLog.read(startLsn, 1_000);
if (walRecords.isEmpty()) {
OLogManager.instance()
.info(this, "Cannot find requested LSN=%s for database sync operation (record in WAL is absent)", startLsn);
return null;
}
// KEEP LAST MAX-ENTRIES TRANSACTIONS' LSN
final List<OAtomicUnitEndRecord> lastTx = new ArrayList<>();
readLoop:
while (!walRecords.isEmpty()) {
for (OWriteableWALRecord walRecord : walRecords) {
final OLogSequenceNumber recordLSN = walRecord.getLsn();
if (endLsn.compareTo(recordLSN) >= 0) {
if (walRecord instanceof OAtomicUnitEndRecord) {
if (lastTx.size() >= maxEntries) {
lastTx.remove(0);
}
lastTx.add((OAtomicUnitEndRecord) walRecord);
}
} else {
break readLoop;
}
}
walRecords = writeAheadLog.next(walRecords.get(walRecords.size() - 1).getLsn(), 1_000);
}
// COLLECT ALL THE MODIFIED RECORDS
for (OAtomicUnitEndRecord atomicUnitEndRecord : lastTx) {
if (atomicUnitEndRecord.getAtomicOperationMetadata().containsKey(ORecordOperationMetadata.RID_METADATA_KEY)) {
final ORecordOperationMetadata recordOperationMetadata = (ORecordOperationMetadata) atomicUnitEndRecord
.getAtomicOperationMetadata().get(ORecordOperationMetadata.RID_METADATA_KEY);
final Set<ORID> rids = recordOperationMetadata.getValue();
for (ORID rid : rids) {
result.add((ORecordId) rid);
}
}
}
OLogManager.instance().info(this, "Found %d records changed in last %d operations", result.size(), lastTx.size());
return result;
} finally {
writeAheadLog.removeCutTillLimit(freezeLSN);
}
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error on reading last changed records"), e);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException e) {
throw logAndPrepareForRethrow(e);
} catch (Error e) {
throw logAndPrepareForRethrow(e);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final long count(int[] iClusterIds, boolean countTombstones) {
try {
checkOpenness();
long tot = 0;
stateLock.acquireReadLock();
try {
checkOpenness();
for (int iClusterId : iClusterIds) {
if (iClusterId >= clusters.size()) {
throw new OConfigurationException("Cluster id " + iClusterId + " was not found in database '" + name + "'");
}
if (iClusterId > -1) {
final OCluster c = clusters.get(iClusterId);
if (c != null) {
tot += c.getEntries() - (countTombstones ? 0L : c.getTombstonesCount());
}
}
}
return tot;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final OStorageOperationResult<OPhysicalPosition> createRecord(final ORecordId rid, final byte[] content,
final int recordVersion, final byte recordType, final ORecordCallback<Long> callback) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
final OCluster cluster = getClusterById(rid.getClusterId());
if (transaction.get() != null) {
return doCreateRecord(rid, content, recordVersion, recordType, callback, cluster, null);
}
stateLock.acquireReadLock();
try {
checkOpenness();
return doCreateRecord(rid, content, recordVersion, recordType, callback, cluster, null);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final ORecordMetadata getRecordMetadata(ORID rid) {
try {
if (rid.isNew()) {
throw new OStorageException("Passed record with id " + rid + " is new and cannot be stored.");
}
checkOpenness();
stateLock.acquireReadLock();
try {
final OCluster cluster = getClusterById(rid.getClusterId());
checkOpenness();
final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition()));
if (ppos == null) {
return null;
}
return new ORecordMetadata(rid, ppos.recordVersion);
} catch (IOException ioe) {
OLogManager.instance().error(this, "Retrieval of record '" + rid + "' cause: " + ioe.getMessage(), ioe);
} finally {
stateLock.releaseReadLock();
}
return null;
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public boolean isDeleted(ORID rid) {
try {
if (rid.isNew()) {
throw new OStorageException("Passed record with id " + rid + " is new and cannot be stored.");
}
checkOpenness();
stateLock.acquireReadLock();
try {
final OCluster cluster = getClusterById(rid.getClusterId());
checkOpenness();
return cluster.isDeleted(new OPhysicalPosition(rid.getClusterPosition()));
} catch (IOException ioe) {
OLogManager.instance().error(this, "Retrieval of record '" + rid + "' cause: " + ioe.getMessage(), ioe);
} finally {
stateLock.releaseReadLock();
}
return false;
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public Iterator<OClusterBrowsePage> browseCluster(int clusterId) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final int finalClusterId;
if (clusterId == ORID.CLUSTER_ID_INVALID) {
// GET THE DEFAULT CLUSTER
finalClusterId = defaultClusterId;
} else {
finalClusterId = clusterId;
}
return new Iterator<OClusterBrowsePage>() {
private OClusterBrowsePage page = null;
private long lastPos = -1;
@Override
public boolean hasNext() {
if (page == null) {
page = nextPage(finalClusterId, lastPos);
if (page != null) {
lastPos = page.getLastPosition();
}
}
return page != null;
}
@Override
public OClusterBrowsePage next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
OClusterBrowsePage curPage = page;
page = null;
return curPage;
}
};
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OClusterBrowsePage nextPage(int clusterId, long lastPosition) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = doGetAndCheckCluster(clusterId);
return cluster.nextPage(lastPosition);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OCluster doGetAndCheckCluster(int clusterId) {
checkClusterSegmentIndexRange(clusterId);
final OCluster cluster = clusters.get(clusterId);
if (cluster == null) {
throw new IllegalArgumentException("Cluster " + clusterId + " is null");
}
return cluster;
}
@Override
public OStorageOperationResult<ORawBuffer> readRecord(final ORecordId iRid, final String iFetchPlan, boolean iIgnoreCache,
boolean prefetchRecords, ORecordCallback<ORawBuffer> iCallback) {
try {
checkOpenness();
final OCluster cluster;
try {
cluster = getClusterById(iRid.getClusterId());
} catch (IllegalArgumentException e) {
throw OException.wrapException(new ORecordNotFoundException(iRid), e);
}
return new OStorageOperationResult<>(readRecord(cluster, iRid, prefetchRecords));
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OStorageOperationResult<ORawBuffer> readRecordIfVersionIsNotLatest(final ORecordId rid, final String fetchPlan,
final boolean ignoreCache, final int recordVersion) throws ORecordNotFoundException {
try {
checkOpenness();
return new OStorageOperationResult<>(readRecordIfNotLatest(getClusterById(rid.getClusterId()), rid, recordVersion));
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final OStorageOperationResult<Integer> updateRecord(final ORecordId rid, final boolean updateContent, final byte[] content,
final int version, final byte recordType, @SuppressWarnings("unused") final int mode,
final ORecordCallback<Integer> callback) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
final OCluster cluster = getClusterById(rid.getClusterId());
if (transaction.get() != null) {
return doUpdateRecord(rid, updateContent, content, version, recordType, callback, cluster);
}
stateLock.acquireReadLock();
try {
// GET THE SHARED LOCK AND GET AN EXCLUSIVE LOCK AGAINST THE RECORD
final Lock lock = recordVersionManager.acquireExclusiveLock(rid);
try {
checkOpenness();
// UPDATE IT
return doUpdateRecord(rid, updateContent, content, version, recordType, callback, cluster);
} finally {
lock.unlock();
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OStorageOperationResult<Integer> recyclePosition(final ORecordId rid, final byte[] content, final int version,
final byte recordType) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
final OCluster cluster = getClusterById(rid.getClusterId());
if (transaction.get() != null) {
return doRecycleRecord(rid, content, version, cluster, recordType);
}
stateLock.acquireReadLock();
try {
// GET THE SHARED LOCK AND GET AN EXCLUSIVE LOCK AGAINST THE RECORD
final Lock lock = recordVersionManager.acquireExclusiveLock(rid);
try {
checkOpenness();
// RECYCLING IT
return doRecycleRecord(rid, content, version, cluster, recordType);
} finally {
lock.unlock();
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public OStorageTransaction getStorageTransaction() {
return transaction.get();
}
public OAtomicOperationsManager getAtomicOperationsManager() {
return atomicOperationsManager;
}
public OWriteAheadLog getWALInstance() {
return writeAheadLog;
}
@Override
public final OStorageOperationResult<Boolean> deleteRecord(final ORecordId rid, final int version, final int mode,
ORecordCallback<Boolean> callback) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
final OCluster cluster = getClusterById(rid.getClusterId());
if (transaction.get() != null) {
return doDeleteRecord(rid, version, cluster);
}
stateLock.acquireReadLock();
try {
checkOpenness();
return doDeleteRecord(rid, version, cluster);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OStorageOperationResult<Boolean> hideRecord(final ORecordId rid, final int mode, ORecordCallback<Boolean> callback) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
final OCluster cluster = getClusterById(rid.getClusterId());
if (transaction.get() != null) {
return doHideMethod(rid, cluster);
}
stateLock.acquireReadLock();
try {
final Lock lock = recordVersionManager.acquireExclusiveLock(rid);
try {
checkOpenness();
return doHideMethod(rid, cluster);
} finally {
lock.unlock();
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
protected OPerformanceStatisticManager getPerformanceStatisticManager() {
return performanceStatisticManager;
}
/**
* Starts to gather information about storage performance for current thread. Details which performance characteristics are
* gathered can be found at {@link OSessionStoragePerformanceStatistic}.
*
* @see #completeGatheringPerformanceStatisticForCurrentThread()
*/
public void startGatheringPerformanceStatisticForCurrentThread() {
try {
performanceStatisticManager.startThreadMonitoring();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Completes gathering performance characteristics for current thread initiated by call of {@link
* #startGatheringPerformanceStatisticForCurrentThread()}
*
* @return Performance statistic gathered after call of {@link #startGatheringPerformanceStatisticForCurrentThread()} or
* <code>null</code> if profiling of storage was not started.
*/
public OSessionStoragePerformanceStatistic completeGatheringPerformanceStatisticForCurrentThread() {
try {
return performanceStatisticManager.stopThreadMonitoring();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final <V> V callInLock(Callable<V> iCallable, boolean iExclusiveLock) {
try {
stateLock.acquireReadLock();
try {
if (iExclusiveLock) {
return super.callInLock(iCallable, true);
} else {
return super.callInLock(iCallable, false);
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final Set<String> getClusterNames() {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return new HashSet<>(clusterMap.keySet());
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int getClusterIdByName(final String clusterName) {
try {
checkOpenness();
if (clusterName == null) {
throw new IllegalArgumentException("Cluster name is null");
}
if (clusterName.length() == 0) {
throw new IllegalArgumentException("Cluster name is empty");
}
// if (Character.isDigit(clusterName.charAt(0)))
// return Integer.parseInt(clusterName);
stateLock.acquireReadLock();
try {
checkOpenness();
// SEARCH IT BETWEEN PHYSICAL CLUSTERS
final OCluster segment = clusterMap.get(clusterName.toLowerCase(configuration.getLocaleInstance()));
if (segment != null) {
return segment.getId();
}
return -1;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Scan the given transaction for new record and allocate a record id for them, the relative record id is inserted inside the
* transaction for future use.
*
* @param clientTx the transaction of witch allocate rids
*/
public void preallocateRids(final OTransactionInternal clientTx) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
@SuppressWarnings("unchecked")
final Iterable<ORecordOperation> entries = clientTx.getRecordOperations();
final TreeMap<Integer, OCluster> clustersToLock = new TreeMap<>();
final Set<ORecordOperation> newRecords = new TreeSet<>(COMMIT_RECORD_OPERATION_COMPARATOR);
for (ORecordOperation txEntry : entries) {
if (txEntry.type == ORecordOperation.CREATED) {
newRecords.add(txEntry);
int clusterId = txEntry.getRID().getClusterId();
clustersToLock.put(clusterId, getClusterById(clusterId));
}
}
stateLock.acquireReadLock();
try {
checkOpenness();
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
lockClusters(clustersToLock);
for (ORecordOperation txEntry : newRecords) {
ORecord rec = txEntry.getRecord();
if (!rec.getIdentity().isPersistent()) {
if (rec.isDirty()) {
//This allocate a position for a new record
ORecordId rid = (ORecordId) rec.getIdentity().copy();
ORecordId oldRID = rid.copy();
final OCluster cluster = getClusterById(rid.getClusterId());
OPhysicalPosition ppos = cluster.allocatePosition(ORecordInternal.getRecordType(rec));
rid.setClusterPosition(ppos.clusterPosition);
clientTx.updateIdentityAfterCommit(oldRID, rid);
}
} else {
//This allocate position starting from a valid rid, used in distributed for allocate the same position on other nodes
ORecordId rid = (ORecordId) rec.getIdentity();
final OCluster cluster = getClusterById(rid.getClusterId());
OPhysicalPosition ppos = cluster.allocatePosition(ORecordInternal.getRecordType(rec));
if (ppos.clusterPosition != rid.getClusterPosition()) {
throw new OConcurrentCreateException(rid, new ORecordId(rid.getClusterId(), ppos.clusterPosition));
}
}
}
} catch (Exception e) {
rollback = true;
throw e;
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
} catch (IOException | RuntimeException ioe) {
throw OException.wrapException(new OStorageException("Could not preallocate RIDs"), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Traditional commit that support already temporary rid and already assigned rids
*
* @param clientTx the transaction to commit
*
* @return The list of operations applied by the transaction
*/
@Override
public List<ORecordOperation> commit(final OTransactionInternal clientTx) {
return commit(clientTx, false);
}
/**
* Commit a transaction where the rid where pre-allocated in a previous phase
*
* @param clientTx the pre-allocated transaction to commit
*
* @return The list of operations applied by the transaction
*/
@SuppressWarnings("UnusedReturnValue")
public List<ORecordOperation> commitPreAllocated(final OTransactionInternal clientTx) {
return commit(clientTx, true);
}
/**
* The commit operation can be run in 3 different conditions, embedded commit, pre-allocated commit, other node commit.
* <bold>Embedded commit</bold> is the basic commit where the operation is run in embedded or server side, the transaction arrive
* with invalid rids that get allocated and committed.
* <bold>pre-allocated commit</bold> is the commit that happen after an preAllocateRids call is done, this is usually run by the
* coordinator of a tx in distributed.
* <bold>other node commit</bold> is the commit that happen when a node execute a transaction of another node where all the rids
* are already allocated in the other node.
*
* @param transaction the transaction to commit
* @param allocated true if the operation is pre-allocated commit
*
* @return The list of operations applied by the transaction
*/
private List<ORecordOperation> commit(final OTransactionInternal transaction, boolean allocated) {
// XXX: At this moment, there are two implementations of the commit method. One for regular client transactions and one for
// implicit micro-transactions. The implementations are quite identical, but operate on slightly different data. If you change
// this method don't forget to change its counterpart:
//
// OAbstractPaginatedStorage.commit(com.orientechnologies.orient.core.storage.impl.local.OMicroTransaction)
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
txBegun.incrementAndGet();
final ODatabaseDocumentInternal database = transaction.getDatabase();
final OIndexManager indexManager = database.getMetadata().getIndexManager();
final TreeMap<String, OTransactionIndexChanges> indexOperations = getSortedIndexOperations(transaction);
database.getMetadata().makeThreadLocalSchemaSnapshot();
final Collection<ORecordOperation> recordOperations = transaction.getRecordOperations();
final TreeMap<Integer, OCluster> clustersToLock = new TreeMap<>();
final Map<ORecordOperation, Integer> clusterOverrides = new IdentityHashMap<>();
final Set<ORecordOperation> newRecords = new TreeSet<>(COMMIT_RECORD_OPERATION_COMPARATOR);
for (ORecordOperation recordOperation : recordOperations) {
if (recordOperation.type == ORecordOperation.CREATED || recordOperation.type == ORecordOperation.UPDATED) {
final ORecord record = recordOperation.getRecord();
if (record instanceof ODocument) {
((ODocument) record).validate();
}
}
if (recordOperation.type == ORecordOperation.UPDATED || recordOperation.type == ORecordOperation.DELETED) {
final int clusterId = recordOperation.getRecord().getIdentity().getClusterId();
clustersToLock.put(clusterId, getClusterById(clusterId));
} else if (recordOperation.type == ORecordOperation.CREATED) {
newRecords.add(recordOperation);
final ORecord record = recordOperation.getRecord();
final ORID rid = record.getIdentity();
int clusterId = rid.getClusterId();
if (record.isDirty() && clusterId == ORID.CLUSTER_ID_INVALID && record instanceof ODocument) {
// TRY TO FIX CLUSTER ID TO THE DEFAULT CLUSTER ID DEFINED IN SCHEMA CLASS
final OImmutableClass class_ = ODocumentInternal.getImmutableSchemaClass(((ODocument) record));
if (class_ != null) {
clusterId = class_.getClusterForNewInstance((ODocument) record);
clusterOverrides.put(recordOperation, clusterId);
}
}
clustersToLock.put(clusterId, getClusterById(clusterId));
}
}
final List<ORecordOperation> result = new ArrayList<>();
stateLock.acquireReadLock();
try {
if (modificationLock) {
List<ORID> recordLocks = new ArrayList<>();
for (ORecordOperation recordOperation : recordOperations) {
if (recordOperation.type == ORecordOperation.UPDATED || recordOperation.type == ORecordOperation.DELETED) {
recordLocks.add(recordOperation.getRID());
}
}
Set<ORID> locked = transaction.getLockedRecords();
if (locked != null) {
recordLocks.removeAll(locked);
}
Collections.sort(recordLocks);
for (ORID rid : recordLocks) {
acquireWriteLock(rid);
}
}
try {
checkOpenness();
makeStorageDirty();
boolean rollback = false;
startStorageTx(transaction);
try {
final OAtomicOperation atomicOperation = OAtomicOperationsManager.getCurrentOperation();
lockClusters(clustersToLock);
checkReadOnlyConditions();
Map<ORecordOperation, OPhysicalPosition> positions = new IdentityHashMap<>();
for (ORecordOperation recordOperation : newRecords) {
ORecord rec = recordOperation.getRecord();
if (allocated) {
if (rec.getIdentity().isPersistent()) {
positions.put(recordOperation, new OPhysicalPosition(rec.getIdentity().getClusterPosition()));
} else {
throw new OStorageException("Impossible to commit a transaction with not valid rid in pre-allocated commit");
}
} else if (rec.isDirty() && !rec.getIdentity().isPersistent()) {
ORecordId rid = (ORecordId) rec.getIdentity().copy();
ORecordId oldRID = rid.copy();
final Integer clusterOverride = clusterOverrides.get(recordOperation);
final int clusterId = clusterOverride == null ? rid.getClusterId() : clusterOverride;
final OCluster cluster = getClusterById(clusterId);
assert atomicOperation.getCounter() == 1;
OPhysicalPosition physicalPosition = cluster.allocatePosition(ORecordInternal.getRecordType(rec));
assert atomicOperation.getCounter() == 1;
rid.setClusterId(cluster.getId());
if (rid.getClusterPosition() > -1) {
// CREATE EMPTY RECORDS UNTIL THE POSITION IS REACHED. THIS IS THE CASE WHEN A SERVER IS OUT OF SYNC
// BECAUSE A TRANSACTION HAS BEEN ROLLED BACK BEFORE TO SEND THE REMOTE CREATES. SO THE OWNER NODE DELETED
// RECORD HAVING A HIGHER CLUSTER POSITION
while (rid.getClusterPosition() > physicalPosition.clusterPosition) {
assert atomicOperation.getCounter() == 1;
physicalPosition = cluster.allocatePosition(ORecordInternal.getRecordType(rec));
assert atomicOperation.getCounter() == 1;
}
if (rid.getClusterPosition() != physicalPosition.clusterPosition) {
throw new OConcurrentCreateException(rid, new ORecordId(rid.getClusterId(), physicalPosition.clusterPosition));
}
}
positions.put(recordOperation, physicalPosition);
rid.setClusterPosition(physicalPosition.clusterPosition);
transaction.updateIdentityAfterCommit(oldRID, rid);
}
}
lockRidBags(clustersToLock, indexOperations, indexManager);
checkReadOnlyConditions();
for (ORecordOperation recordOperation : recordOperations) {
assert atomicOperation.getCounter() == 1;
commitEntry(recordOperation, positions.get(recordOperation), database.getSerializer());
assert atomicOperation.getCounter() == 1;
result.add(recordOperation);
}
lockIndexes(indexOperations);
checkReadOnlyConditions();
commitIndexes(indexOperations, atomicOperation);
} catch (IOException | RuntimeException e) {
rollback = true;
if (e instanceof RuntimeException) {
throw ((RuntimeException) e);
} else {
throw OException.wrapException(new OStorageException("Error during transaction commit"), e);
}
} finally {
if (rollback) {
rollback(transaction);
} else {
endStorageTx(transaction, recordOperations);
}
this.transaction.set(null);
}
} finally {
atomicOperationsManager.ensureThatComponentsUnlocked();
database.getMetadata().clearThreadLocalSchemaSnapshot();
}
} finally {
try {
if (modificationLock) {
List<ORID> recordLocks = new ArrayList<>();
for (ORecordOperation recordOperation : recordOperations) {
if (recordOperation.type == ORecordOperation.UPDATED || recordOperation.type == ORecordOperation.DELETED) {
recordLocks.add(recordOperation.getRID());
}
}
Set<ORID> locked = transaction.getLockedRecords();
if (locked != null) {
recordLocks.removeAll(locked);
}
for (ORID rid : recordLocks) {
releaseWriteLock(rid);
}
}
} finally {
stateLock.releaseReadLock();
}
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance()
.debug(this, "%d Committed transaction %d on database '%s' (result=%s)", Thread.currentThread().getId(),
transaction.getId(), database.getName(), result);
}
return result;
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
handleJVMError(ee);
OAtomicOperationsManager.alarmClearOfAtomicOperation();
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private static void commitIndexes(final Map<String, OTransactionIndexChanges> indexesToCommit,
final OAtomicOperation atomicOperation) {
final Map<OIndex, OIndexAbstract.IndexTxSnapshot> snapshots = new IdentityHashMap<>();
for (OTransactionIndexChanges changes : indexesToCommit.values()) {
final OIndexInternal<?> index = changes.getAssociatedIndex();
final OIndexAbstract.IndexTxSnapshot snapshot = new OIndexAbstract.IndexTxSnapshot();
snapshots.put(index, snapshot);
assert atomicOperation.getCounter() == 1;
index.preCommit(snapshot);
assert atomicOperation.getCounter() == 1;
}
for (OTransactionIndexChanges changes : indexesToCommit.values()) {
final OIndexInternal<?> index = changes.getAssociatedIndex();
final OIndexAbstract.IndexTxSnapshot snapshot = snapshots.get(index);
assert atomicOperation.getCounter() == 1;
index.addTxOperation(snapshot, changes);
assert atomicOperation.getCounter() == 1;
}
try {
for (OTransactionIndexChanges changes : indexesToCommit.values()) {
final OIndexInternal<?> index = changes.getAssociatedIndex();
final OIndexAbstract.IndexTxSnapshot snapshot = snapshots.get(index);
assert atomicOperation.getCounter() == 1;
index.commit(snapshot);
assert atomicOperation.getCounter() == 1;
}
} finally {
for (OTransactionIndexChanges changes : indexesToCommit.values()) {
final OIndexInternal<?> index = changes.getAssociatedIndex();
final OIndexAbstract.IndexTxSnapshot snapshot = snapshots.get(index);
assert atomicOperation.getCounter() == 1;
index.postCommit(snapshot);
assert atomicOperation.getCounter() == 1;
}
}
}
private static TreeMap<String, OTransactionIndexChanges> getSortedIndexOperations(OTransactionInternal clientTx) {
return new TreeMap<>(clientTx.getIndexOperations());
}
public int loadIndexEngine(String name) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OIndexEngine engine = indexEngineNameMap.get(name);
if (engine == null) {
return -1;
}
final int indexId = indexEngines.indexOf(engine);
assert indexId >= 0;
return indexId;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public int loadExternalIndexEngine(String engineName, String algorithm, String indexType, OIndexDefinition indexDefinition,
OBinarySerializer valueSerializer, boolean isAutomatic, Boolean durableInNonTxMode, int version,
Map<String, String> engineProperties) {
try {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
// this method introduced for binary compatibility only
if (configuration.getBinaryFormatVersion() > 15) {
return -1;
}
if (indexEngineNameMap.containsKey(engineName)) {
throw new OIndexException("Index with name " + engineName + " already exists");
}
makeStorageDirty();
final OBinarySerializer keySerializer = determineKeySerializer(indexDefinition);
final int keySize = determineKeySize(indexDefinition);
final OType[] keyTypes = indexDefinition != null ? indexDefinition.getTypes() : null;
final boolean nullValuesSupport = indexDefinition != null && !indexDefinition.isNullValuesIgnored();
final OStorageConfigurationImpl.IndexEngineData engineData = new OStorageConfigurationImpl.IndexEngineData(engineName,
algorithm, indexType, durableInNonTxMode, version, valueSerializer.getId(), keySerializer.getId(), isAutomatic,
keyTypes, nullValuesSupport, keySize, null, null, engineProperties);
final OIndexEngine engine = OIndexes
.createIndexEngine(engineName, algorithm, indexType, durableInNonTxMode, this, version, engineProperties, null);
engine.load(engineName, valueSerializer, isAutomatic, keySerializer, keyTypes, nullValuesSupport, keySize,
engineData.getEngineProperties(), null);
indexEngineNameMap.put(engineName, engine);
indexEngines.add(engine);
((OStorageConfigurationImpl) configuration).addIndexEngine(engineName, engineData);
return indexEngines.size() - 1;
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot add index engine " + engineName + " in storage."), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public int addIndexEngine(String engineName, final String algorithm, final String indexType,
final OIndexDefinition indexDefinition, final OBinarySerializer valueSerializer, final boolean isAutomatic,
final Boolean durableInNonTxMode, final int version, final Map<String, String> engineProperties,
final Set<String> clustersToIndex, final ODocument metadata) {
try {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
if (indexEngineNameMap.containsKey(engineName)) {
// OLD INDEX FILE ARE PRESENT: THIS IS THE CASE OF PARTIAL/BROKEN INDEX
OLogManager.instance().warn(this, "Index with name '%s' already exists, removing it and re-create the index", engineName);
final OIndexEngine engine = indexEngineNameMap.remove(engineName);
if (engine != null) {
indexEngines.remove(engine);
((OStorageConfigurationImpl) configuration).deleteIndexEngine(engineName);
engine.delete();
}
}
makeStorageDirty();
final OBinarySerializer keySerializer = determineKeySerializer(indexDefinition);
final int keySize = determineKeySize(indexDefinition);
final OType[] keyTypes = indexDefinition != null ? indexDefinition.getTypes() : null;
final boolean nullValuesSupport = indexDefinition != null && !indexDefinition.isNullValuesIgnored();
final byte serializerId;
if (valueSerializer != null) {
serializerId = valueSerializer.getId();
} else {
serializerId = -1;
}
final OIndexEngine engine = OIndexes
.createIndexEngine(engineName, algorithm, indexType, durableInNonTxMode, this, version, engineProperties, metadata);
final OContextConfiguration ctxCfg = getConfiguration().getContextConfiguration();
final String cfgEncryption = ctxCfg.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD);
final String cfgEncryptionKey = ctxCfg.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY);
final OEncryption encryption;
if (cfgEncryption == null || cfgEncryption.equals(ONothingEncryption.NAME)) {
encryption = null;
} else {
encryption = OEncryptionFactory.INSTANCE.getEncryption(cfgEncryption, cfgEncryptionKey);
}
engine.create(valueSerializer, isAutomatic, keyTypes, nullValuesSupport, keySerializer, keySize, clustersToIndex,
engineProperties, metadata, encryption);
if (writeAheadLog != null) {
writeAheadLog.flush();
}
indexEngineNameMap.put(engineName, engine);
indexEngines.add(engine);
final OStorageConfigurationImpl.IndexEngineData engineData = new OStorageConfigurationImpl.IndexEngineData(engineName,
algorithm, indexType, durableInNonTxMode, version, serializerId, keySerializer.getId(), isAutomatic, keyTypes,
nullValuesSupport, keySize, cfgEncryption, cfgEncryptionKey, engineProperties);
((OStorageConfigurationImpl) configuration).addIndexEngine(engineName, engineData);
return indexEngines.size() - 1;
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot add index engine " + engineName + " in storage."), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private static int determineKeySize(OIndexDefinition indexDefinition) {
if (indexDefinition == null || indexDefinition instanceof ORuntimeKeyIndexDefinition) {
return 1;
} else {
return indexDefinition.getTypes().length;
}
}
private OBinarySerializer determineKeySerializer(OIndexDefinition indexDefinition) {
final OBinarySerializer keySerializer;
if (indexDefinition != null) {
if (indexDefinition instanceof ORuntimeKeyIndexDefinition) {
keySerializer = ((ORuntimeKeyIndexDefinition) indexDefinition).getSerializer();
} else {
if (indexDefinition.getTypes().length > 1) {
keySerializer = OCompositeKeySerializer.INSTANCE;
} else {
final OType keyType = indexDefinition.getTypes()[0];
if (keyType == OType.STRING && configuration.getBinaryFormatVersion() >= 13) {
return OUTF8Serializer.INSTANCE;
}
OCurrentStorageComponentsFactory currentStorageComponentsFactory = componentsFactory;
if (currentStorageComponentsFactory != null) {
keySerializer = currentStorageComponentsFactory.binarySerializerFactory.getObjectSerializer(keyType);
} else {
throw new IllegalStateException("Cannot load binary serializer, storage is not properly initialized");
}
}
}
} else {
keySerializer = new OSimpleKeySerializer();
}
return keySerializer;
}
public void deleteIndexEngine(int indexId) throws OInvalidIndexEngineIdException {
try {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
checkIndexId(indexId);
makeStorageDirty();
final OIndexEngine engine = indexEngines.get(indexId);
indexEngines.set(indexId, null);
engine.delete();
final String engineName = engine.getName();
indexEngineNameMap.remove(engineName);
((OStorageConfigurationImpl) configuration).deleteIndexEngine(engineName);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error on index deletion"), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private void checkIndexId(int indexId) throws OInvalidIndexEngineIdException {
if (indexId < 0 || indexId >= indexEngines.size() || indexEngines.get(indexId) == null) {
throw new OInvalidIndexEngineIdException("Engine with id " + indexId + " is not registered inside of storage");
}
}
public boolean indexContainsKey(int indexId, Object key) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doIndexContainsKey(indexId, key);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doIndexContainsKey(indexId, key);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private boolean doIndexContainsKey(int indexId, Object key) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.contains(key);
}
public boolean removeKeyFromIndex(int indexId, Object key) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doRemoveKeyFromIndex(indexId, key);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
return doRemoveKeyFromIndex(indexId, key);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private boolean doRemoveKeyFromIndex(int indexId, Object key) throws OInvalidIndexEngineIdException {
try {
checkIndexId(indexId);
makeStorageDirty();
final OIndexEngine engine = indexEngines.get(indexId);
return engine.remove(key);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during removal of entry with key " + key + " from index "), e);
}
}
public void clearIndex(int indexId) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
doClearIndex(indexId);
return;
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
doClearIndex(indexId);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private void doClearIndex(int indexId) throws OInvalidIndexEngineIdException {
try {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
makeStorageDirty();
engine.clear();
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during clearing of index"), e);
}
}
public Object getIndexValue(int indexId, Object key) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexValue(indexId, key);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexValue(indexId, key);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private Object doGetIndexValue(int indexId, Object key) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.get(key);
}
public OIndexEngine getIndexEngine(int indexId) throws OInvalidIndexEngineIdException {
try {
checkIndexId(indexId);
return indexEngines.get(indexId);
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public void updateIndexEntry(int indexId, Object key, OIndexKeyUpdater<Object> valueCreator)
throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
doUpdateIndexEntry(indexId, key, valueCreator);
return;
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
doUpdateIndexEntry(indexId, key, valueCreator);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public <T> T callIndexEngine(boolean atomicOperation, boolean readOperation, int indexId, OIndexEngineCallback<T> callback)
throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doCallIndexEngine(atomicOperation, readOperation, indexId, callback);
}
checkOpenness();
stateLock.acquireReadLock();
try {
return doCallIndexEngine(atomicOperation, readOperation, indexId, callback);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private <T> T doCallIndexEngine(boolean atomicOperation, boolean readOperation, int indexId, OIndexEngineCallback<T> callback)
throws OInvalidIndexEngineIdException, IOException {
checkIndexId(indexId);
boolean rollback = false;
if (atomicOperation) {
atomicOperationsManager.startAtomicOperation((String) null, true);
}
try {
if (!readOperation) {
makeStorageDirty();
}
final OIndexEngine engine = indexEngines.get(indexId);
return callback.callEngine(engine);
} catch (Exception e) {
rollback = true;
throw OException.wrapException(new OStorageException("Cannot put key value entry in index"), e);
} finally {
if (atomicOperation) {
atomicOperationsManager.endAtomicOperation(rollback);
}
}
}
private void doUpdateIndexEntry(int indexId, Object key, OIndexKeyUpdater<Object> valueCreator)
throws OInvalidIndexEngineIdException, IOException {
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
makeStorageDirty();
engine.update(key, valueCreator);
} catch (Exception e) {
rollback = true;
throw e;
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
}
public void putIndexValue(int indexId, Object key, Object value) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
doPutIndexValue(indexId, key, value);
return;
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
doPutIndexValue(indexId, key, value);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private void doPutIndexValue(int indexId, Object key, Object value) throws OInvalidIndexEngineIdException {
try {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
makeStorageDirty();
engine.put(key, value);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot put key " + key + " value " + value + " entry to the index"), e);
}
}
/**
* Puts the given value under the given key into this storage for the index with the given index id. Validates the operation using
* the provided validator.
*
* @param indexId the index id of the index to put the value into.
* @param key the key to put the value under.
* @param value the value to put.
* @param validator the operation validator.
*
* @return {@code true} if the validator allowed the put, {@code false} otherwise.
*
* @see OIndexEngine.Validator#validate(Object, Object, Object)
*/
@SuppressWarnings("UnusedReturnValue")
public boolean validatedPutIndexValue(int indexId, Object key, OIdentifiable value,
OIndexEngine.Validator<Object, OIdentifiable> validator) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doValidatedPutIndexValue(indexId, key, value, validator);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
return doValidatedPutIndexValue(indexId, key, value, validator);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private boolean doValidatedPutIndexValue(int indexId, Object key, OIdentifiable value,
OIndexEngine.Validator<Object, OIdentifiable> validator) throws OInvalidIndexEngineIdException {
try {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
makeStorageDirty();
return engine.validatedPut(key, value, validator);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot put key " + key + " value " + value + " entry to the index"), e);
}
}
public Object getIndexFirstKey(int indexId) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexFirstKey(indexId);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexFirstKey(indexId);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private Object doGetIndexFirstKey(int indexId) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.getFirstKey();
}
public Object getIndexLastKey(int indexId) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexFirstKey(indexId);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexLastKey(indexId);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private Object doGetIndexLastKey(int indexId) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.getLastKey();
}
public OIndexCursor iterateIndexEntriesBetween(int indexId, Object rangeFrom, boolean fromInclusive, Object rangeTo,
boolean toInclusive, boolean ascSortOrder, OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doIterateIndexEntriesBetween(indexId, rangeFrom, fromInclusive, rangeTo, toInclusive, ascSortOrder, transformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doIterateIndexEntriesBetween(indexId, rangeFrom, fromInclusive, rangeTo, toInclusive, ascSortOrder, transformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexCursor doIterateIndexEntriesBetween(int indexId, Object rangeFrom, boolean fromInclusive, Object rangeTo,
boolean toInclusive, boolean ascSortOrder, OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.iterateEntriesBetween(rangeFrom, fromInclusive, rangeTo, toInclusive, ascSortOrder, transformer);
}
public OIndexCursor iterateIndexEntriesMajor(int indexId, Object fromKey, boolean isInclusive, boolean ascSortOrder,
OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doIterateIndexEntriesMajor(indexId, fromKey, isInclusive, ascSortOrder, transformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doIterateIndexEntriesMajor(indexId, fromKey, isInclusive, ascSortOrder, transformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexCursor doIterateIndexEntriesMajor(int indexId, Object fromKey, boolean isInclusive, boolean ascSortOrder,
OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.iterateEntriesMajor(fromKey, isInclusive, ascSortOrder, transformer);
}
public OIndexCursor iterateIndexEntriesMinor(int indexId, final Object toKey, final boolean isInclusive, boolean ascSortOrder,
OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doIterateIndexEntriesMinor(indexId, toKey, isInclusive, ascSortOrder, transformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doIterateIndexEntriesMinor(indexId, toKey, isInclusive, ascSortOrder, transformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexCursor doIterateIndexEntriesMinor(int indexId, Object toKey, boolean isInclusive, boolean ascSortOrder,
OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.iterateEntriesMinor(toKey, isInclusive, ascSortOrder, transformer);
}
public OIndexCursor getIndexCursor(int indexId, OIndexEngine.ValuesTransformer valuesTransformer)
throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexCursor(indexId, valuesTransformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexCursor(indexId, valuesTransformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexCursor doGetIndexCursor(int indexId, OIndexEngine.ValuesTransformer valuesTransformer)
throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.cursor(valuesTransformer);
}
public OIndexCursor getIndexDescCursor(int indexId, OIndexEngine.ValuesTransformer valuesTransformer)
throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexDescCursor(indexId, valuesTransformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexDescCursor(indexId, valuesTransformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexCursor doGetIndexDescCursor(int indexId, OIndexEngine.ValuesTransformer valuesTransformer)
throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.descCursor(valuesTransformer);
}
public OIndexKeyCursor getIndexKeyCursor(int indexId) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexKeyCursor(indexId);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexKeyCursor(indexId);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexKeyCursor doGetIndexKeyCursor(int indexId) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.keyCursor();
}
public long getIndexSize(int indexId, OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexSize(indexId, transformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexSize(indexId, transformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private long doGetIndexSize(int indexId, OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.size(transformer);
}
public boolean hasIndexRangeQuerySupport(int indexId) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doHasRangeQuerySupport(indexId);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doHasRangeQuerySupport(indexId);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private boolean doHasRangeQuerySupport(int indexId) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.hasRangeQuerySupport();
}
@Override
public void rollback(final OTransactionInternal clientTx) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
try {
checkOpenness();
assert transaction.get() != null;
if (transaction.get().getClientTx().getId() != clientTx.getId()) {
throw new OStorageException(
"Passed in and active transaction are different transactions. Passed in transaction cannot be rolled back.");
}
makeStorageDirty();
rollbackStorageTx();
OTransactionAbstract.updateCacheFromEntries(clientTx.getDatabase(), clientTx.getRecordOperations(), false);
txRollback.incrementAndGet();
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during transaction rollback"), e);
} finally {
transaction.set(null);
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Rollbacks the given micro-transaction.
*
* @param microTransaction the micro-transaction to rollback.
*/
public void rollback(OMicroTransaction microTransaction) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
try {
checkOpenness();
if (transaction.get() == null) {
return;
}
if (transaction.get().getMicroTransaction().getId() != microTransaction.getId()) {
throw new OStorageException(
"Passed in and active micro-transaction are different micro-transactions. Passed in micro-transaction cannot be "
+ "rolled back.");
}
makeStorageDirty();
rollbackStorageTx();
microTransaction.updateRecordCacheAfterRollback();
txRollback.incrementAndGet();
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during micro-transaction rollback"), e);
} finally {
transaction.set(null);
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final boolean checkForRecordValidity(final OPhysicalPosition ppos) {
try {
return ppos != null && !ORecordVersionHelper.isTombstone(ppos.recordVersion);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final void synch() {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
final long timer = Orient.instance().getProfiler().startChrono();
final long lockId = atomicOperationsManager.freezeAtomicOperations(null, null);
try {
checkOpenness();
if (jvmError.get() == null) {
for (OIndexEngine indexEngine : indexEngines) {
try {
if (indexEngine != null) {
indexEngine.flush();
}
} catch (Throwable t) {
OLogManager.instance().error(this, "Error while flushing index via index engine of class %s.", t,
indexEngine.getClass().getSimpleName());
}
}
if (writeAheadLog != null) {
makeFullCheckpoint();
return;
}
writeCache.flush();
clearStorageDirty();
} else {
OLogManager.instance().errorNoDb(this, "Sync can not be performed because of JVM error on storage", null);
}
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error on synch storage '" + name + "'"), e);
} finally {
atomicOperationsManager.releaseAtomicOperations(lockId);
//noinspection ResultOfMethodCallIgnored
Orient.instance().getProfiler().stopChrono("db." + name + ".synch", "Synch a database", timer, "db.*.synch");
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final String getPhysicalClusterNameById(final int iClusterId) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
if (iClusterId < 0 || iClusterId >= clusters.size()) {
return null;
}
return clusters.get(iClusterId) != null ? clusters.get(iClusterId).getName() : null;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int getDefaultClusterId() {
return defaultClusterId;
}
@Override
public final void setDefaultClusterId(final int defaultClusterId) {
this.defaultClusterId = defaultClusterId;
}
@Override
public final OCluster getClusterById(int iClusterId) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
if (iClusterId == ORID.CLUSTER_ID_INVALID)
// GET THE DEFAULT CLUSTER
{
iClusterId = defaultClusterId;
}
final OCluster cluster = doGetAndCheckCluster(iClusterId);
return cluster;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OCluster getClusterByName(final String clusterName) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = clusterMap.get(clusterName.toLowerCase(configuration.getLocaleInstance()));
if (cluster == null) {
throw new OStorageException("Cluster " + clusterName + " does not exist in database '" + name + "'");
}
return cluster;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final long getSize() {
try {
try {
long size = 0;
stateLock.acquireReadLock();
try {
for (OCluster c : clusters) {
if (c != null) {
size += c.getRecordsSize();
}
}
} finally {
stateLock.releaseReadLock();
}
return size;
} catch (IOException ioe) {
throw OException.wrapException(new OStorageException("Cannot calculate records size"), ioe);
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int getClusters() {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return clusterMap.size();
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final Set<OCluster> getClusterInstances() {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final Set<OCluster> result = new HashSet<>();
// ADD ALL THE CLUSTERS
for (OCluster c : clusters) {
if (c != null) {
result.add(c);
}
}
return result;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Method that completes the cluster rename operation. <strong>IT WILL NOT RENAME A CLUSTER, IT JUST CHANGES THE NAME IN THE
* INTERNAL MAPPING</strong>
*/
public void renameCluster(final String oldName, final String newName) {
try {
clusterMap.put(newName.toLowerCase(configuration.getLocaleInstance()),
clusterMap.remove(oldName.toLowerCase(configuration.getLocaleInstance())));
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final boolean cleanOutRecord(final ORecordId recordId, final int recordVersion, final int iMode,
final ORecordCallback<Boolean> callback) {
return deleteRecord(recordId, recordVersion, iMode, callback).getResult();
}
@Override
public final boolean isFrozen() {
try {
return atomicOperationsManager.isFrozen();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final void freeze(final boolean throwException) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
if (throwException) {
atomicOperationsManager
.freezeAtomicOperations(OModificationOperationProhibitedException.class, "Modification requests are prohibited");
} else {
atomicOperationsManager.freezeAtomicOperations(null, null);
}
final List<OFreezableStorageComponent> frozenIndexes = new ArrayList<>(indexEngines.size());
try {
for (OIndexEngine indexEngine : indexEngines) {
if (indexEngine instanceof OFreezableStorageComponent) {
((OFreezableStorageComponent) indexEngine).freeze(false);
frozenIndexes.add((OFreezableStorageComponent) indexEngine);
}
}
} catch (Exception e) {
// RELEASE ALL THE FROZEN INDEXES
for (OFreezableStorageComponent indexEngine : frozenIndexes) {
indexEngine.release();
}
throw OException.wrapException(new OStorageException("Error on freeze of storage '" + name + "'"), e);
}
synch();
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final void release() {
try {
for (OIndexEngine indexEngine : indexEngines) {
if (indexEngine instanceof OFreezableStorageComponent) {
((OFreezableStorageComponent) indexEngine).release();
}
}
atomicOperationsManager.releaseAtomicOperations(-1);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final boolean isRemote() {
return false;
}
public boolean wereDataRestoredAfterOpen() {
return wereDataRestoredAfterOpen;
}
public boolean wereNonTxOperationsPerformedInPreviousOpen() {
return wereNonTxOperationsPerformedInPreviousOpen;
}
@Override
public final void reload() {
try {
close();
open(null, null, null);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@SuppressWarnings("unused")
public String getMode() {
return mode;
}
@Override
public final void lowDiskSpace(OLowDiskSpaceInformation information) {
lowDiskSpace = information;
}
/**
* @inheritDoc
*/
@Override
public final void pageIsBroken(String fileName, long pageIndex) {
brokenPages.add(new OPair<>(fileName, pageIndex));
}
@Override
public final void requestCheckpoint() {
try {
if (!walVacuumInProgress.get() && walVacuumInProgress.compareAndSet(false, true)) {
fuzzyCheckpointExecutor.submit(new WALVacuum());
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Executes the command request and return the result back.
*/
@Override
public final Object command(final OCommandRequestText iCommand) {
try {
while (true) {
try {
final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand);
// COPY THE CONTEXT FROM THE REQUEST
executor.setContext(iCommand.getContext());
executor.setProgressListener(iCommand.getProgressListener());
executor.parse(iCommand);
return executeCommand(iCommand, executor);
} catch (ORetryQueryException ignore) {
if (iCommand instanceof OQueryAbstract) {
final OQueryAbstract query = (OQueryAbstract) iCommand;
query.reset();
}
}
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee, false);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@SuppressWarnings("WeakerAccess")
public final Object executeCommand(final OCommandRequestText iCommand, final OCommandExecutor executor) {
try {
if (iCommand.isIdempotent() && !executor.isIdempotent()) {
throw new OCommandExecutionException("Cannot execute non idempotent command");
}
long beginTime = Orient.instance().getProfiler().startChrono();
try {
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().get();
// CALL BEFORE COMMAND
Iterable<ODatabaseListener> listeners = db.getListeners();
for (ODatabaseListener oDatabaseListener : listeners) {
oDatabaseListener.onBeforeCommand(iCommand, executor);
}
boolean foundInCache = false;
Object result = null;
if (iCommand.isCacheableResult() && executor.isCacheable() && iCommand.getParameters() == null) {
// TRY WITH COMMAND CACHE
result = db.getMetadata().getCommandCache().get(db.getUser(), iCommand.getText(), iCommand.getLimit());
if (result != null) {
foundInCache = true;
if (iCommand.getResultListener() != null) {
// INVOKE THE LISTENER IF ANY
if (result instanceof Collection) {
for (Object o : (Collection) result) {
iCommand.getResultListener().result(o);
}
} else {
iCommand.getResultListener().result(result);
}
// RESET THE RESULT TO AVOID TO SEND IT TWICE
result = null;
}
}
}
if (!foundInCache) {
// EXECUTE THE COMMAND
Map<Object, Object> params = iCommand.getParameters();
result = executor.execute(params);
if (result != null && iCommand.isCacheableResult() && executor.isCacheable() && (iCommand.getParameters() == null
|| iCommand.getParameters().isEmpty()))
// CACHE THE COMMAND RESULT
{
db.getMetadata().getCommandCache()
.put(db.getUser(), iCommand.getText(), result, iCommand.getLimit(), executor.getInvolvedClusters(),
System.currentTimeMillis() - beginTime);
}
}
// CALL AFTER COMMAND
for (ODatabaseListener oDatabaseListener : listeners) {
oDatabaseListener.onAfterCommand(iCommand, executor, result);
}
return result;
} catch (OException e) {
// PASS THROUGH
throw e;
} catch (Exception e) {
throw OException.wrapException(new OCommandExecutionException("Error on execution of command: " + iCommand), e);
} finally {
if (Orient.instance().getProfiler().isRecording()) {
final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db != null) {
final OSecurityUser user = db.getUser();
final String userString = user != null ? user.toString() : null;
//noinspection ResultOfMethodCallIgnored
Orient.instance().getProfiler()
.stopChrono("db." + ODatabaseRecordThreadLocal.instance().get().getName() + ".command." + iCommand.toString(),
"Command executed against the database", beginTime, "db.*.command.*", null, userString);
}
}
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee, false);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OPhysicalPosition[] higherPhysicalPositions(int currentClusterId, OPhysicalPosition physicalPosition) {
try {
if (currentClusterId == -1) {
return new OPhysicalPosition[0];
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = getClusterById(currentClusterId);
return cluster.higherPositions(physicalPosition);
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Cluster Id " + currentClusterId + " is invalid in storage '" + name + '\''), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OPhysicalPosition[] ceilingPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) {
try {
if (clusterId == -1) {
return new OPhysicalPosition[0];
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = getClusterById(clusterId);
return cluster.ceilingPositions(physicalPosition);
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Cluster Id " + clusterId + " is invalid in storage '" + name + '\''), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OPhysicalPosition[] lowerPhysicalPositions(int currentClusterId, OPhysicalPosition physicalPosition) {
try {
if (currentClusterId == -1) {
return new OPhysicalPosition[0];
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = getClusterById(currentClusterId);
return cluster.lowerPositions(physicalPosition);
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Cluster Id " + currentClusterId + " is invalid in storage '" + name + '\''), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OPhysicalPosition[] floorPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) {
try {
if (clusterId == -1) {
return new OPhysicalPosition[0];
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = getClusterById(clusterId);
return cluster.floorPositions(physicalPosition);
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Cluster Id " + clusterId + " is invalid in storage '" + name + '\''), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public void acquireWriteLock(final ORID rid, long timeout) {
if (!modificationLock) {
throw new ODatabaseException(
"Record write locks are off by configuration, set the configuration \"storage.pessimisticLock\" to \""
+ OrientDBConfig.LOCK_TYPE_READWRITE + "\" for enable them");
}
try {
lockManager.acquireWriteLock(rid, timeout);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final void acquireWriteLock(final ORID rid) {
if (!modificationLock) {
throw new ODatabaseException(
"Record write locks are off by configuration, set the configuration \"storage.pessimisticLock\" to \""
+ OrientDBConfig.LOCK_TYPE_MODIFICATION + "\" for enable them");
}
try {
lockManager.acquireWriteLock(rid, 0);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final void releaseWriteLock(final ORID rid) {
try {
lockManager.releaseWriteLock(rid);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final void acquireReadLock(final ORID rid) {
if (!readLock) {
throw new ODatabaseException(
"Record read locks are off by configuration, set the configuration \"storage.pessimisticLock\" to \""
+ OrientDBConfig.LOCK_TYPE_READWRITE + "\" for enable them");
}
try {
lockManager.acquireReadLock(rid, 0);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public void acquireReadLock(final ORID rid, long timeout) {
if (!readLock) {
throw new ODatabaseException(
"Record read locks are off by configuration, set the configuration \"storage.pessimisticLock\" to \""
+ OrientDBConfig.LOCK_TYPE_READWRITE + "\" for enable them");
}
try {
lockManager.acquireReadLock(rid, timeout);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final void releaseReadLock(final ORID rid) {
try {
lockManager.releaseReadLock(rid);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final ORecordConflictStrategy getConflictStrategy() {
return recordConflictStrategy;
}
@Override
public final void setConflictStrategy(final ORecordConflictStrategy conflictResolver) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
this.recordConflictStrategy = conflictResolver;
((OStorageConfigurationImpl) configuration).setConflictStrategy(conflictResolver.getName());
} finally {
stateLock.releaseWriteLock();
}
}
@SuppressWarnings("unused")
public AtomicLong getRecordScanned() {
return recordScanned;
}
@SuppressWarnings("unused")
protected abstract OLogSequenceNumber copyWALToIncrementalBackup(ZipOutputStream zipOutputStream, long startSegment)
throws IOException;
@SuppressWarnings("unused")
protected abstract boolean isWriteAllowedDuringIncrementalBackup();
@SuppressWarnings("unused")
public OStorageRecoverListener getRecoverListener() {
return recoverListener;
}
public void registerRecoverListener(final OStorageRecoverListener recoverListener) {
this.recoverListener = recoverListener;
}
@SuppressWarnings("unused")
public void unregisterRecoverListener(final OStorageRecoverListener recoverListener) {
if (this.recoverListener == recoverListener) {
this.recoverListener = null;
}
}
@SuppressWarnings("unused")
protected abstract File createWalTempDirectory();
@SuppressWarnings("unused")
protected abstract void addFileToDirectory(String name, InputStream stream, File directory) throws IOException;
@SuppressWarnings("unused")
protected abstract OWriteAheadLog createWalFromIBUFiles(File directory) throws IOException;
/**
* Checks if the storage is open. If it's closed an exception is raised.
*/
@SuppressWarnings("WeakerAccess")
protected final void checkOpenness() {
if (status != STATUS.OPEN) {
throw new OStorageException("Storage " + name + " is not opened.");
}
}
protected void makeFuzzyCheckpoint() {
if (writeAheadLog == null) {
return;
}
//check every 1 ms.
while (!stateLock.tryAcquireReadLock(1_000_000)) {
if (status != STATUS.OPEN) {
return;
}
}
try {
if (status != STATUS.OPEN || writeAheadLog == null) {
return;
}
OLogSequenceNumber beginLSN = writeAheadLog.begin();
OLogSequenceNumber endLSN = writeAheadLog.end();
final Long minLSNSegment = writeCache.getMinimalNotFlushedSegment();
final long fuzzySegment;
if (minLSNSegment != null) {
fuzzySegment = minLSNSegment;
} else {
if (endLSN == null) {
return;
}
fuzzySegment = endLSN.getSegment();
}
OLogManager.instance().debugNoDb(this,
"Before fuzzy checkpoint: min LSN segment is " + minLSNSegment + ", WAL begin is " + beginLSN + ", WAL end is " + endLSN
+ ", fuzzy segment is " + fuzzySegment, null);
if (fuzzySegment > beginLSN.getSegment() && beginLSN.getSegment() < endLSN.getSegment()) {
OLogManager.instance().infoNoDb(this, "Making fuzzy checkpoint");
writeCache.makeFuzzyCheckpoint(fuzzySegment);
beginLSN = writeAheadLog.begin();
endLSN = writeAheadLog.end();
OLogManager.instance().debugNoDb(this, "After fuzzy checkpoint: WAL begin is " + beginLSN + " WAL end is " + endLSN, null);
} else {
OLogManager.instance().debugNoDb(this, "No reason to make fuzzy checkpoint", null);
}
} catch (IOException ioe) {
throw OException.wrapException(new OIOException("Error during fuzzy checkpoint"), ioe);
} finally {
stateLock.releaseReadLock();
}
}
protected void makeFullCheckpoint() {
final OSessionStoragePerformanceStatistic statistic = performanceStatisticManager.getSessionPerformanceStatistic();
if (statistic != null) {
statistic.startFullCheckpointTimer();
}
try {
if (writeAheadLog == null) {
return;
}
try {
writeAheadLog.flush();
//so we will be able to cut almost all the log
writeAheadLog.appendNewSegment();
final OLogSequenceNumber lastLSN = writeAheadLog.logFullCheckpointStart();
writeCache.flush();
writeAheadLog.logFullCheckpointEnd();
writeAheadLog.flush();
writeAheadLog.cutTill(lastLSN);
if (jvmError.get() == null) {
clearStorageDirty();
}
} catch (IOException ioe) {
throw OException.wrapException(new OStorageException("Error during checkpoint creation for storage " + name), ioe);
}
fullCheckpointCount.increment();
} finally {
if (statistic != null) {
statistic.stopFullCheckpointTimer();
}
}
}
public long getFullCheckpointCount() {
return fullCheckpointCount.sum();
}
protected void preOpenSteps() throws IOException {
}
@SuppressWarnings({ "WeakerAccess", "EmptyMethod" })
protected final void postCreateSteps() {
}
protected void preCreateSteps() throws IOException {
}
protected abstract void initWalAndDiskCache(OContextConfiguration contextConfiguration) throws IOException, InterruptedException;
protected abstract void postCloseSteps(@SuppressWarnings("unused") boolean onDelete, boolean jvmError) throws IOException;
@SuppressWarnings("EmptyMethod")
protected void postCloseStepsAfterLock(Map<String, Object> params) {
}
@SuppressWarnings({ "EmptyMethod", "WeakerAccess" })
protected Map<String, Object> preCloseSteps() {
return new HashMap<>();
}
protected void postDeleteSteps() {
}
protected void makeStorageDirty() throws IOException {
}
protected void clearStorageDirty() throws IOException {
}
protected boolean isDirty() {
return false;
}
private ORawBuffer readRecordIfNotLatest(final OCluster cluster, final ORecordId rid, final int recordVersion)
throws ORecordNotFoundException {
checkOpenness();
if (!rid.isPersistent()) {
throw new ORecordNotFoundException(rid,
"Cannot read record " + rid + " since the position is invalid in database '" + name + '\'');
}
if (transaction.get() != null) {
return doReadRecordIfNotLatest(cluster, rid, recordVersion);
}
stateLock.acquireReadLock();
try {
if (readLock) {
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db == null || !((OTransactionAbstract) db.getTransaction()).getLockedRecords().contains(rid)) {
acquireReadLock(rid);
}
}
ORawBuffer buff;
checkOpenness();
buff = doReadRecordIfNotLatest(cluster, rid, recordVersion);
return buff;
} finally {
try {
if (readLock) {
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db == null || !((OTransactionAbstract) db.getTransaction()).getLockedRecords().contains(rid)) {
releaseReadLock(rid);
}
}
} finally {
stateLock.releaseReadLock();
}
}
}
private ORawBuffer readRecord(final OCluster clusterSegment, final ORecordId rid, boolean prefetchRecords) {
checkOpenness();
if (!rid.isPersistent()) {
throw new ORecordNotFoundException(rid,
"Cannot read record " + rid + " since the position is invalid in database '" + name + '\'');
}
if (transaction.get() != null) {
// Disabled this assert have no meaning anymore
// assert iLockingStrategy.equals(LOCKING_STRATEGY.DEFAULT);
return doReadRecord(clusterSegment, rid, prefetchRecords);
}
stateLock.acquireReadLock();
try {
if (readLock) {
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db == null || !((OTransactionAbstract) db.getTransaction()).getLockedRecords().contains(rid)) {
acquireReadLock(rid);
}
}
checkOpenness();
return doReadRecord(clusterSegment, rid, prefetchRecords);
} finally {
try {
if (readLock) {
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db == null || !((OTransactionAbstract) db.getTransaction()).getLockedRecords().contains(rid)) {
releaseReadLock(rid);
}
}
} finally {
stateLock.releaseReadLock();
}
}
}
private void endStorageTx(final OTransactionInternal txi, final Collection<ORecordOperation> recordOperations)
throws IOException {
atomicOperationsManager.endAtomicOperation(false);
assert OAtomicOperationsManager.getCurrentOperation() == null;
OTransactionAbstract.updateCacheFromEntries(txi.getDatabase(), recordOperations, true);
txCommit.incrementAndGet();
}
private void startStorageTx(OTransactionInternal clientTx) throws IOException {
final OStorageTransaction storageTx = transaction.get();
assert storageTx == null || storageTx.getClientTx().getId() == clientTx.getId();
assert OAtomicOperationsManager.getCurrentOperation() == null;
transaction.set(new OStorageTransaction(clientTx));
try {
atomicOperationsManager.startAtomicOperation((String) null, true);
} catch (RuntimeException e) {
transaction.set(null);
throw e;
}
}
private void rollbackStorageTx() throws IOException {
assert transaction.get() != null;
atomicOperationsManager.endAtomicOperation(true);
assert OAtomicOperationsManager.getCurrentOperation() == null;
}
private void recoverIfNeeded() throws Exception {
if (isDirty()) {
OLogManager.instance().warn(this, "Storage '" + name + "' was not closed properly. Will try to recover from write ahead log");
try {
wereDataRestoredAfterOpen = restoreFromWAL() != null;
if (recoverListener != null) {
recoverListener.onStorageRecover();
}
makeFullCheckpoint();
} catch (Exception e) {
OLogManager.instance().error(this, "Exception during storage data restore", e);
throw e;
}
OLogManager.instance().info(this, "Storage data recover was completed");
}
}
private OStorageOperationResult<OPhysicalPosition> doCreateRecord(final ORecordId rid, final byte[] content, int recordVersion,
final byte recordType, final ORecordCallback<Long> callback, final OCluster cluster, final OPhysicalPosition allocated) {
if (content == null) {
throw new IllegalArgumentException("Record is null");
}
try {
if (recordVersion > -1) {
recordVersion++;
} else {
recordVersion = 0;
}
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
OPhysicalPosition ppos;
try {
ppos = cluster.createRecord(content, recordVersion, recordType, allocated);
rid.setClusterPosition(ppos.clusterPosition);
final ORecordSerializationContext context = ORecordSerializationContext.getContext();
if (context != null) {
context.executeOperations(this);
}
} catch (Exception e) {
rollback = true;
OLogManager.instance().error(this, "Error on creating record in cluster: " + cluster, e);
throw ODatabaseException.wrapException(new OStorageException("Error during creation of record"), e);
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
if (callback != null) {
callback.call(rid, ppos.clusterPosition);
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance().debug(this, "Created record %s v.%s size=%d bytes", rid, recordVersion, content.length);
}
recordCreated.incrementAndGet();
return new OStorageOperationResult<>(ppos);
} catch (IOException ioe) {
throw OException.wrapException(
new OStorageException("Error during record deletion in cluster " + (cluster != null ? cluster.getName() : "")), ioe);
}
}
private OStorageOperationResult<Integer> doUpdateRecord(final ORecordId rid, final boolean updateContent, byte[] content,
final int version, final byte recordType, final ORecordCallback<Integer> callback, final OCluster cluster) {
Orient.instance().getProfiler().startChrono();
try {
final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition()));
if (!checkForRecordValidity(ppos)) {
final int recordVersion = -1;
if (callback != null) {
callback.call(rid, recordVersion);
}
return new OStorageOperationResult<>(recordVersion);
}
boolean contentModified = false;
if (updateContent) {
final AtomicInteger recVersion = new AtomicInteger(version);
final AtomicInteger dbVersion = new AtomicInteger(ppos.recordVersion);
final byte[] newContent = checkAndIncrementVersion(cluster, rid, recVersion, dbVersion, content, recordType);
ppos.recordVersion = dbVersion.get();
// REMOVED BECAUSE DISTRIBUTED COULD UNDO AN OPERATION RESTORING A LOWER VERSION
// assert ppos.recordVersion >= oldVersion;
if (newContent != null) {
contentModified = true;
content = newContent;
}
}
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
if (updateContent) {
cluster.updateRecord(rid.getClusterPosition(), content, ppos.recordVersion, recordType);
}
final ORecordSerializationContext context = ORecordSerializationContext.getContext();
if (context != null) {
context.executeOperations(this);
}
} catch (Exception e) {
rollback = true;
OLogManager.instance().error(this, "Error on updating record " + rid + " (cluster: " + cluster + ")", e);
throw OException
.wrapException(new OStorageException("Error on updating record " + rid + " (cluster: " + cluster.getName() + ")"), e);
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
//if we do not update content of the record we should keep version of the record the same
//otherwise we would have issues when two records may have the same version but different content
int newRecordVersion;
if (updateContent) {
newRecordVersion = ppos.recordVersion;
} else {
newRecordVersion = version;
}
if (callback != null) {
callback.call(rid, newRecordVersion);
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance().debug(this, "Updated record %s v.%s size=%d", rid, newRecordVersion, content.length);
}
recordUpdated.incrementAndGet();
if (contentModified) {
return new OStorageOperationResult<>(newRecordVersion, content, false);
} else {
return new OStorageOperationResult<>(newRecordVersion);
}
} catch (OConcurrentModificationException e) {
recordConflict.incrementAndGet();
throw e;
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Error on updating record " + rid + " (cluster: " + cluster.getName() + ")"), ioe);
}
}
private OStorageOperationResult<Integer> doRecycleRecord(final ORecordId rid, byte[] content, final int version,
final OCluster cluster, final byte recordType) {
try {
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
cluster.recycleRecord(rid.getClusterPosition(), content, version, recordType);
final ORecordSerializationContext context = ORecordSerializationContext.getContext();
if (context != null) {
context.executeOperations(this);
}
} catch (Exception e) {
rollback = true;
throw e;
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance().debug(this, "Recycled record %s v.%s size=%d", rid, version, content.length);
}
return new OStorageOperationResult<>(version, content, false);
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error on recycling record " + rid + " (cluster: " + cluster + ")", ioe);
throw OException
.wrapException(new OStorageException("Error on recycling record " + rid + " (cluster: " + cluster + ")"), ioe);
}
}
private OStorageOperationResult<Boolean> doDeleteRecord(ORecordId rid, final int version, OCluster cluster) {
Orient.instance().getProfiler().startChrono();
try {
final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition()));
if (ppos == null) {
// ALREADY DELETED
return new OStorageOperationResult<>(false);
}
// MVCC TRANSACTION: CHECK IF VERSION IS THE SAME
if (version > -1 && ppos.recordVersion != version) {
recordConflict.incrementAndGet();
if (OFastConcurrentModificationException.enabled()) {
throw OFastConcurrentModificationException.instance();
} else {
throw new OConcurrentModificationException(rid, ppos.recordVersion, version, ORecordOperation.DELETED);
}
}
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
cluster.deleteRecord(ppos.clusterPosition);
final ORecordSerializationContext context = ORecordSerializationContext.getContext();
if (context != null) {
context.executeOperations(this);
}
} catch (Exception e) {
rollback = true;
throw e;
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance().debug(this, "Deleted record %s v.%s", rid, version);
}
recordDeleted.incrementAndGet();
return new OStorageOperationResult<>(true);
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Error on deleting record " + rid + "( cluster: " + cluster.getName() + ")"), ioe);
}
}
private OStorageOperationResult<Boolean> doHideMethod(ORecordId rid, OCluster cluster) {
try {
final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition()));
if (ppos == null) {
// ALREADY HIDDEN
return new OStorageOperationResult<>(false);
}
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
cluster.hideRecord(ppos.clusterPosition);
final ORecordSerializationContext context = ORecordSerializationContext.getContext();
if (context != null) {
context.executeOperations(this);
}
} catch (Exception e) {
rollback = true;
throw e;
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
return new OStorageOperationResult<>(true);
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error on deleting record " + rid + "( cluster: " + cluster + ")", ioe);
throw OException.wrapException(new OStorageException("Error on deleting record " + rid + "( cluster: " + cluster + ")"), ioe);
}
}
private ORawBuffer doReadRecord(final OCluster clusterSegment, final ORecordId rid, boolean prefetchRecords) {
try {
final ORawBuffer buff = clusterSegment.readRecord(rid.getClusterPosition(), prefetchRecords);
if (buff != null && OLogManager.instance().isDebugEnabled()) {
OLogManager.instance()
.debug(this, "Read record %s v.%s size=%d bytes", rid, buff.version, buff.buffer != null ? buff.buffer.length : 0);
}
recordRead.incrementAndGet();
return buff;
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during read of record with rid = " + rid), e);
}
}
private static ORawBuffer doReadRecordIfNotLatest(final OCluster cluster, final ORecordId rid, final int recordVersion)
throws ORecordNotFoundException {
try {
return cluster.readRecordIfVersionIsNotLatest(rid.getClusterPosition(), recordVersion);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during read of record with rid = " + rid), e);
}
}
private int createClusterFromConfig(final OStorageClusterConfiguration config) throws IOException {
OCluster cluster = clusterMap.get(config.getName().toLowerCase(configuration.getLocaleInstance()));
if (cluster != null) {
cluster.configure(this, config);
return -1;
}
if (config.getStatus() == OStorageClusterConfiguration.STATUS.ONLINE) {
cluster = OPaginatedClusterFactory
.createCluster(config.getName(), configuration.getVersion(), config.getBinaryVersion(), this);
} else {
cluster = new OOfflineCluster(this, config.getId(), config.getName());
}
cluster.configure(this, config);
return registerCluster(cluster);
}
private void setCluster(int id, OCluster cluster) {
if (clusters.size() <= id) {
while (clusters.size() < id) {
clusters.add(null);
}
clusters.add(cluster);
} else {
clusters.set(id, cluster);
}
}
/**
* Register the cluster internally.
*
* @param cluster OCluster implementation
*
* @return The id (physical position into the array) of the new cluster just created. First is 0.
*/
private int registerCluster(final OCluster cluster) {
final int id;
if (cluster != null) {
// CHECK FOR DUPLICATION OF NAMES
if (clusterMap.containsKey(cluster.getName().toLowerCase(configuration.getLocaleInstance()))) {
throw new OConfigurationException(
"Cannot add cluster '" + cluster.getName() + "' because it is already registered in database '" + name + "'");
}
// CREATE AND ADD THE NEW REF SEGMENT
clusterMap.put(cluster.getName().toLowerCase(configuration.getLocaleInstance()), cluster);
id = cluster.getId();
} else {
id = clusters.size();
}
setCluster(id, cluster);
return id;
}
private int doAddCluster(String clusterName, Object[] parameters) throws IOException {
// FIND THE FIRST AVAILABLE CLUSTER ID
int clusterPos = clusters.size();
for (int i = 0; i < clusters.size(); ++i) {
if (clusters.get(i) == null) {
clusterPos = i;
break;
}
}
return addClusterInternal(clusterName, clusterPos, parameters);
}
private int addClusterInternal(String clusterName, int clusterPos, Object... parameters) throws IOException {
final OCluster cluster;
if (clusterName != null) {
clusterName = clusterName.toLowerCase(configuration.getLocaleInstance());
cluster = OPaginatedClusterFactory
.createCluster(clusterName, configuration.getVersion(), OPaginatedCluster.getLatestBinaryVersion(), this);
cluster.configure(this, clusterPos, clusterName, parameters);
} else {
cluster = null;
}
int createdClusterId = -1;
if (cluster != null) {
if (!cluster.exists()) {
cluster.create(-1);
} else {
cluster.open();
}
if (writeAheadLog != null) {
writeAheadLog.flush();
}
createdClusterId = registerCluster(cluster);
((OPaginatedCluster) cluster).registerInStorageConfig((OStorageConfigurationImpl) configuration);
((OStorageConfigurationImpl) configuration).update();
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance()
.debug(this, "Created cluster '%s' in database '%s' with id %d. Clusters: %s", clusterName, url, createdClusterId,
clusters);
}
return createdClusterId;
}
private void doClose(boolean force, boolean onDelete) {
if (!force && !onDelete) {
return;
}
if (status == STATUS.CLOSED) {
return;
}
final long timer = Orient.instance().getProfiler().startChrono();
Map<String, Object> params = new HashMap<>();
stateLock.acquireWriteLock();
try {
if (status == STATUS.CLOSED) {
return;
}
status = STATUS.CLOSING;
if (jvmError.get() == null) {
readCache.storeCacheState(writeCache);
if (!onDelete && jvmError.get() == null) {
makeFullCheckpoint();
}
params = preCloseSteps();
sbTreeCollectionManager.close();
// we close all files inside cache system so we only clear cluster metadata
clusters.clear();
clusterMap.clear();
// we close all files inside cache system so we only clear index metadata and close non core indexes
for (OIndexEngine engine : indexEngines) {
if (engine != null && !(engine instanceof OSBTreeIndexEngine || engine instanceof OHashTableIndexEngine
|| engine instanceof OPrefixBTreeIndexEngine)) {
if (onDelete) {
engine.delete();
} else {
engine.close();
}
}
}
indexEngines.clear();
indexEngineNameMap.clear();
if (getConfiguration() != null) {
if (onDelete) {
((OStorageConfigurationImpl) configuration).delete();
} else {
((OStorageConfigurationImpl) configuration).close();
}
}
super.close(force, onDelete);
if (writeCache != null) {
writeCache.removeLowDiskSpaceListener(this);
writeCache.removeBackgroundExceptionListener(this);
writeCache.removePageIsBrokenListener(this);
}
if (writeAheadLog != null) {
writeAheadLog.removeFullCheckpointListener(this);
writeAheadLog.removeLowDiskSpaceListener(this);
}
if (readCache != null) {
if (!onDelete) {
readCache.closeStorage(writeCache);
} else {
readCache.deleteStorage(writeCache);
}
}
if (writeAheadLog != null) {
if (onDelete) {
writeAheadLog.delete();
} else {
writeAheadLog.close();
}
}
try {
performanceStatisticManager.unregisterMBean(name, id);
} catch (Exception e) {
OLogManager.instance().error(this, "MBean for write cache cannot be unregistered", e);
}
postCloseSteps(onDelete, jvmError.get() != null);
transaction = null;
} else {
OLogManager.instance()
.errorNoDb(this, "Because of JVM error happened inside of storage it can not be properly closed", null);
}
status = STATUS.CLOSED;
} catch (IOException e) {
final String message = "Error on closing of storage '" + name;
OLogManager.instance().error(this, message, e);
throw OException.wrapException(new OStorageException(message), e);
} finally {
//noinspection ResultOfMethodCallIgnored
Orient.instance().getProfiler().stopChrono("db." + name + ".close", "Close a database", timer, "db.*.close");
stateLock.releaseWriteLock();
}
postCloseStepsAfterLock(params);
}
@SuppressWarnings("unused")
protected void closeClusters(boolean onDelete) throws IOException {
for (OCluster cluster : clusters) {
if (cluster != null) {
cluster.close(!onDelete);
}
}
clusters.clear();
clusterMap.clear();
}
@SuppressWarnings("unused")
protected void closeIndexes(boolean onDelete) {
for (OIndexEngine engine : indexEngines) {
if (engine != null) {
if (onDelete) {
try {
engine.delete();
} catch (IOException e) {
OLogManager.instance().error(this, "Can not delete index engine " + engine.getName(), e);
}
} else {
engine.close();
}
}
}
indexEngines.clear();
indexEngineNameMap.clear();
}
@SuppressFBWarnings(value = "PZLA_PREFER_ZERO_LENGTH_ARRAYS")
private byte[] checkAndIncrementVersion(final OCluster iCluster, final ORecordId rid, final AtomicInteger version,
final AtomicInteger iDatabaseVersion, final byte[] iRecordContent, final byte iRecordType) {
final int v = version.get();
switch (v) {
// DOCUMENT UPDATE, NO VERSION CONTROL
case -1:
iDatabaseVersion.incrementAndGet();
break;
// DOCUMENT UPDATE, NO VERSION CONTROL, NO VERSION UPDATE
case -2:
break;
default:
// MVCC CONTROL AND RECORD UPDATE OR WRONG VERSION VALUE
// MVCC TRANSACTION: CHECK IF VERSION IS THE SAME
if (v < -2) {
// OVERWRITE VERSION: THIS IS USED IN CASE OF FIX OF RECORDS IN DISTRIBUTED MODE
version.set(ORecordVersionHelper.clearRollbackMode(v));
iDatabaseVersion.set(version.get());
} else if (v != iDatabaseVersion.get()) {
final ORecordConflictStrategy strategy =
iCluster.getRecordConflictStrategy() != null ? iCluster.getRecordConflictStrategy() : recordConflictStrategy;
return strategy.onUpdate(this, iRecordType, rid, v, iRecordContent, iDatabaseVersion);
} else
// OK, INCREMENT DB VERSION
{
iDatabaseVersion.incrementAndGet();
}
}
return null;
}
private void commitEntry(final ORecordOperation txEntry, final OPhysicalPosition allocated, ORecordSerializer serializer) {
final ORecord rec = txEntry.getRecord();
if (txEntry.type != ORecordOperation.DELETED && !rec.isDirty())
// NO OPERATION
{
return;
}
ORecordId rid = (ORecordId) rec.getIdentity();
if (txEntry.type == ORecordOperation.UPDATED && rid.isNew())
// OVERWRITE OPERATION AS CREATE
{
txEntry.type = ORecordOperation.CREATED;
}
ORecordSerializationContext.pushContext();
try {
final OCluster cluster = getClusterById(rid.getClusterId());
if (cluster.getName().equals(OMetadataDefault.CLUSTER_INDEX_NAME) || cluster.getName()
.equals(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME))
// AVOID TO COMMIT INDEX STUFF
{
return;
}
switch (txEntry.type) {
case ORecordOperation.LOADED:
break;
case ORecordOperation.CREATED: {
final byte[] stream = serializer.toStream(rec, false);
if (allocated != null) {
final OPhysicalPosition ppos;
final byte recordType = ORecordInternal.getRecordType(rec);
ppos = doCreateRecord(rid, stream, rec.getVersion(), recordType, null, cluster, allocated).getResult();
ORecordInternal.setVersion(rec, ppos.recordVersion);
} else {
// USE -2 AS VERSION TO AVOID INCREMENTING THE VERSION
final OStorageOperationResult<Integer> updateRes = updateRecord(rid, ORecordInternal.isContentChanged(rec), stream, -2,
ORecordInternal.getRecordType(rec), -1, null);
ORecordInternal.setVersion(rec, updateRes.getResult());
if (updateRes.getModifiedRecordContent() != null) {
ORecordInternal.fill(rec, rid, updateRes.getResult(), updateRes.getModifiedRecordContent(), false);
}
}
break;
}
case ORecordOperation.UPDATED: {
final byte[] stream = serializer.toStream(rec, false);
final OStorageOperationResult<Integer> updateRes = doUpdateRecord(rid, ORecordInternal.isContentChanged(rec), stream,
rec.getVersion(), ORecordInternal.getRecordType(rec), null, cluster);
txEntry.setResultData(updateRes.getResult());
ORecordInternal.setVersion(rec, updateRes.getResult());
if (updateRes.getModifiedRecordContent() != null) {
ORecordInternal.fill(rec, rid, updateRes.getResult(), updateRes.getModifiedRecordContent(), false);
}
break;
}
case ORecordOperation.DELETED: {
if (rec instanceof ODocument) {
ORidBagDeleter.deleteAllRidBags((ODocument) rec);
}
deleteRecord(rid, rec.getVersion(), -1, null);
break;
}
default:
throw new OStorageException("Unknown record operation " + txEntry.type);
}
} finally {
ORecordSerializationContext.pullContext();
}
// RESET TRACKING
if (rec instanceof ODocument && ((ODocument) rec).isTrackingChanges()) {
ODocumentInternal.clearTrackData(((ODocument) rec));
}
ORecordInternal.unsetDirty(rec);
}
private void checkClusterSegmentIndexRange(final int iClusterId) {
if (iClusterId < 0 || iClusterId > clusters.size() - 1) {
throw new IllegalArgumentException("Cluster segment #" + iClusterId + " does not exist in database '" + name + "'");
}
}
private OLogSequenceNumber restoreFromWAL() throws IOException {
if (writeAheadLog == null) {
OLogManager.instance().error(this, "Restore is not possible because write ahead logging is switched off.", null);
return null;
}
if (writeAheadLog.begin() == null) {
OLogManager.instance().error(this, "Restore is not possible because write ahead log is empty.", null);
return null;
}
OLogManager.instance().info(this, "Looking for last checkpoint...");
final OLogSequenceNumber end = writeAheadLog.end();
if (end == null) {
OLogManager.instance().errorNoDb(this, "WAL is empty, there is nothing not restore", null);
return null;
}
writeAheadLog.addCutTillLimit(end);
try {
OLogSequenceNumber lastCheckPoint;
try {
lastCheckPoint = writeAheadLog.getLastCheckpoint();
} catch (OWALPageBrokenException ignore) {
lastCheckPoint = null;
}
if (lastCheckPoint == null) {
OLogManager.instance().info(this, "Checkpoints are absent, the restore will start from the beginning.");
return restoreFromBeginning();
}
List<OWriteableWALRecord> checkPointRecord;
try {
checkPointRecord = writeAheadLog.read(lastCheckPoint, 1);
} catch (OWALPageBrokenException ignore) {
checkPointRecord = Collections.emptyList();
}
if (checkPointRecord.isEmpty()) {
OLogManager.instance().info(this, "Checkpoints are absent, the restore will start from the beginning.");
return restoreFromBeginning();
}
if (checkPointRecord.get(0) instanceof OFuzzyCheckpointStartRecord) {
OLogManager.instance().info(this, "Found FUZZY checkpoint.");
boolean fuzzyCheckPointIsComplete = checkFuzzyCheckPointIsComplete(lastCheckPoint);
if (!fuzzyCheckPointIsComplete) {
OLogManager.instance().warn(this, "FUZZY checkpoint is not complete.");
OLogSequenceNumber previousCheckpoint = ((OFuzzyCheckpointStartRecord) checkPointRecord.get(0)).getPreviousCheckpoint();
checkPointRecord = Collections.emptyList();
if (previousCheckpoint != null) {
checkPointRecord = writeAheadLog.read(previousCheckpoint, 1);
}
if (!checkPointRecord.isEmpty()) {
OLogManager.instance().warn(this, "Restore will start from the previous checkpoint.");
return restoreFromCheckPoint((OAbstractCheckPointStartRecord) checkPointRecord.get(0));
} else {
OLogManager.instance().warn(this, "Restore will start from the beginning.");
return restoreFromBeginning();
}
} else {
return restoreFromCheckPoint((OAbstractCheckPointStartRecord) checkPointRecord.get(0));
}
}
if (checkPointRecord.get(0) instanceof OFullCheckpointStartRecord) {
OLogManager.instance().info(this, "FULL checkpoint found.");
boolean fullCheckPointIsComplete = checkFullCheckPointIsComplete(lastCheckPoint);
if (!fullCheckPointIsComplete) {
OLogManager.instance().warn(this, "FULL checkpoint has not completed.");
OLogSequenceNumber previousCheckpoint = ((OFullCheckpointStartRecord) checkPointRecord.get(0)).getPreviousCheckpoint();
checkPointRecord = Collections.emptyList();
if (previousCheckpoint != null) {
checkPointRecord = writeAheadLog.read(previousCheckpoint, 1);
}
if (!checkPointRecord.isEmpty()) {
OLogManager.instance().warn(this, "Restore will start from the previous checkpoint.");
return restoreFromCheckPoint((OAbstractCheckPointStartRecord) checkPointRecord.get(0));
} else {
OLogManager.instance().warn(this, "Restore will start from the beginning.");
return restoreFromBeginning();
}
} else {
return restoreFromCheckPoint((OAbstractCheckPointStartRecord) checkPointRecord.get(0));
}
}
throw new OStorageException("Unknown checkpoint record type " + checkPointRecord.get(0).getClass().getName());
} finally {
writeAheadLog.removeCutTillLimit(end);
}
}
private boolean checkFullCheckPointIsComplete(OLogSequenceNumber lastCheckPoint) throws IOException {
try {
List<OWriteableWALRecord> walRecords = writeAheadLog.next(lastCheckPoint, 10);
while (!walRecords.isEmpty()) {
for (OWriteableWALRecord walRecord : walRecords) {
if (walRecord instanceof OCheckpointEndRecord) {
return true;
}
}
walRecords = writeAheadLog.next(walRecords.get(walRecords.size() - 1).getLsn(), 10);
}
} catch (OWALPageBrokenException ignore) {
return false;
}
return false;
}
@Override
public String incrementalBackup(String backupDirectory, OCallable<Void, Void> started) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Incremental backup is supported only in enterprise version");
}
@Override
public void restoreFromIncrementalBackup(String filePath) {
throw new UnsupportedOperationException("Incremental backup is supported only in enterprise version");
}
private boolean checkFuzzyCheckPointIsComplete(OLogSequenceNumber lastCheckPoint) throws IOException {
try {
List<OWriteableWALRecord> walRecords = writeAheadLog.next(lastCheckPoint, 10);
while (!walRecords.isEmpty()) {
for (OWriteableWALRecord walRecord : walRecords) {
if (walRecord instanceof OFuzzyCheckpointEndRecord) {
return true;
}
}
walRecords = writeAheadLog.next(walRecords.get(walRecords.size() - 1).getLsn(), 10);
}
} catch (OWALPageBrokenException ignore) {
return false;
}
return false;
}
private OLogSequenceNumber restoreFromCheckPoint(OAbstractCheckPointStartRecord checkPointRecord) throws IOException {
if (checkPointRecord instanceof OFuzzyCheckpointStartRecord) {
return restoreFromFuzzyCheckPoint((OFuzzyCheckpointStartRecord) checkPointRecord);
}
if (checkPointRecord instanceof OFullCheckpointStartRecord) {
return restoreFromFullCheckPoint((OFullCheckpointStartRecord) checkPointRecord);
}
throw new OStorageException("Unknown checkpoint record type " + checkPointRecord.getClass().getName());
}
private OLogSequenceNumber restoreFromFullCheckPoint(OFullCheckpointStartRecord checkPointRecord) throws IOException {
OLogManager.instance().info(this, "Data restore procedure from full checkpoint is started. Restore is performed from LSN %s",
checkPointRecord.getLsn());
final OLogSequenceNumber lsn = writeAheadLog.next(checkPointRecord.getLsn(), 1).get(0).getLsn();
return restoreFrom(lsn, writeAheadLog);
}
private OLogSequenceNumber restoreFromFuzzyCheckPoint(OFuzzyCheckpointStartRecord checkPointRecord) throws IOException {
OLogManager.instance().infoNoDb(this, "Data restore procedure from FUZZY checkpoint is started.");
OLogSequenceNumber flushedLsn = checkPointRecord.getFlushedLsn();
if (flushedLsn.compareTo(writeAheadLog.begin()) < 0) {
OLogManager.instance().errorNoDb(this,
"Fuzzy checkpoint points to removed part of the log, " + "will try to restore data from the rest of the WAL", null);
flushedLsn = writeAheadLog.begin();
}
return restoreFrom(flushedLsn, writeAheadLog);
}
private OLogSequenceNumber restoreFromBeginning() throws IOException {
OLogManager.instance().info(this, "Data restore procedure is started.");
OLogSequenceNumber lsn = writeAheadLog.begin();
return restoreFrom(lsn, writeAheadLog);
}
@SuppressWarnings("WeakerAccess")
protected final OLogSequenceNumber restoreFrom(OLogSequenceNumber lsn, OWriteAheadLog writeAheadLog) throws IOException {
OLogSequenceNumber logSequenceNumber = null;
OModifiableBoolean atLeastOnePageUpdate = new OModifiableBoolean();
long recordsProcessed = 0;
final int reportBatchSize = OGlobalConfiguration.WAL_REPORT_AFTER_OPERATIONS_DURING_RESTORE.getValueAsInteger();
final Map<OOperationUnitId, List<OWALRecord>> operationUnits = new HashMap<>();
long lastReportTime = 0;
try {
List<OWriteableWALRecord> records = writeAheadLog.read(lsn, 1_000);
while (!records.isEmpty()) {
for (OWriteableWALRecord walRecord : records) {
logSequenceNumber = walRecord.getLsn();
if (walRecord instanceof OAtomicUnitEndRecord) {
OAtomicUnitEndRecord atomicUnitEndRecord = (OAtomicUnitEndRecord) walRecord;
List<OWALRecord> atomicUnit = operationUnits.remove(atomicUnitEndRecord.getOperationUnitId());
// in case of data restore from fuzzy checkpoint part of operations may be already flushed to the disk
if (atomicUnit != null) {
atomicUnit.add(walRecord);
restoreAtomicUnit(atomicUnit, atLeastOnePageUpdate);
}
} else if (walRecord instanceof OAtomicUnitStartRecord) {
List<OWALRecord> operationList = new ArrayList<>();
assert !operationUnits.containsKey(((OAtomicUnitStartRecord) walRecord).getOperationUnitId());
operationUnits.put(((OAtomicUnitStartRecord) walRecord).getOperationUnitId(), operationList);
operationList.add(walRecord);
} else if (walRecord instanceof OOperationUnitRecord) {
OOperationUnitRecord operationUnitRecord = (OOperationUnitRecord) walRecord;
List<OWALRecord> operationList = operationUnits.get(operationUnitRecord.getOperationUnitId());
if (operationList == null || operationList.isEmpty()) {
OLogManager.instance().errorNoDb(this, "'Start transaction' record is absent for atomic operation", null);
if (operationList == null) {
operationList = new ArrayList<>();
operationUnits.put(operationUnitRecord.getOperationUnitId(), operationList);
}
}
operationList.add(operationUnitRecord);
} else if (walRecord instanceof ONonTxOperationPerformedWALRecord) {
if (!wereNonTxOperationsPerformedInPreviousOpen) {
OLogManager.instance()
.warnNoDb(this, "Non tx operation was used during data modification we will need index rebuild.");
wereNonTxOperationsPerformedInPreviousOpen = true;
}
} else {
OLogManager.instance().warnNoDb(this, "Record %s will be skipped during data restore", walRecord);
}
recordsProcessed++;
final long currentTime = System.currentTimeMillis();
if (reportBatchSize > 0 && recordsProcessed % reportBatchSize == 0
|| currentTime - lastReportTime > WAL_RESTORE_REPORT_INTERVAL) {
OLogManager.instance()
.infoNoDb(this, "%d operations were processed, current LSN is %s last LSN is %s", recordsProcessed, lsn,
writeAheadLog.end());
lastReportTime = currentTime;
}
}
records = writeAheadLog.next(records.get(records.size() - 1).getLsn(), 1_000);
}
} catch (OWALPageBrokenException e) {
OLogManager.instance()
.errorNoDb(this, "Data restore was paused because broken WAL page was found. The rest of changes will be rolled back.",
e);
} catch (RuntimeException e) {
OLogManager.instance().errorNoDb(this,
"Data restore was paused because of exception. The rest of changes will be rolled back and WAL files will be backed up."
+ " Please report issue about this exception to bug tracker and provide WAL files which are backed up in 'wal_backup' directory.",
e);
backUpWAL(e);
}
if (atLeastOnePageUpdate.getValue()) {
return logSequenceNumber;
}
return null;
}
private void backUpWAL(Exception e) {
try {
final File rootDir = new File(getConfiguration().getDirectory());
final File backUpDir = new File(rootDir, "wal_backup");
if (!backUpDir.exists()) {
final boolean created = backUpDir.mkdir();
if (!created) {
OLogManager.instance().error(this, "Cannot create directory for backup files " + backUpDir.getAbsolutePath(), null);
return;
}
}
final Date date = new Date();
final SimpleDateFormat dateFormat = new SimpleDateFormat("dd_MM_yy_HH_mm_ss");
final String strDate = dateFormat.format(date);
final String archiveName = "wal_backup_" + strDate + ".zip";
final String metadataName = "wal_metadata_" + strDate + ".txt";
final File archiveFile = new File(backUpDir, archiveName);
if (!archiveFile.createNewFile()) {
OLogManager.instance().error(this, "Cannot create backup file " + archiveFile.getAbsolutePath(), null);
return;
}
try (final FileOutputStream archiveOutputStream = new FileOutputStream(archiveFile)) {
try (final ZipOutputStream archiveZipOutputStream = new ZipOutputStream(new BufferedOutputStream(archiveOutputStream))) {
final ZipEntry metadataEntry = new ZipEntry(metadataName);
archiveZipOutputStream.putNextEntry(metadataEntry);
final PrintWriter metadataFileWriter = new PrintWriter(
new OutputStreamWriter(archiveZipOutputStream, StandardCharsets.UTF_8));
metadataFileWriter.append("Storage name : ").append(getName()).append("\r\n");
metadataFileWriter.append("Date : ").append(strDate).append("\r\n");
metadataFileWriter.append("Stacktrace : \r\n");
e.printStackTrace(metadataFileWriter);
metadataFileWriter.flush();
archiveZipOutputStream.closeEntry();
final List<String> walPaths = ((OCASDiskWriteAheadLog) writeAheadLog).getWalFiles();
for (String walSegment : walPaths) {
archiveEntry(archiveZipOutputStream, walSegment);
}
archiveEntry(archiveZipOutputStream, ((OCASDiskWriteAheadLog) writeAheadLog).getWMRFile().toString());
}
}
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error during WAL backup", ioe);
}
}
private static void archiveEntry(ZipOutputStream archiveZipOutputStream, String walSegment) throws IOException {
final File walFile = new File(walSegment);
final ZipEntry walZipEntry = new ZipEntry(walFile.getName());
archiveZipOutputStream.putNextEntry(walZipEntry);
try {
try (FileInputStream walInputStream = new FileInputStream(walFile)) {
try (BufferedInputStream walBufferedInputStream = new BufferedInputStream(walInputStream)) {
final byte[] buffer = new byte[1024];
int readBytes;
while ((readBytes = walBufferedInputStream.read(buffer)) > -1) {
archiveZipOutputStream.write(buffer, 0, readBytes);
}
}
}
} finally {
archiveZipOutputStream.closeEntry();
}
}
@SuppressWarnings("WeakerAccess")
protected final void restoreAtomicUnit(List<OWALRecord> atomicUnit, OModifiableBoolean atLeastOnePageUpdate) throws IOException {
assert atomicUnit.get(atomicUnit.size() - 1) instanceof OAtomicUnitEndRecord;
for (OWALRecord walRecord : atomicUnit) {
if (walRecord instanceof OFileDeletedWALRecord) {
OFileDeletedWALRecord fileDeletedWALRecord = (OFileDeletedWALRecord) walRecord;
if (writeCache.exists(fileDeletedWALRecord.getFileId())) {
readCache.deleteFile(fileDeletedWALRecord.getFileId(), writeCache);
}
} else if (walRecord instanceof OFileCreatedWALRecord) {
OFileCreatedWALRecord fileCreatedCreatedWALRecord = (OFileCreatedWALRecord) walRecord;
if (!writeCache.exists(fileCreatedCreatedWALRecord.getFileName())) {
readCache.addFile(fileCreatedCreatedWALRecord.getFileName(), fileCreatedCreatedWALRecord.getFileId(), writeCache);
}
} else if (walRecord instanceof OUpdatePageRecord) {
final OUpdatePageRecord updatePageRecord = (OUpdatePageRecord) walRecord;
long fileId = updatePageRecord.getFileId();
if (!writeCache.exists(fileId)) {
String fileName = writeCache.restoreFileById(fileId);
if (fileName == null) {
throw new OStorageException(
"File with id " + fileId + " was deleted from storage, the rest of operations can not be restored");
} else {
OLogManager.instance().warn(this, "Previously deleted file with name " + fileName
+ " was deleted but new empty file was added to continue restore process");
}
}
final long pageIndex = updatePageRecord.getPageIndex();
fileId = writeCache.externalFileId(writeCache.internalFileId(fileId));
OCacheEntry cacheEntry = readCache.loadForWrite(fileId, pageIndex, true, writeCache, 1, false, null);
if (cacheEntry == null) {
do {
if (cacheEntry != null) {
readCache.releaseFromWrite(cacheEntry, writeCache);
}
cacheEntry = readCache.allocateNewPage(fileId, writeCache, false, null, false);
} while (cacheEntry.getPageIndex() != pageIndex);
}
try {
ODurablePage durablePage = new ODurablePage(cacheEntry);
durablePage.restoreChanges(updatePageRecord.getChanges());
durablePage.setLsn(updatePageRecord.getLsn());
} finally {
readCache.releaseFromWrite(cacheEntry, writeCache);
}
atLeastOnePageUpdate.setValue(true);
} else if (walRecord instanceof OAtomicUnitStartRecord) {
//noinspection UnnecessaryContinue
continue;
} else if (walRecord instanceof OAtomicUnitEndRecord) {
//noinspection UnnecessaryContinue
continue;
} else {
OLogManager.instance()
.error(this, "Invalid WAL record type was passed %s. Given record will be skipped.", null, walRecord.getClass());
assert false : "Invalid WAL record type was passed " + walRecord.getClass().getName();
}
}
}
/**
* Method which is called before any data modification operation to check alarm conditions such as: <ol> <li>Low disk space</li>
* <li>Exception during data flush in background threads</li> <li>Broken files</li> </ol>
* If one of those conditions are satisfied data modification operation is aborted and storage is switched in "read only" mode.
*/
private void checkLowDiskSpaceRequestsAndReadOnlyConditions() {
if (transaction.get() != null) {
return;
}
if (lowDiskSpace != null) {
if (checkpointInProgress.compareAndSet(false, true)) {
try {
if (writeCache.checkLowDiskSpace()) {
OLogManager.instance().error(this, "Not enough disk space, force sync will be called", null);
synch();
if (writeCache.checkLowDiskSpace()) {
throw new OLowDiskSpaceException("Error occurred while executing a write operation to database '" + name
+ "' due to limited free space on the disk (" + (lowDiskSpace.freeSpace / (1024 * 1024))
+ " MB). The database is now working in read-only mode."
+ " Please close the database (or stop OrientDB), make room on your hard drive and then reopen the database. "
+ "The minimal required space is " + (lowDiskSpace.requiredSpace / (1024 * 1024)) + " MB. "
+ "Required space is now set to " + getConfiguration().getContextConfiguration()
.getValueAsInteger(OGlobalConfiguration.DISK_CACHE_FREE_SPACE_LIMIT)
+ "MB (you can change it by setting parameter " + OGlobalConfiguration.DISK_CACHE_FREE_SPACE_LIMIT.getKey()
+ ") .");
} else {
lowDiskSpace = null;
}
} else {
lowDiskSpace = null;
}
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during low disk space handling"), e);
} finally {
checkpointInProgress.set(false);
}
}
}
checkReadOnlyConditions();
}
public final void checkReadOnlyConditions() {
if (dataFlushException != null) {
throw OException.wrapException(new OStorageException(
"Error in data flush background thread, please restart database and send full stack trace inside of bug report"),
dataFlushException);
}
if (!brokenPages.isEmpty()) {
//order pages by file and index
final Map<String, SortedSet<Long>> pagesByFile = new HashMap<>();
for (OPair<String, Long> brokenPage : brokenPages) {
final SortedSet<Long> sortedPages = pagesByFile.computeIfAbsent(brokenPage.key, (fileName) -> new TreeSet<>());
sortedPages.add(brokenPage.value);
}
final StringBuilder brokenPagesList = new StringBuilder();
brokenPagesList.append("[");
for (String fileName : pagesByFile.keySet()) {
brokenPagesList.append('\'').append(fileName).append("' :");
final SortedSet<Long> pageIndexes = pagesByFile.get(fileName);
final long lastPage = pageIndexes.last();
for (Long pageIndex : pagesByFile.get(fileName)) {
brokenPagesList.append(pageIndex);
if (pageIndex != lastPage) {
brokenPagesList.append(", ");
}
}
brokenPagesList.append(";");
}
brokenPagesList.append("]");
throw new OPageIsBrokenException("Following files and pages are detected to be broken " + brokenPagesList + ", storage is "
+ "switched to 'read only' mode. Any modification operations are prohibited. "
+ "To restore database and make it fully operational you may export and import database " + "to and from JSON.");
}
if (jvmError.get() != null) {
throw new OJVMErrorException("JVM error '" + jvmError.get().getClass().getSimpleName() + " : " + jvmError.get().getMessage()
+ "' occurred during data processing, storage is switched to 'read-only' mode. "
+ "To prevent this exception please restart the JVM and check data consistency by calling of 'check database' "
+ "command from database console.");
}
}
@SuppressWarnings("unused")
public void setStorageConfigurationUpdateListener(OStorageConfigurationUpdateListener storageConfigurationUpdateListener) {
stateLock.acquireWriteLock();
try {
checkOpenness();
((OStorageConfigurationImpl) configuration).setConfigurationUpdateListener(storageConfigurationUpdateListener);
} finally {
stateLock.releaseWriteLock();
}
}
@SuppressWarnings("unused")
protected static Map<Integer, List<ORecordId>> getRidsGroupedByCluster(final Collection<ORecordId> iRids) {
final Map<Integer, List<ORecordId>> ridsPerCluster = new HashMap<>();
for (ORecordId rid : iRids) {
List<ORecordId> rids = ridsPerCluster.computeIfAbsent(rid.getClusterId(), k -> new ArrayList<>(iRids.size()));
rids.add(rid);
}
return ridsPerCluster;
}
private static void lockIndexes(final TreeMap<String, OTransactionIndexChanges> indexes) {
for (OTransactionIndexChanges changes : indexes.values()) {
assert changes.changesPerKey instanceof TreeMap;
final OIndexInternal<?> index = changes.getAssociatedIndex();
final List<Object> orderedIndexNames = new ArrayList<>(changes.changesPerKey.keySet());
if (orderedIndexNames.size() > 1) {
orderedIndexNames.sort((o1, o2) -> {
String i1 = index.getIndexNameByKey(o1);
String i2 = index.getIndexNameByKey(o2);
return i1.compareTo(i2);
});
}
boolean fullyLocked = false;
for (Object key : orderedIndexNames) {
if (index.acquireAtomicExclusiveLock(key)) {
fullyLocked = true;
break;
}
}
if (!fullyLocked && !changes.nullKeyChanges.entries.isEmpty()) {
index.acquireAtomicExclusiveLock(null);
}
}
}
private static void lockClusters(final TreeMap<Integer, OCluster> clustersToLock) {
for (OCluster cluster : clustersToLock.values()) {
cluster.acquireAtomicExclusiveLock();
}
}
private void lockRidBags(final TreeMap<Integer, OCluster> clusters, final TreeMap<String, OTransactionIndexChanges> indexes,
OIndexManager manager) {
final OAtomicOperation atomicOperation = OAtomicOperationsManager.getCurrentOperation();
for (Integer clusterId : clusters.keySet()) {
atomicOperationsManager
.acquireExclusiveLockTillOperationComplete(atomicOperation, OSBTreeCollectionManagerAbstract.generateLockName(clusterId));
}
for (Map.Entry<String, OTransactionIndexChanges> entry : indexes.entrySet()) {
final String indexName = entry.getKey();
final OIndexInternal<?> index = entry.getValue().resolveAssociatedIndex(indexName, manager);
if (!index.isUnique()) {
atomicOperationsManager
.acquireExclusiveLockTillOperationComplete(atomicOperation, OIndexRIDContainerSBTree.generateLockName(indexName));
}
}
}
private void registerProfilerHooks() {
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".createRecord", "Number of created records", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordCreated), "db.*.createRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".readRecord", "Number of read records", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordRead), "db.*.readRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".updateRecord", "Number of updated records", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordUpdated), "db.*.updateRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".deleteRecord", "Number of deleted records", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordDeleted), "db.*.deleteRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".scanRecord", "Number of read scanned", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordScanned), "db.*.scanRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".recyclePosition", "Number of recycled records", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordRecycled), "db.*.recyclePosition");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".conflictRecord", "Number of conflicts during updating and deleting records",
OProfiler.METRIC_TYPE.COUNTER, new AtomicLongOProfilerHookValue(recordConflict), "db.*.conflictRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".txBegun", "Number of transactions begun", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(txBegun), "db.*.txBegun");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".txCommit", "Number of committed transactions", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(txCommit), "db.*.txCommit");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".txRollback", "Number of rolled back transactions", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(txRollback), "db.*.txRollback");
}
protected final RuntimeException logAndPrepareForRethrow(RuntimeException runtimeException) {
if (!(runtimeException instanceof OHighLevelException || runtimeException instanceof ONeedRetryException)) {
OLogManager.instance()
.errorStorage(this, "Exception `%08X` in storage `%s`: %s", runtimeException, System.identityHashCode(runtimeException),
getURL(), OConstants.getVersion());
}
return runtimeException;
}
protected final Error logAndPrepareForRethrow(Error error) {
return logAndPrepareForRethrow(error, true);
}
private Error logAndPrepareForRethrow(Error error, boolean putInReadOnlyMode) {
if (!(error instanceof OHighLevelException)) {
OLogManager.instance()
.errorStorage(this, "Exception `%08X` in storage `%s`: %s", error, System.identityHashCode(error), getURL(),
OConstants.getVersion());
}
if (putInReadOnlyMode) {
handleJVMError(error);
}
return error;
}
protected final RuntimeException logAndPrepareForRethrow(Throwable throwable) {
if (!(throwable instanceof OHighLevelException || throwable instanceof ONeedRetryException)) {
OLogManager.instance()
.errorStorage(this, "Exception `%08X` in storage `%s`: %s", throwable, System.identityHashCode(throwable), getURL(),
OConstants.getVersion());
}
return new RuntimeException(throwable);
}
private OInvalidIndexEngineIdException logAndPrepareForRethrow(OInvalidIndexEngineIdException exception) {
OLogManager.instance()
.errorStorage(this, "Exception `%08X` in storage `%s` : %s", exception, System.identityHashCode(exception), getURL(),
OConstants.getVersion());
return exception;
}
private static final class FuzzyCheckpointThreadFactory implements ThreadFactory {
@Override
public final Thread newThread(Runnable r) {
Thread thread = new Thread(storageThreadGroup, r);
thread.setDaemon(true);
thread.setUncaughtExceptionHandler(new OUncaughtExceptionHandler());
return thread;
}
}
private final class WALVacuum implements Runnable {
WALVacuum() {
}
@Override
public void run() {
stateLock.acquireReadLock();
try {
if (status == STATUS.CLOSED) {
return;
}
final long[] nonActiveSegments = writeAheadLog.nonActiveSegments();
if (nonActiveSegments.length == 0) {
return;
}
long flushTillSegmentId;
if (nonActiveSegments.length == 1) {
flushTillSegmentId = writeAheadLog.activeSegment();
} else {
flushTillSegmentId = (nonActiveSegments[0] + nonActiveSegments[nonActiveSegments.length - 1]) / 2;
}
long minDirtySegment;
do {
writeCache.flushTillSegment(flushTillSegmentId);
//we should take min lsn BEFORE min write cache LSN call
//to avoid case when new data are changed before call
OLogSequenceNumber endLSN = writeAheadLog.end();
Long minLSNSegment = writeCache.getMinimalNotFlushedSegment();
if (minLSNSegment == null) {
minDirtySegment = endLSN.getSegment();
} else {
minDirtySegment = minLSNSegment;
}
} while (minDirtySegment < flushTillSegmentId);
writeCache.makeFuzzyCheckpoint(minDirtySegment);
} catch (Exception e) {
dataFlushException = e;
OLogManager.instance().error(this, "Error during flushing of data for fuzzy checkpoint", e);
} finally {
stateLock.releaseReadLock();
walVacuumInProgress.set(false);
}
}
}
@Override
public final OStorageConfiguration getConfiguration() {
return configuration;
}
@Override
public final void setSchemaRecordId(String schemaRecordId) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setSchemaRecordId(schemaRecordId);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setDateFormat(String dateFormat) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setDateFormat(dateFormat);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setTimeZone(TimeZone timeZoneValue) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setTimeZone(timeZoneValue);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setLocaleLanguage(String locale) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setLocaleLanguage(locale);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setCharset(String charset) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setCharset(charset);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setIndexMgrRecordId(String indexMgrRecordId) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setIndexMgrRecordId(indexMgrRecordId);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setDateTimeFormat(String dateTimeFormat) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setDateTimeFormat(dateTimeFormat);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setLocaleCountry(String localeCountry) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setLocaleCountry(localeCountry);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setClusterSelection(String clusterSelection) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setClusterSelection(clusterSelection);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setMinimumClusters(int minimumClusters) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setMinimumClusters(minimumClusters);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setValidation(boolean validation) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setValidation(validation);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void removeProperty(String property) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.removeProperty(property);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setProperty(String property, String value) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setProperty(property, value);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setRecordSerializer(String recordSerializer, int version) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setRecordSerializer(recordSerializer);
storageConfiguration.setRecordSerializerVersion(version);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void clearProperties() {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.clearProperties();
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
}
| core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OAbstractPaginatedStorage.java | /*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.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.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.storage.impl.local;
import com.orientechnologies.common.concur.ONeedRetryException;
import com.orientechnologies.common.concur.lock.OLockManager;
import com.orientechnologies.common.concur.lock.OModificationOperationProhibitedException;
import com.orientechnologies.common.concur.lock.ONotThreadRWLockManager;
import com.orientechnologies.common.concur.lock.OPartitionedLockManager;
import com.orientechnologies.common.concur.lock.OSimpleRWLockManager;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.exception.OHighLevelException;
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.profiler.AtomicLongOProfilerHookValue;
import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.common.serialization.types.OBinarySerializer;
import com.orientechnologies.common.serialization.types.OUTF8Serializer;
import com.orientechnologies.common.thread.OScheduledThreadPoolExecutorWithLogging;
import com.orientechnologies.common.types.OModifiableBoolean;
import com.orientechnologies.common.util.OCallable;
import com.orientechnologies.common.util.OCommonConst;
import com.orientechnologies.common.util.OPair;
import com.orientechnologies.common.util.OUncaughtExceptionHandler;
import com.orientechnologies.orient.core.OConstants;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.config.OContextConfiguration;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.config.OStorageClusterConfiguration;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.orientechnologies.orient.core.config.OStorageConfigurationImpl;
import com.orientechnologies.orient.core.config.OStorageConfigurationUpdateListener;
import com.orientechnologies.orient.core.conflict.ORecordConflictStrategy;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseListener;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.OrientDBConfig;
import com.orientechnologies.orient.core.db.record.OCurrentStorageComponentsFactory;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordOperation;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBagDeleter;
import com.orientechnologies.orient.core.encryption.OEncryption;
import com.orientechnologies.orient.core.encryption.OEncryptionFactory;
import com.orientechnologies.orient.core.encryption.impl.ONothingEncryption;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.exception.OConcurrentCreateException;
import com.orientechnologies.orient.core.exception.OConcurrentModificationException;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.exception.OFastConcurrentModificationException;
import com.orientechnologies.orient.core.exception.OInvalidIndexEngineIdException;
import com.orientechnologies.orient.core.exception.OJVMErrorException;
import com.orientechnologies.orient.core.exception.OLowDiskSpaceException;
import com.orientechnologies.orient.core.exception.OPageIsBrokenException;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import com.orientechnologies.orient.core.exception.ORetryQueryException;
import com.orientechnologies.orient.core.exception.OStorageException;
import com.orientechnologies.orient.core.exception.OStorageExistsException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexAbstract;
import com.orientechnologies.orient.core.index.OIndexCursor;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexEngine;
import com.orientechnologies.orient.core.index.OIndexException;
import com.orientechnologies.orient.core.index.OIndexInternal;
import com.orientechnologies.orient.core.index.OIndexKeyCursor;
import com.orientechnologies.orient.core.index.OIndexKeyUpdater;
import com.orientechnologies.orient.core.index.OIndexManager;
import com.orientechnologies.orient.core.index.OIndexes;
import com.orientechnologies.orient.core.index.ORuntimeKeyIndexDefinition;
import com.orientechnologies.orient.core.metadata.OMetadataDefault;
import com.orientechnologies.orient.core.metadata.schema.OImmutableClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.metadata.security.OSecurityUser;
import com.orientechnologies.orient.core.metadata.security.OToken;
import com.orientechnologies.orient.core.query.OQueryAbstract;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordVersionHelper;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentInternal;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.index.OCompositeKeySerializer;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.index.OSimpleKeySerializer;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OIdentifiableStorage;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.ORecordCallback;
import com.orientechnologies.orient.core.storage.ORecordMetadata;
import com.orientechnologies.orient.core.storage.OStorageAbstract;
import com.orientechnologies.orient.core.storage.OStorageOperationResult;
import com.orientechnologies.orient.core.storage.cache.OCacheEntry;
import com.orientechnologies.orient.core.storage.cache.OPageDataVerificationError;
import com.orientechnologies.orient.core.storage.cache.OReadCache;
import com.orientechnologies.orient.core.storage.cache.OWriteCache;
import com.orientechnologies.orient.core.storage.cache.local.OBackgroundExceptionListener;
import com.orientechnologies.orient.core.storage.cluster.OOfflineCluster;
import com.orientechnologies.orient.core.storage.cluster.OPaginatedCluster;
import com.orientechnologies.orient.core.storage.impl.local.paginated.ORecordOperationMetadata;
import com.orientechnologies.orient.core.storage.impl.local.paginated.ORecordSerializationContext;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OStorageTransaction;
import com.orientechnologies.orient.core.storage.impl.local.paginated.atomicoperations.OAtomicOperation;
import com.orientechnologies.orient.core.storage.impl.local.paginated.atomicoperations.OAtomicOperationsManager;
import com.orientechnologies.orient.core.storage.impl.local.paginated.base.ODurablePage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OAbstractCheckPointStartRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OAtomicUnitEndRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OAtomicUnitStartRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OCheckpointEndRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OFileCreatedWALRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OFileDeletedWALRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OFullCheckpointStartRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OFuzzyCheckpointEndRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OFuzzyCheckpointStartRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OLogSequenceNumber;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.ONonTxOperationPerformedWALRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OOperationUnitId;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OOperationUnitRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OPaginatedClusterFactory;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OUpdatePageRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWALPageBrokenException;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWALRecord;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWriteAheadLog;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.cas.OCASDiskWriteAheadLog;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.cas.OWriteableWALRecord;
import com.orientechnologies.orient.core.storage.impl.local.statistic.OPerformanceStatisticManager;
import com.orientechnologies.orient.core.storage.impl.local.statistic.OSessionStoragePerformanceStatistic;
import com.orientechnologies.orient.core.storage.index.engine.OHashTableIndexEngine;
import com.orientechnologies.orient.core.storage.index.engine.OPrefixBTreeIndexEngine;
import com.orientechnologies.orient.core.storage.index.engine.OSBTreeIndexEngine;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OIndexRIDContainerSBTree;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OSBTreeCollectionManager;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OSBTreeCollectionManagerAbstract;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OSBTreeCollectionManagerShared;
import com.orientechnologies.orient.core.tx.OTransactionAbstract;
import com.orientechnologies.orient.core.tx.OTransactionIndexChanges;
import com.orientechnologies.orient.core.tx.OTransactionInternal;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.locks.Lock;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author Andrey Lomakin (a.lomakin-at-orientdb.com)
* @since 28.03.13
*/
public abstract class OAbstractPaginatedStorage extends OStorageAbstract
implements OLowDiskSpaceListener, OCheckpointRequestListener, OIdentifiableStorage, OBackgroundExceptionListener,
OFreezableStorageComponent, OPageIsBrokenListener {
private static final int WAL_RESTORE_REPORT_INTERVAL = 30 * 1000; // milliseconds
private static final Comparator<ORecordOperation> COMMIT_RECORD_OPERATION_COMPARATOR = Comparator
.comparing(o -> o.getRecord().getIdentity());
protected static final OScheduledThreadPoolExecutorWithLogging fuzzyCheckpointExecutor;
static {
fuzzyCheckpointExecutor = new OScheduledThreadPoolExecutorWithLogging(1, new FuzzyCheckpointThreadFactory());
fuzzyCheckpointExecutor.setMaximumPoolSize(1);
}
private final OSimpleRWLockManager<ORID> lockManager;
/**
* Lock is used to atomically update record versions.
*/
private final OLockManager<ORID> recordVersionManager;
private final Map<String, OCluster> clusterMap = new HashMap<>();
private final List<OCluster> clusters = new ArrayList<>();
private volatile ThreadLocal<OStorageTransaction> transaction;
private final AtomicBoolean checkpointInProgress = new AtomicBoolean();
private final AtomicBoolean walVacuumInProgress = new AtomicBoolean();
/**
* Error which happened inside of storage or during data processing related to this storage.
*/
private final AtomicReference<Error> jvmError = new AtomicReference<>();
@SuppressWarnings("WeakerAccess")
protected final OSBTreeCollectionManagerShared sbTreeCollectionManager;
private final OPerformanceStatisticManager performanceStatisticManager = new OPerformanceStatisticManager(this,
OGlobalConfiguration.STORAGE_PROFILER_SNAPSHOT_INTERVAL.getValueAsInteger() * 1000000L,
OGlobalConfiguration.STORAGE_PROFILER_CLEANUP_INTERVAL.getValueAsInteger() * 1000000L);
protected volatile OWriteAheadLog writeAheadLog;
private OStorageRecoverListener recoverListener;
protected volatile OReadCache readCache;
protected volatile OWriteCache writeCache;
private volatile ORecordConflictStrategy recordConflictStrategy = Orient.instance().getRecordConflictStrategy()
.getDefaultImplementation();
private volatile int defaultClusterId = -1;
@SuppressWarnings("WeakerAccess")
protected volatile OAtomicOperationsManager atomicOperationsManager;
private volatile boolean wereNonTxOperationsPerformedInPreviousOpen = false;
private volatile OLowDiskSpaceInformation lowDiskSpace = null;
private volatile boolean modificationLock = false;
private volatile boolean readLock = false;
/**
* Set of pages which were detected as broken and need to be repaired.
*/
private final Set<OPair<String, Long>> brokenPages = Collections
.newSetFromMap(new ConcurrentHashMap<>());
private volatile Throwable dataFlushException = null;
private final int id;
private final Map<String, OIndexEngine> indexEngineNameMap = new HashMap<>();
private final List<OIndexEngine> indexEngines = new ArrayList<>();
private boolean wereDataRestoredAfterOpen = false;
private final LongAdder fullCheckpointCount = new LongAdder();
private final AtomicLong recordCreated = new AtomicLong(0);
private final AtomicLong recordUpdated = new AtomicLong(0);
private final AtomicLong recordRead = new AtomicLong(0);
private final AtomicLong recordDeleted = new AtomicLong(0);
private final AtomicLong recordScanned = new AtomicLong(0);
private final AtomicLong recordRecycled = new AtomicLong(0);
private final AtomicLong recordConflict = new AtomicLong(0);
private final AtomicLong txBegun = new AtomicLong(0);
private final AtomicLong txCommit = new AtomicLong(0);
private final AtomicLong txRollback = new AtomicLong(0);
public OAbstractPaginatedStorage(String name, String filePath, String mode, int id) {
super(name, filePath, mode);
this.id = id;
lockManager = new ONotThreadRWLockManager<>();
recordVersionManager = new OPartitionedLockManager<>();
registerProfilerHooks();
sbTreeCollectionManager = new OSBTreeCollectionManagerShared(this);
}
@Override
public final void open(final String iUserName, final String iUserPassword, final OContextConfiguration contextConfiguration) {
open(contextConfiguration);
}
public final void open(final OContextConfiguration contextConfiguration) {
try {
stateLock.acquireReadLock();
try {
if (status == STATUS.OPEN)
// ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS
// REUSED
{
return;
}
} finally {
stateLock.releaseReadLock();
}
stateLock.acquireWriteLock();
try {
if (status == STATUS.OPEN)
// ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS
// REUSED
{
return;
}
if (!exists()) {
throw new OStorageException("Cannot open the storage '" + name + "' because it does not exist in path: " + url);
}
initLockingStrategy(contextConfiguration);
transaction = new ThreadLocal<>();
((OStorageConfigurationImpl) configuration).load(contextConfiguration);
checkPageSizeAndRelatedParameters();
componentsFactory = new OCurrentStorageComponentsFactory(getConfiguration());
preOpenSteps();
initWalAndDiskCache(contextConfiguration);
atomicOperationsManager = new OAtomicOperationsManager(this);
recoverIfNeeded();
openClusters();
openIndexes();
status = STATUS.OPEN;
final String cs = configuration.getConflictStrategy();
if (cs != null) {
// SET THE CONFLICT STORAGE STRATEGY FROM THE LOADED CONFIGURATION
setConflictStrategy(Orient.instance().getRecordConflictStrategy().getStrategy(cs));
}
readCache.loadCacheState(writeCache);
} catch (OStorageException e) {
throw e;
} catch (Exception e) {
for (OCluster c : clusters) {
try {
if (c != null) {
c.close(false);
}
} catch (IOException e1) {
OLogManager.instance().error(this, "Cannot close cluster after exception on open", e1);
}
}
try {
status = STATUS.OPEN;
close(true, false);
} catch (RuntimeException re) {
OLogManager.instance().error(this, "Error during storage close", re);
}
status = STATUS.CLOSED;
throw OException.wrapException(new OStorageException("Cannot open local storage '" + url + "' with mode=" + mode), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
OLogManager.instance()
.infoNoDb(this, "Storage '%s' is opened under OrientDB distribution : %s", getURL(), OConstants.getVersion());
}
private void initLockingStrategy(OContextConfiguration contextConfiguration) {
String lockKind = contextConfiguration.getValueAsString(OGlobalConfiguration.STORAGE_PESSIMISTIC_LOCKING);
if (OrientDBConfig.LOCK_TYPE_MODIFICATION.equals(lockKind)) {
modificationLock = true;
} else if (OrientDBConfig.LOCK_TYPE_READWRITE.equals(lockKind)) {
modificationLock = true;
readLock = true;
}
}
/**
* That is internal method which is called once we encounter any error inside of JVM. In such case we need to restart JVM to avoid
* any data corruption. Till JVM is not restarted storage will be put in read-only state.
*/
public final void handleJVMError(Error e) {
if (jvmError.compareAndSet(null, e)) {
OLogManager.instance().errorNoDb(this, "JVM error was thrown", e);
}
}
/**
* This method is called by distributed storage during initialization to indicate that database is used in distributed cluster
* configuration
*/
public void underDistributedStorage() {
sbTreeCollectionManager.prohibitAccess();
}
/**
* @inheritDoc
*/
@Override
public final String getCreatedAtVersion() {
return getConfiguration().getCreatedAtVersion();
}
@SuppressWarnings("WeakerAccess")
protected final void openIndexes() {
OCurrentStorageComponentsFactory cf = componentsFactory;
if (cf == null) {
throw new OStorageException("Storage '" + name + "' is not properly initialized");
}
final Set<String> indexNames = getConfiguration().indexEngines();
for (String indexName : indexNames) {
final OStorageConfigurationImpl.IndexEngineData engineData = getConfiguration().getIndexEngine(indexName);
final OIndexEngine engine = OIndexes
.createIndexEngine(engineData.getName(), engineData.getAlgorithm(), engineData.getIndexType(),
engineData.getDurableInNonTxMode(), this, engineData.getVersion(), engineData.getEngineProperties(), null);
try {
OEncryption encryption;
if (engineData.getEncryption() == null || engineData.getEncryption().toLowerCase(configuration.getLocaleInstance())
.equals(ONothingEncryption.NAME)) {
encryption = null;
} else {
encryption = OEncryptionFactory.INSTANCE.getEncryption(engineData.getEncryption(), engineData.getEncryptionOptions());
}
engine.load(engineData.getName(), cf.binarySerializerFactory.getObjectSerializer(engineData.getValueSerializerId()),
engineData.isAutomatic(), cf.binarySerializerFactory.getObjectSerializer(engineData.getKeySerializedId()),
engineData.getKeyTypes(), engineData.isNullValuesSupport(), engineData.getKeySize(), engineData.getEngineProperties(),
encryption);
indexEngineNameMap.put(engineData.getName(), engine);
indexEngines.add(engine);
} catch (RuntimeException e) {
OLogManager.instance()
.error(this, "Index '" + engineData.getName() + "' cannot be created and will be removed from configuration", e);
try {
engine.deleteWithoutLoad(engineData.getName());
} catch (IOException ioe) {
OLogManager.instance().error(this, "Can not delete index " + engineData.getName(), ioe);
}
}
}
}
@SuppressWarnings("WeakerAccess")
protected final void openClusters() throws IOException {
// OPEN BASIC SEGMENTS
int pos;
// REGISTER CLUSTER
final List<OStorageClusterConfiguration> configurationClusters = configuration.getClusters();
for (int i = 0; i < configurationClusters.size(); ++i) {
final OStorageClusterConfiguration clusterConfig = configurationClusters.get(i);
if (clusterConfig != null) {
pos = createClusterFromConfig(clusterConfig);
try {
if (pos == -1) {
clusters.get(i).open();
} else {
if (clusterConfig.getName().equals(CLUSTER_DEFAULT_NAME)) {
defaultClusterId = pos;
}
clusters.get(pos).open();
}
} catch (FileNotFoundException e) {
OLogManager.instance().warn(this, "Error on loading cluster '" + configurationClusters.get(i).getName() + "' (" + i
+ "): file not found. It will be excluded from current database '" + getName() + "'.", e);
clusterMap.remove(configurationClusters.get(i).getName().toLowerCase(configuration.getLocaleInstance()));
setCluster(i, null);
}
} else {
setCluster(i, null);
}
}
}
@SuppressWarnings("unused")
public void open(final OToken iToken, final OContextConfiguration configuration) {
open(iToken.getUserName(), "", configuration);
}
@Override
public void create(OContextConfiguration contextConfiguration) throws IOException {
checkPageSizeAndRelatedParametersInGlobalConfiguration();
try {
stateLock.acquireWriteLock();
try {
if (status != STATUS.CLOSED) {
throw new OStorageExistsException("Cannot create new storage '" + getURL() + "' because it is not closed");
}
if (exists()) {
throw new OStorageExistsException("Cannot create new storage '" + getURL() + "' because it already exists");
}
initLockingStrategy(contextConfiguration);
((OStorageConfigurationImpl) configuration).initConfiguration(contextConfiguration);
componentsFactory = new OCurrentStorageComponentsFactory(getConfiguration());
transaction = new ThreadLocal<>();
initWalAndDiskCache(contextConfiguration);
atomicOperationsManager = new OAtomicOperationsManager(this);
preCreateSteps();
status = STATUS.OPEN;
// ADD THE METADATA CLUSTER TO STORE INTERNAL STUFF
doAddCluster(OMetadataDefault.CLUSTER_INTERNAL_NAME, null);
((OStorageConfigurationImpl) configuration).create();
((OStorageConfigurationImpl) configuration).setCreationVersion(OConstants.getVersion());
((OStorageConfigurationImpl) configuration)
.setPageSize(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
((OStorageConfigurationImpl) configuration)
.setFreeListBoundary(OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getValueAsInteger() * 1024);
((OStorageConfigurationImpl) configuration).setMaxKeySize(OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getValueAsInteger());
// ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF
// INDEXING
doAddCluster(OMetadataDefault.CLUSTER_INDEX_NAME, null);
// ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF
// INDEXING
doAddCluster(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME, null);
// ADD THE DEFAULT CLUSTER
defaultClusterId = doAddCluster(CLUSTER_DEFAULT_NAME, null);
if (jvmError.get() == null) {
clearStorageDirty();
}
if (contextConfiguration.getValueAsBoolean(OGlobalConfiguration.STORAGE_MAKE_FULL_CHECKPOINT_AFTER_CREATE)) {
makeFullCheckpoint();
}
postCreateSteps();
} catch (InterruptedException e) {
throw OException.wrapException(new OStorageException("Storage creation was interrupted"), e);
} catch (OStorageException e) {
close();
throw e;
} catch (IOException e) {
close();
throw OException.wrapException(new OStorageException("Error on creation of storage '" + name + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
OLogManager.instance()
.infoNoDb(this, "Storage '%s' is created under OrientDB distribution : %s", getURL(), OConstants.getVersion());
}
private static void checkPageSizeAndRelatedParametersInGlobalConfiguration() {
final int pageSize = OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024;
final int freeListBoundary = OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getValueAsInteger() * 1024;
final int maxKeySize = OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getValueAsInteger();
if (freeListBoundary > pageSize / 2) {
throw new OStorageException("Value of parameter " + OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getKey()
+ " should be at least 2 times bigger than value of parameter "
+ OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getKey() + " but real values are :"
+ OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getKey() + " = " + pageSize + " , "
+ OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getKey() + " = " + freeListBoundary);
}
if (maxKeySize > pageSize / 4) {
throw new OStorageException("Value of parameter " + OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getKey()
+ " should be at least 4 times bigger than value of parameter " + OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getKey()
+ " but real values are :" + OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getKey() + " = " + pageSize + " , "
+ OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getKey() + " = " + maxKeySize);
}
}
private void checkPageSizeAndRelatedParameters() {
final int pageSize = OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024;
final int freeListBoundary = OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getValueAsInteger() * 1024;
final int maxKeySize = OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getValueAsInteger();
if (configuration.getPageSize() != -1 && configuration.getPageSize() != pageSize) {
throw new OStorageException(
"Storage is created with value of " + OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getKey() + " parameter equal to "
+ configuration.getPageSize() + " but current value is " + pageSize);
}
if (configuration.getFreeListBoundary() != -1 && configuration.getFreeListBoundary() != freeListBoundary) {
throw new OStorageException(
"Storage is created with value of " + OGlobalConfiguration.PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY.getKey()
+ " parameter equal to " + configuration.getFreeListBoundary() + " but current value is " + freeListBoundary);
}
if (configuration.getMaxKeySize() != -1 && configuration.getMaxKeySize() != maxKeySize) {
throw new OStorageException(
"Storage is created with value of " + OGlobalConfiguration.SBTREE_MAX_KEY_SIZE.getKey() + " parameter equal to "
+ configuration.getMaxKeySize() + " but current value is " + maxKeySize);
}
}
@Override
public final boolean isClosed() {
try {
stateLock.acquireReadLock();
try {
return super.isClosed();
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final void close(final boolean force, boolean onDelete) {
try {
doClose(force, onDelete);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final void delete() {
try {
final long timer = Orient.instance().getProfiler().startChrono();
stateLock.acquireWriteLock();
try {
try {
// CLOSE THE DATABASE BY REMOVING THE CURRENT USER
close(true, true);
if (writeCache != null) {
if (readCache != null) {
readCache.deleteStorage(writeCache);
} else {
writeCache.delete();
}
}
postDeleteSteps();
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot delete database '" + name + "'"), e);
}
} finally {
stateLock.releaseWriteLock();
//noinspection ResultOfMethodCallIgnored
Orient.instance().getProfiler().stopChrono("db." + name + ".drop", "Drop a database", timer, "db.*.drop");
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public boolean check(final boolean verbose, final OCommandOutputListener listener) {
try {
listener.onMessage("Check of storage is started...");
checkOpenness();
stateLock.acquireReadLock();
try {
final long lockId = atomicOperationsManager.freezeAtomicOperations(null, null);
try {
checkOpenness();
final long start = System.currentTimeMillis();
OPageDataVerificationError[] pageErrors = writeCache.checkStoredPages(verbose ? listener : null);
listener.onMessage(
"Check of storage completed in " + (System.currentTimeMillis() - start) + "ms. " + (pageErrors.length > 0 ?
pageErrors.length + " with errors." :
" without errors."));
return pageErrors.length == 0;
} finally {
atomicOperationsManager.releaseAtomicOperations(lockId);
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int addCluster(String clusterName, final Object... parameters) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
stateLock.acquireWriteLock();
try {
checkOpenness();
makeStorageDirty();
return doAddCluster(clusterName, parameters);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error in creation of new cluster '" + clusterName), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int addCluster(String clusterName, int requestedId, Object... parameters) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
stateLock.acquireWriteLock();
try {
checkOpenness();
if (requestedId < 0) {
throw new OConfigurationException("Cluster id must be positive!");
}
if (requestedId < clusters.size() && clusters.get(requestedId) != null) {
throw new OConfigurationException(
"Requested cluster ID [" + requestedId + "] is occupied by cluster with name [" + clusters.get(requestedId).getName()
+ "]");
}
makeStorageDirty();
return addClusterInternal(clusterName, requestedId, parameters);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error in creation of new cluster '" + clusterName + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final boolean dropCluster(final int clusterId, final boolean iTruncate) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
stateLock.acquireWriteLock();
try {
checkOpenness();
if (clusterId < 0 || clusterId >= clusters.size()) {
throw new IllegalArgumentException(
"Cluster id '" + clusterId + "' is outside the of range of configured clusters (0-" + (clusters.size() - 1)
+ ") in database '" + name + "'");
}
final OCluster cluster = clusters.get(clusterId);
if (cluster == null) {
return false;
}
if (iTruncate) {
cluster.truncate();
}
cluster.delete();
makeStorageDirty();
clusterMap.remove(cluster.getName().toLowerCase(configuration.getLocaleInstance()));
clusters.set(clusterId, null);
// UPDATE CONFIGURATION
getConfiguration().dropCluster(clusterId);
return true;
} catch (Exception e) {
throw OException.wrapException(new OStorageException("Error while removing cluster '" + clusterId + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int getId() {
return id;
}
public boolean setClusterStatus(final int clusterId, final OStorageClusterConfiguration.STATUS iStatus) {
try {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
if (clusterId < 0 || clusterId >= clusters.size()) {
throw new IllegalArgumentException(
"Cluster id '" + clusterId + "' is outside the of range of configured clusters (0-" + (clusters.size() - 1)
+ ") in database '" + name + "'");
}
final OCluster cluster = clusters.get(clusterId);
if (cluster == null) {
return false;
}
if (iStatus == OStorageClusterConfiguration.STATUS.OFFLINE && cluster instanceof OOfflineCluster
|| iStatus == OStorageClusterConfiguration.STATUS.ONLINE && !(cluster instanceof OOfflineCluster)) {
return false;
}
final OCluster newCluster;
if (iStatus == OStorageClusterConfiguration.STATUS.OFFLINE) {
cluster.close(true);
newCluster = new OOfflineCluster(this, clusterId, cluster.getName());
boolean configured = false;
for (OStorageClusterConfiguration clusterConfiguration : configuration.getClusters()) {
if (clusterConfiguration.getId() == cluster.getId()) {
newCluster.configure(this, clusterConfiguration);
configured = true;
break;
}
}
if (!configured) {
throw new OStorageException("Can not configure offline cluster with id " + clusterId);
}
} else {
newCluster = OPaginatedClusterFactory
.createCluster(cluster.getName(), configuration.getVersion(), cluster.getBinaryVersion(), this);
newCluster.configure(this, clusterId, cluster.getName());
newCluster.open();
}
clusterMap.put(cluster.getName().toLowerCase(configuration.getLocaleInstance()), newCluster);
clusters.set(clusterId, newCluster);
// UPDATE CONFIGURATION
makeStorageDirty();
((OStorageConfigurationImpl) configuration).setClusterStatus(clusterId, iStatus);
makeFullCheckpoint();
return true;
} catch (Exception e) {
throw OException.wrapException(new OStorageException("Error while removing cluster '" + clusterId + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OSBTreeCollectionManager getSBtreeCollectionManager() {
return sbTreeCollectionManager;
}
public OReadCache getReadCache() {
return readCache;
}
public OWriteCache getWriteCache() {
return writeCache;
}
@Override
public final long count(final int iClusterId) {
return count(iClusterId, false);
}
@Override
public final long count(int clusterId, boolean countTombstones) {
try {
if (clusterId == -1) {
throw new OStorageException("Cluster Id " + clusterId + " is invalid in database '" + name + "'");
}
// COUNT PHYSICAL CLUSTER IF ANY
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = clusters.get(clusterId);
if (cluster == null) {
return 0;
}
if (countTombstones) {
return cluster.getEntries();
}
return cluster.getEntries() - cluster.getTombstonesCount();
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final long[] getClusterDataRange(final int iClusterId) {
try {
if (iClusterId == -1) {
return new long[] { ORID.CLUSTER_POS_INVALID, ORID.CLUSTER_POS_INVALID };
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return clusters.get(iClusterId) != null ?
new long[] { clusters.get(iClusterId).getFirstPosition(), clusters.get(iClusterId).getLastPosition() } :
OCommonConst.EMPTY_LONG_ARRAY;
} catch (IOException ioe) {
throw OException.wrapException(new OStorageException("Cannot retrieve information about data range"), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public OLogSequenceNumber getLSN() {
try {
if (writeAheadLog == null) {
return null;
}
return writeAheadLog.end();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final long count(final int[] iClusterIds) {
return count(iClusterIds, false);
}
@Override
public final void onException(Throwable e) {
dataFlushException = e;
}
/**
* This method finds all the records which were updated starting from (but not including) current LSN and write result in provided
* output stream. In output stream will be included all thw records which were updated/deleted/created since passed in LSN till
* the current moment. Deleted records are written in output stream first, then created/updated records. All records are sorted by
* record id. Data format: <ol> <li>Amount of records (single entry) - 8 bytes</li> <li>Record's cluster id - 4 bytes</li>
* <li>Record's cluster position - 8 bytes</li> <li>Delete flag, 1 if record is deleted - 1 byte</li> <li>Record version , only
* if record is not deleted - 4 bytes</li> <li>Record type, only if record is not deleted - 1 byte</li> <li>Length of binary
* presentation of record, only if record is not deleted - 4 bytes</li> <li>Binary presentation of the record, only if record is
* not deleted - length of content is provided in above entity</li> </ol>
*
* @param lsn LSN from which we should find changed records
* @param stream Stream which will contain found records
*
* @return Last LSN processed during examination of changed records, or <code>null</code> if it was impossible to find changed
* records: write ahead log is absent, record with start LSN was not found in WAL, etc.
*
* @see OGlobalConfiguration#STORAGE_TRACK_CHANGED_RECORDS_IN_WAL
*/
public OLogSequenceNumber recordsChangedAfterLSN(final OLogSequenceNumber lsn, final OutputStream stream,
final OCommandOutputListener outputListener) {
try {
if (!getConfiguration().getContextConfiguration()
.getValueAsBoolean(OGlobalConfiguration.STORAGE_TRACK_CHANGED_RECORDS_IN_WAL)) {
throw new IllegalStateException(
"Cannot find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, "
+ "to switch it on please set property " + OGlobalConfiguration.STORAGE_TRACK_CHANGED_RECORDS_IN_WAL.getKey()
+ " to the true value, please note that only records"
+ " which are stored after this property was set will be retrieved");
}
stateLock.acquireReadLock();
try {
if (writeAheadLog == null) {
return null;
}
// we iterate till the last record is contained in wal at the moment when we call this method
final OLogSequenceNumber endLsn = writeAheadLog.end();
if (endLsn == null || lsn.compareTo(endLsn) > 0) {
OLogManager.instance()
.warn(this, "Cannot find requested LSN=%s for database sync operation. Last available LSN is %s", lsn, endLsn);
return null;
}
if (lsn.equals(endLsn)) {
// nothing has changed
return endLsn;
}
// container of rids of changed records
final SortedSet<ORID> sortedRids = new TreeSet<>();
List<OWriteableWALRecord> records = writeAheadLog.next(lsn, 1);
if (records.isEmpty()) {
OLogManager.instance()
.info(this, "Cannot find requested LSN=%s for database sync operation (last available LSN is %s)", lsn, endLsn);
return null;
}
final OLogSequenceNumber freezeLsn = records.get(0).getLsn();
writeAheadLog.addCutTillLimit(freezeLsn);
try {
records = writeAheadLog.next(lsn, 1_000);
if (records.isEmpty()) {
OLogManager.instance()
.info(this, "Cannot find requested LSN=%s for database sync operation (last available LSN is %s)", lsn, endLsn);
return null;
}
// all information about changed records is contained in atomic operation metadata
long read = 0;
readLoop:
while (!records.isEmpty()) {
for (OWALRecord record : records) {
final OLogSequenceNumber recordLSN = record.getLsn();
if (endLsn.compareTo(recordLSN) >= 0) {
if (record instanceof OFileCreatedWALRecord) {
throw new ODatabaseException(
"Cannot execute delta-sync because a new file has been added. Filename: '" + ((OFileCreatedWALRecord) record)
.getFileName() + "' (id=" + ((OFileCreatedWALRecord) record).getFileId() + ")");
}
if (record instanceof OFileDeletedWALRecord) {
throw new ODatabaseException(
"Cannot execute delta-sync because a file has been deleted. File id: " + ((OFileDeletedWALRecord) record)
.getFileId());
}
if (record instanceof OAtomicUnitEndRecord) {
final OAtomicUnitEndRecord atomicUnitEndRecord = (OAtomicUnitEndRecord) record;
if (atomicUnitEndRecord.getAtomicOperationMetadata().containsKey(ORecordOperationMetadata.RID_METADATA_KEY)) {
final ORecordOperationMetadata recordOperationMetadata = (ORecordOperationMetadata) atomicUnitEndRecord
.getAtomicOperationMetadata().get(ORecordOperationMetadata.RID_METADATA_KEY);
final Set<ORID> rids = recordOperationMetadata.getValue();
sortedRids.addAll(rids);
}
}
read++;
if (outputListener != null) {
outputListener.onMessage("read " + read + " records from WAL and collected " + sortedRids.size() + " records");
}
} else {
break readLoop;
}
}
records = writeAheadLog.next(records.get(records.size() - 1).getLsn(), 1_000);
}
} finally {
writeAheadLog.removeCutTillLimit(freezeLsn);
}
final int totalRecords = sortedRids.size();
OLogManager.instance().info(this, "Exporting records after LSN=%s. Found %d records", lsn, totalRecords);
// records may be deleted after we flag them as existing and as result rule of sorting of records
// (deleted records go first will be broken), so we prohibit any modifications till we do not complete method execution
final long lockId = atomicOperationsManager.freezeAtomicOperations(null, null);
try {
try (DataOutputStream dataOutputStream = new DataOutputStream(stream)) {
dataOutputStream.writeLong(sortedRids.size());
long exportedRecord = 1;
Iterator<ORID> ridIterator = sortedRids.iterator();
while (ridIterator.hasNext()) {
final ORID rid = ridIterator.next();
final OCluster cluster = clusters.get(rid.getClusterId());
// we do not need to load record only check it's presence
if (cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition())) == null) {
dataOutputStream.writeInt(rid.getClusterId());
dataOutputStream.writeLong(rid.getClusterPosition());
dataOutputStream.write(1);
OLogManager.instance().debug(this, "Exporting deleted record %s", rid);
if (outputListener != null) {
outputListener.onMessage("exporting record " + exportedRecord + "/" + totalRecords);
}
// delete to avoid duplication
ridIterator.remove();
exportedRecord++;
}
}
ridIterator = sortedRids.iterator();
while (ridIterator.hasNext()) {
final ORID rid = ridIterator.next();
final OCluster cluster = clusters.get(rid.getClusterId());
dataOutputStream.writeInt(rid.getClusterId());
dataOutputStream.writeLong(rid.getClusterPosition());
if (cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition())) == null) {
dataOutputStream.writeBoolean(true);
OLogManager.instance().debug(this, "Exporting deleted record %s", rid);
} else {
final ORawBuffer rawBuffer = cluster.readRecord(rid.getClusterPosition(), false);
assert rawBuffer != null;
dataOutputStream.writeBoolean(false);
dataOutputStream.writeInt(rawBuffer.version);
dataOutputStream.write(rawBuffer.recordType);
dataOutputStream.writeInt(rawBuffer.buffer.length);
dataOutputStream.write(rawBuffer.buffer);
OLogManager.instance().debug(this, "Exporting modified record rid=%s type=%d size=%d v=%d - buffer size=%d", rid,
rawBuffer.recordType, rawBuffer.buffer.length, rawBuffer.version, dataOutputStream.size());
}
if (outputListener != null) {
outputListener.onMessage("exporting record " + exportedRecord + "/" + totalRecords);
}
exportedRecord++;
}
}
} finally {
atomicOperationsManager.releaseAtomicOperations(lockId);
}
return endLsn;
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error of reading of records changed after LSN " + lsn), e);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException e) {
throw logAndPrepareForRethrow(e);
} catch (Error e) {
throw logAndPrepareForRethrow(e);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* This method finds all the records changed in the last X transactions.
*
* @param maxEntries Maximum number of entries to check back from last log.
*
* @return A set of record ids of the changed records
*
* @see OGlobalConfiguration#STORAGE_TRACK_CHANGED_RECORDS_IN_WAL
*/
public Set<ORecordId> recordsChangedRecently(final int maxEntries) {
final SortedSet<ORecordId> result = new TreeSet<>();
try {
if (!OGlobalConfiguration.STORAGE_TRACK_CHANGED_RECORDS_IN_WAL.getValueAsBoolean()) {
throw new IllegalStateException(
"Cannot find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, "
+ "to switch it on please set property " + OGlobalConfiguration.STORAGE_TRACK_CHANGED_RECORDS_IN_WAL.getKey()
+ " to the true value, please note that only records"
+ " which are stored after this property was set will be retrieved");
}
stateLock.acquireReadLock();
try {
if (writeAheadLog == null) {
OLogManager.instance().warn(this, "No WAL found for database '%s'", name);
return null;
}
OLogSequenceNumber startLsn = writeAheadLog.begin();
if (startLsn == null) {
OLogManager.instance().warn(this, "The WAL is empty for database '%s'", name);
return result;
}
final OLogSequenceNumber freezeLSN = startLsn;
writeAheadLog.addCutTillLimit(freezeLSN);
try {
//reread because log may be already truncated
startLsn = writeAheadLog.begin();
if (startLsn == null) {
OLogManager.instance().warn(this, "The WAL is empty for database '%s'", name);
return result;
}
final OLogSequenceNumber endLsn = writeAheadLog.end();
if (endLsn == null) {
OLogManager.instance().warn(this, "The WAL is empty for database '%s'", name);
return result;
}
List<OWriteableWALRecord> walRecords = writeAheadLog.read(startLsn, 1_000);
if (walRecords.isEmpty()) {
OLogManager.instance()
.info(this, "Cannot find requested LSN=%s for database sync operation (record in WAL is absent)", startLsn);
return null;
}
// KEEP LAST MAX-ENTRIES TRANSACTIONS' LSN
final List<OAtomicUnitEndRecord> lastTx = new ArrayList<>();
readLoop:
while (!walRecords.isEmpty()) {
for (OWriteableWALRecord walRecord : walRecords) {
final OLogSequenceNumber recordLSN = walRecord.getLsn();
if (endLsn.compareTo(recordLSN) >= 0) {
if (walRecord instanceof OAtomicUnitEndRecord) {
if (lastTx.size() >= maxEntries) {
lastTx.remove(0);
}
lastTx.add((OAtomicUnitEndRecord) walRecord);
}
} else {
break readLoop;
}
}
walRecords = writeAheadLog.next(walRecords.get(walRecords.size() - 1).getLsn(), 1_000);
}
// COLLECT ALL THE MODIFIED RECORDS
for (OAtomicUnitEndRecord atomicUnitEndRecord : lastTx) {
if (atomicUnitEndRecord.getAtomicOperationMetadata().containsKey(ORecordOperationMetadata.RID_METADATA_KEY)) {
final ORecordOperationMetadata recordOperationMetadata = (ORecordOperationMetadata) atomicUnitEndRecord
.getAtomicOperationMetadata().get(ORecordOperationMetadata.RID_METADATA_KEY);
final Set<ORID> rids = recordOperationMetadata.getValue();
for (ORID rid : rids) {
result.add((ORecordId) rid);
}
}
}
OLogManager.instance().info(this, "Found %d records changed in last %d operations", result.size(), lastTx.size());
return result;
} finally {
writeAheadLog.removeCutTillLimit(freezeLSN);
}
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error on reading last changed records"), e);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException e) {
throw logAndPrepareForRethrow(e);
} catch (Error e) {
throw logAndPrepareForRethrow(e);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final long count(int[] iClusterIds, boolean countTombstones) {
try {
checkOpenness();
long tot = 0;
stateLock.acquireReadLock();
try {
checkOpenness();
for (int iClusterId : iClusterIds) {
if (iClusterId >= clusters.size()) {
throw new OConfigurationException("Cluster id " + iClusterId + " was not found in database '" + name + "'");
}
if (iClusterId > -1) {
final OCluster c = clusters.get(iClusterId);
if (c != null) {
tot += c.getEntries() - (countTombstones ? 0L : c.getTombstonesCount());
}
}
}
return tot;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final OStorageOperationResult<OPhysicalPosition> createRecord(final ORecordId rid, final byte[] content,
final int recordVersion, final byte recordType, final ORecordCallback<Long> callback) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
final OCluster cluster = getClusterById(rid.getClusterId());
if (transaction.get() != null) {
return doCreateRecord(rid, content, recordVersion, recordType, callback, cluster, null);
}
stateLock.acquireReadLock();
try {
checkOpenness();
return doCreateRecord(rid, content, recordVersion, recordType, callback, cluster, null);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final ORecordMetadata getRecordMetadata(ORID rid) {
try {
if (rid.isNew()) {
throw new OStorageException("Passed record with id " + rid + " is new and cannot be stored.");
}
checkOpenness();
stateLock.acquireReadLock();
try {
final OCluster cluster = getClusterById(rid.getClusterId());
checkOpenness();
final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition()));
if (ppos == null) {
return null;
}
return new ORecordMetadata(rid, ppos.recordVersion);
} catch (IOException ioe) {
OLogManager.instance().error(this, "Retrieval of record '" + rid + "' cause: " + ioe.getMessage(), ioe);
} finally {
stateLock.releaseReadLock();
}
return null;
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public boolean isDeleted(ORID rid) {
try {
if (rid.isNew()) {
throw new OStorageException("Passed record with id " + rid + " is new and cannot be stored.");
}
checkOpenness();
stateLock.acquireReadLock();
try {
final OCluster cluster = getClusterById(rid.getClusterId());
checkOpenness();
return cluster.isDeleted(new OPhysicalPosition(rid.getClusterPosition()));
} catch (IOException ioe) {
OLogManager.instance().error(this, "Retrieval of record '" + rid + "' cause: " + ioe.getMessage(), ioe);
} finally {
stateLock.releaseReadLock();
}
return false;
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public Iterator<OClusterBrowsePage> browseCluster(int clusterId) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final int finalClusterId;
if (clusterId == ORID.CLUSTER_ID_INVALID) {
// GET THE DEFAULT CLUSTER
finalClusterId = defaultClusterId;
} else {
finalClusterId = clusterId;
}
return new Iterator<OClusterBrowsePage>() {
private OClusterBrowsePage page = null;
private long lastPos = -1;
@Override
public boolean hasNext() {
if (page == null) {
page = nextPage(finalClusterId, lastPos);
if (page != null) {
lastPos = page.getLastPosition();
}
}
return page != null;
}
@Override
public OClusterBrowsePage next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
OClusterBrowsePage curPage = page;
page = null;
return curPage;
}
};
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OClusterBrowsePage nextPage(int clusterId, long lastPosition) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = doGetAndCheckCluster(clusterId);
return cluster.nextPage(lastPosition);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OCluster doGetAndCheckCluster(int clusterId) {
checkClusterSegmentIndexRange(clusterId);
final OCluster cluster = clusters.get(clusterId);
if (cluster == null) {
throw new IllegalArgumentException("Cluster " + clusterId + " is null");
}
return cluster;
}
@Override
public OStorageOperationResult<ORawBuffer> readRecord(final ORecordId iRid, final String iFetchPlan, boolean iIgnoreCache,
boolean prefetchRecords, ORecordCallback<ORawBuffer> iCallback) {
try {
checkOpenness();
final OCluster cluster;
try {
cluster = getClusterById(iRid.getClusterId());
} catch (IllegalArgumentException e) {
throw OException.wrapException(new ORecordNotFoundException(iRid), e);
}
return new OStorageOperationResult<>(readRecord(cluster, iRid, prefetchRecords));
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OStorageOperationResult<ORawBuffer> readRecordIfVersionIsNotLatest(final ORecordId rid, final String fetchPlan,
final boolean ignoreCache, final int recordVersion) throws ORecordNotFoundException {
try {
checkOpenness();
return new OStorageOperationResult<>(readRecordIfNotLatest(getClusterById(rid.getClusterId()), rid, recordVersion));
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final OStorageOperationResult<Integer> updateRecord(final ORecordId rid, final boolean updateContent, final byte[] content,
final int version, final byte recordType, @SuppressWarnings("unused") final int mode,
final ORecordCallback<Integer> callback) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
final OCluster cluster = getClusterById(rid.getClusterId());
if (transaction.get() != null) {
return doUpdateRecord(rid, updateContent, content, version, recordType, callback, cluster);
}
stateLock.acquireReadLock();
try {
// GET THE SHARED LOCK AND GET AN EXCLUSIVE LOCK AGAINST THE RECORD
final Lock lock = recordVersionManager.acquireExclusiveLock(rid);
try {
checkOpenness();
// UPDATE IT
return doUpdateRecord(rid, updateContent, content, version, recordType, callback, cluster);
} finally {
lock.unlock();
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OStorageOperationResult<Integer> recyclePosition(final ORecordId rid, final byte[] content, final int version,
final byte recordType) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
final OCluster cluster = getClusterById(rid.getClusterId());
if (transaction.get() != null) {
return doRecycleRecord(rid, content, version, cluster, recordType);
}
stateLock.acquireReadLock();
try {
// GET THE SHARED LOCK AND GET AN EXCLUSIVE LOCK AGAINST THE RECORD
final Lock lock = recordVersionManager.acquireExclusiveLock(rid);
try {
checkOpenness();
// RECYCLING IT
return doRecycleRecord(rid, content, version, cluster, recordType);
} finally {
lock.unlock();
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public OStorageTransaction getStorageTransaction() {
return transaction.get();
}
public OAtomicOperationsManager getAtomicOperationsManager() {
return atomicOperationsManager;
}
public OWriteAheadLog getWALInstance() {
return writeAheadLog;
}
@Override
public final OStorageOperationResult<Boolean> deleteRecord(final ORecordId rid, final int version, final int mode,
ORecordCallback<Boolean> callback) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
final OCluster cluster = getClusterById(rid.getClusterId());
if (transaction.get() != null) {
return doDeleteRecord(rid, version, cluster);
}
stateLock.acquireReadLock();
try {
checkOpenness();
return doDeleteRecord(rid, version, cluster);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OStorageOperationResult<Boolean> hideRecord(final ORecordId rid, final int mode, ORecordCallback<Boolean> callback) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
final OCluster cluster = getClusterById(rid.getClusterId());
if (transaction.get() != null) {
return doHideMethod(rid, cluster);
}
stateLock.acquireReadLock();
try {
final Lock lock = recordVersionManager.acquireExclusiveLock(rid);
try {
checkOpenness();
return doHideMethod(rid, cluster);
} finally {
lock.unlock();
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
protected OPerformanceStatisticManager getPerformanceStatisticManager() {
return performanceStatisticManager;
}
/**
* Starts to gather information about storage performance for current thread. Details which performance characteristics are
* gathered can be found at {@link OSessionStoragePerformanceStatistic}.
*
* @see #completeGatheringPerformanceStatisticForCurrentThread()
*/
public void startGatheringPerformanceStatisticForCurrentThread() {
try {
performanceStatisticManager.startThreadMonitoring();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Completes gathering performance characteristics for current thread initiated by call of {@link
* #startGatheringPerformanceStatisticForCurrentThread()}
*
* @return Performance statistic gathered after call of {@link #startGatheringPerformanceStatisticForCurrentThread()} or
* <code>null</code> if profiling of storage was not started.
*/
public OSessionStoragePerformanceStatistic completeGatheringPerformanceStatisticForCurrentThread() {
try {
return performanceStatisticManager.stopThreadMonitoring();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final <V> V callInLock(Callable<V> iCallable, boolean iExclusiveLock) {
try {
stateLock.acquireReadLock();
try {
if (iExclusiveLock) {
return super.callInLock(iCallable, true);
} else {
return super.callInLock(iCallable, false);
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final Set<String> getClusterNames() {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return new HashSet<>(clusterMap.keySet());
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int getClusterIdByName(final String clusterName) {
try {
checkOpenness();
if (clusterName == null) {
throw new IllegalArgumentException("Cluster name is null");
}
if (clusterName.length() == 0) {
throw new IllegalArgumentException("Cluster name is empty");
}
// if (Character.isDigit(clusterName.charAt(0)))
// return Integer.parseInt(clusterName);
stateLock.acquireReadLock();
try {
checkOpenness();
// SEARCH IT BETWEEN PHYSICAL CLUSTERS
final OCluster segment = clusterMap.get(clusterName.toLowerCase(configuration.getLocaleInstance()));
if (segment != null) {
return segment.getId();
}
return -1;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Scan the given transaction for new record and allocate a record id for them, the relative record id is inserted inside the
* transaction for future use.
*
* @param clientTx the transaction of witch allocate rids
*/
public void preallocateRids(final OTransactionInternal clientTx) {
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
@SuppressWarnings("unchecked")
final Iterable<ORecordOperation> entries = clientTx.getRecordOperations();
final TreeMap<Integer, OCluster> clustersToLock = new TreeMap<>();
final Set<ORecordOperation> newRecords = new TreeSet<>(COMMIT_RECORD_OPERATION_COMPARATOR);
for (ORecordOperation txEntry : entries) {
if (txEntry.type == ORecordOperation.CREATED) {
newRecords.add(txEntry);
int clusterId = txEntry.getRID().getClusterId();
clustersToLock.put(clusterId, getClusterById(clusterId));
}
}
stateLock.acquireReadLock();
try {
checkOpenness();
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
lockClusters(clustersToLock);
for (ORecordOperation txEntry : newRecords) {
ORecord rec = txEntry.getRecord();
if (!rec.getIdentity().isPersistent()) {
if (rec.isDirty()) {
//This allocate a position for a new record
ORecordId rid = (ORecordId) rec.getIdentity().copy();
ORecordId oldRID = rid.copy();
final OCluster cluster = getClusterById(rid.getClusterId());
OPhysicalPosition ppos = cluster.allocatePosition(ORecordInternal.getRecordType(rec));
rid.setClusterPosition(ppos.clusterPosition);
clientTx.updateIdentityAfterCommit(oldRID, rid);
}
} else {
//This allocate position starting from a valid rid, used in distributed for allocate the same position on other nodes
ORecordId rid = (ORecordId) rec.getIdentity();
final OCluster cluster = getClusterById(rid.getClusterId());
OPhysicalPosition ppos = cluster.allocatePosition(ORecordInternal.getRecordType(rec));
if (ppos.clusterPosition != rid.getClusterPosition()) {
throw new OConcurrentCreateException(rid, new ORecordId(rid.getClusterId(), ppos.clusterPosition));
}
}
}
} catch (Exception e) {
rollback = true;
throw e;
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
} catch (IOException | RuntimeException ioe) {
throw OException.wrapException(new OStorageException("Could not preallocate RIDs"), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Traditional commit that support already temporary rid and already assigned rids
*
* @param clientTx the transaction to commit
*
* @return The list of operations applied by the transaction
*/
@Override
public List<ORecordOperation> commit(final OTransactionInternal clientTx) {
return commit(clientTx, false);
}
/**
* Commit a transaction where the rid where pre-allocated in a previous phase
*
* @param clientTx the pre-allocated transaction to commit
*
* @return The list of operations applied by the transaction
*/
@SuppressWarnings("UnusedReturnValue")
public List<ORecordOperation> commitPreAllocated(final OTransactionInternal clientTx) {
return commit(clientTx, true);
}
/**
* The commit operation can be run in 3 different conditions, embedded commit, pre-allocated commit, other node commit.
* <bold>Embedded commit</bold> is the basic commit where the operation is run in embedded or server side, the transaction arrive
* with invalid rids that get allocated and committed.
* <bold>pre-allocated commit</bold> is the commit that happen after an preAllocateRids call is done, this is usually run by the
* coordinator of a tx in distributed.
* <bold>other node commit</bold> is the commit that happen when a node execute a transaction of another node where all the rids
* are already allocated in the other node.
*
* @param transaction the transaction to commit
* @param allocated true if the operation is pre-allocated commit
*
* @return The list of operations applied by the transaction
*/
private List<ORecordOperation> commit(final OTransactionInternal transaction, boolean allocated) {
// XXX: At this moment, there are two implementations of the commit method. One for regular client transactions and one for
// implicit micro-transactions. The implementations are quite identical, but operate on slightly different data. If you change
// this method don't forget to change its counterpart:
//
// OAbstractPaginatedStorage.commit(com.orientechnologies.orient.core.storage.impl.local.OMicroTransaction)
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
txBegun.incrementAndGet();
final ODatabaseDocumentInternal database = transaction.getDatabase();
final OIndexManager indexManager = database.getMetadata().getIndexManager();
final TreeMap<String, OTransactionIndexChanges> indexOperations = getSortedIndexOperations(transaction);
database.getMetadata().makeThreadLocalSchemaSnapshot();
final Collection<ORecordOperation> recordOperations = transaction.getRecordOperations();
final TreeMap<Integer, OCluster> clustersToLock = new TreeMap<>();
final Map<ORecordOperation, Integer> clusterOverrides = new IdentityHashMap<>();
final Set<ORecordOperation> newRecords = new TreeSet<>(COMMIT_RECORD_OPERATION_COMPARATOR);
for (ORecordOperation recordOperation : recordOperations) {
if (recordOperation.type == ORecordOperation.CREATED || recordOperation.type == ORecordOperation.UPDATED) {
final ORecord record = recordOperation.getRecord();
if (record instanceof ODocument) {
((ODocument) record).validate();
}
}
if (recordOperation.type == ORecordOperation.UPDATED || recordOperation.type == ORecordOperation.DELETED) {
final int clusterId = recordOperation.getRecord().getIdentity().getClusterId();
clustersToLock.put(clusterId, getClusterById(clusterId));
} else if (recordOperation.type == ORecordOperation.CREATED) {
newRecords.add(recordOperation);
final ORecord record = recordOperation.getRecord();
final ORID rid = record.getIdentity();
int clusterId = rid.getClusterId();
if (record.isDirty() && clusterId == ORID.CLUSTER_ID_INVALID && record instanceof ODocument) {
// TRY TO FIX CLUSTER ID TO THE DEFAULT CLUSTER ID DEFINED IN SCHEMA CLASS
final OImmutableClass class_ = ODocumentInternal.getImmutableSchemaClass(((ODocument) record));
if (class_ != null) {
clusterId = class_.getClusterForNewInstance((ODocument) record);
clusterOverrides.put(recordOperation, clusterId);
}
}
clustersToLock.put(clusterId, getClusterById(clusterId));
}
}
final List<ORecordOperation> result = new ArrayList<>();
stateLock.acquireReadLock();
try {
if (modificationLock) {
List<ORID> recordLocks = new ArrayList<>();
for (ORecordOperation recordOperation : recordOperations) {
if (recordOperation.type == ORecordOperation.UPDATED || recordOperation.type == ORecordOperation.DELETED) {
recordLocks.add(recordOperation.getRID());
}
}
Set<ORID> locked = transaction.getLockedRecords();
if (locked != null) {
recordLocks.removeAll(locked);
}
Collections.sort(recordLocks);
for (ORID rid : recordLocks) {
acquireWriteLock(rid);
}
}
try {
checkOpenness();
makeStorageDirty();
boolean rollback = false;
startStorageTx(transaction);
try {
final OAtomicOperation atomicOperation = OAtomicOperationsManager.getCurrentOperation();
lockClusters(clustersToLock);
checkReadOnlyConditions();
Map<ORecordOperation, OPhysicalPosition> positions = new IdentityHashMap<>();
for (ORecordOperation recordOperation : newRecords) {
ORecord rec = recordOperation.getRecord();
if (allocated) {
if (rec.getIdentity().isPersistent()) {
positions.put(recordOperation, new OPhysicalPosition(rec.getIdentity().getClusterPosition()));
} else {
throw new OStorageException("Impossible to commit a transaction with not valid rid in pre-allocated commit");
}
} else if (rec.isDirty() && !rec.getIdentity().isPersistent()) {
ORecordId rid = (ORecordId) rec.getIdentity().copy();
ORecordId oldRID = rid.copy();
final Integer clusterOverride = clusterOverrides.get(recordOperation);
final int clusterId = clusterOverride == null ? rid.getClusterId() : clusterOverride;
final OCluster cluster = getClusterById(clusterId);
assert atomicOperation.getCounter() == 1;
OPhysicalPosition physicalPosition = cluster.allocatePosition(ORecordInternal.getRecordType(rec));
assert atomicOperation.getCounter() == 1;
rid.setClusterId(cluster.getId());
if (rid.getClusterPosition() > -1) {
// CREATE EMPTY RECORDS UNTIL THE POSITION IS REACHED. THIS IS THE CASE WHEN A SERVER IS OUT OF SYNC
// BECAUSE A TRANSACTION HAS BEEN ROLLED BACK BEFORE TO SEND THE REMOTE CREATES. SO THE OWNER NODE DELETED
// RECORD HAVING A HIGHER CLUSTER POSITION
while (rid.getClusterPosition() > physicalPosition.clusterPosition) {
assert atomicOperation.getCounter() == 1;
physicalPosition = cluster.allocatePosition(ORecordInternal.getRecordType(rec));
assert atomicOperation.getCounter() == 1;
}
if (rid.getClusterPosition() != physicalPosition.clusterPosition) {
throw new OConcurrentCreateException(rid, new ORecordId(rid.getClusterId(), physicalPosition.clusterPosition));
}
}
positions.put(recordOperation, physicalPosition);
rid.setClusterPosition(physicalPosition.clusterPosition);
transaction.updateIdentityAfterCommit(oldRID, rid);
}
}
lockRidBags(clustersToLock, indexOperations, indexManager);
checkReadOnlyConditions();
for (ORecordOperation recordOperation : recordOperations) {
assert atomicOperation.getCounter() == 1;
commitEntry(recordOperation, positions.get(recordOperation), database.getSerializer());
assert atomicOperation.getCounter() == 1;
result.add(recordOperation);
}
lockIndexes(indexOperations);
checkReadOnlyConditions();
commitIndexes(indexOperations, atomicOperation);
} catch (IOException | RuntimeException e) {
rollback = true;
if (e instanceof RuntimeException) {
throw ((RuntimeException) e);
} else {
throw OException.wrapException(new OStorageException("Error during transaction commit"), e);
}
} finally {
if (rollback) {
rollback(transaction);
} else {
endStorageTx(transaction, recordOperations);
}
this.transaction.set(null);
}
} finally {
atomicOperationsManager.ensureThatComponentsUnlocked();
database.getMetadata().clearThreadLocalSchemaSnapshot();
}
} finally {
try {
if (modificationLock) {
List<ORID> recordLocks = new ArrayList<>();
for (ORecordOperation recordOperation : recordOperations) {
if (recordOperation.type == ORecordOperation.UPDATED || recordOperation.type == ORecordOperation.DELETED) {
recordLocks.add(recordOperation.getRID());
}
}
Set<ORID> locked = transaction.getLockedRecords();
if (locked != null) {
recordLocks.removeAll(locked);
}
for (ORID rid : recordLocks) {
releaseWriteLock(rid);
}
}
} finally {
stateLock.releaseReadLock();
}
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance()
.debug(this, "%d Committed transaction %d on database '%s' (result=%s)", Thread.currentThread().getId(),
transaction.getId(), database.getName(), result);
}
return result;
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
handleJVMError(ee);
OAtomicOperationsManager.alarmClearOfAtomicOperation();
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private static void commitIndexes(final Map<String, OTransactionIndexChanges> indexesToCommit,
final OAtomicOperation atomicOperation) {
final Map<OIndex, OIndexAbstract.IndexTxSnapshot> snapshots = new IdentityHashMap<>();
for (OTransactionIndexChanges changes : indexesToCommit.values()) {
final OIndexInternal<?> index = changes.getAssociatedIndex();
final OIndexAbstract.IndexTxSnapshot snapshot = new OIndexAbstract.IndexTxSnapshot();
snapshots.put(index, snapshot);
assert atomicOperation.getCounter() == 1;
index.preCommit(snapshot);
assert atomicOperation.getCounter() == 1;
}
for (OTransactionIndexChanges changes : indexesToCommit.values()) {
final OIndexInternal<?> index = changes.getAssociatedIndex();
final OIndexAbstract.IndexTxSnapshot snapshot = snapshots.get(index);
assert atomicOperation.getCounter() == 1;
index.addTxOperation(snapshot, changes);
assert atomicOperation.getCounter() == 1;
}
try {
for (OTransactionIndexChanges changes : indexesToCommit.values()) {
final OIndexInternal<?> index = changes.getAssociatedIndex();
final OIndexAbstract.IndexTxSnapshot snapshot = snapshots.get(index);
assert atomicOperation.getCounter() == 1;
index.commit(snapshot);
assert atomicOperation.getCounter() == 1;
}
} finally {
for (OTransactionIndexChanges changes : indexesToCommit.values()) {
final OIndexInternal<?> index = changes.getAssociatedIndex();
final OIndexAbstract.IndexTxSnapshot snapshot = snapshots.get(index);
assert atomicOperation.getCounter() == 1;
index.postCommit(snapshot);
assert atomicOperation.getCounter() == 1;
}
}
}
private static TreeMap<String, OTransactionIndexChanges> getSortedIndexOperations(OTransactionInternal clientTx) {
return new TreeMap<>(clientTx.getIndexOperations());
}
public int loadIndexEngine(String name) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OIndexEngine engine = indexEngineNameMap.get(name);
if (engine == null) {
return -1;
}
final int indexId = indexEngines.indexOf(engine);
assert indexId >= 0;
return indexId;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public int loadExternalIndexEngine(String engineName, String algorithm, String indexType, OIndexDefinition indexDefinition,
OBinarySerializer valueSerializer, boolean isAutomatic, Boolean durableInNonTxMode, int version,
Map<String, String> engineProperties) {
try {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
// this method introduced for binary compatibility only
if (configuration.getBinaryFormatVersion() > 15) {
return -1;
}
if (indexEngineNameMap.containsKey(engineName)) {
throw new OIndexException("Index with name " + engineName + " already exists");
}
makeStorageDirty();
final OBinarySerializer keySerializer = determineKeySerializer(indexDefinition);
final int keySize = determineKeySize(indexDefinition);
final OType[] keyTypes = indexDefinition != null ? indexDefinition.getTypes() : null;
final boolean nullValuesSupport = indexDefinition != null && !indexDefinition.isNullValuesIgnored();
final OStorageConfigurationImpl.IndexEngineData engineData = new OStorageConfigurationImpl.IndexEngineData(engineName,
algorithm, indexType, durableInNonTxMode, version, valueSerializer.getId(), keySerializer.getId(), isAutomatic,
keyTypes, nullValuesSupport, keySize, null, null, engineProperties);
final OIndexEngine engine = OIndexes
.createIndexEngine(engineName, algorithm, indexType, durableInNonTxMode, this, version, engineProperties, null);
engine.load(engineName, valueSerializer, isAutomatic, keySerializer, keyTypes, nullValuesSupport, keySize,
engineData.getEngineProperties(), null);
indexEngineNameMap.put(engineName, engine);
indexEngines.add(engine);
((OStorageConfigurationImpl) configuration).addIndexEngine(engineName, engineData);
return indexEngines.size() - 1;
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot add index engine " + engineName + " in storage."), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public int addIndexEngine(String engineName, final String algorithm, final String indexType,
final OIndexDefinition indexDefinition, final OBinarySerializer valueSerializer, final boolean isAutomatic,
final Boolean durableInNonTxMode, final int version, final Map<String, String> engineProperties,
final Set<String> clustersToIndex, final ODocument metadata) {
try {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
if (indexEngineNameMap.containsKey(engineName)) {
// OLD INDEX FILE ARE PRESENT: THIS IS THE CASE OF PARTIAL/BROKEN INDEX
OLogManager.instance().warn(this, "Index with name '%s' already exists, removing it and re-create the index", engineName);
final OIndexEngine engine = indexEngineNameMap.remove(engineName);
if (engine != null) {
indexEngines.remove(engine);
((OStorageConfigurationImpl) configuration).deleteIndexEngine(engineName);
engine.delete();
}
}
makeStorageDirty();
final OBinarySerializer keySerializer = determineKeySerializer(indexDefinition);
final int keySize = determineKeySize(indexDefinition);
final OType[] keyTypes = indexDefinition != null ? indexDefinition.getTypes() : null;
final boolean nullValuesSupport = indexDefinition != null && !indexDefinition.isNullValuesIgnored();
final byte serializerId;
if (valueSerializer != null) {
serializerId = valueSerializer.getId();
} else {
serializerId = -1;
}
final OIndexEngine engine = OIndexes
.createIndexEngine(engineName, algorithm, indexType, durableInNonTxMode, this, version, engineProperties, metadata);
final OContextConfiguration ctxCfg = getConfiguration().getContextConfiguration();
final String cfgEncryption = ctxCfg.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD);
final String cfgEncryptionKey = ctxCfg.getValueAsString(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY);
final OEncryption encryption;
if (cfgEncryption == null || cfgEncryption.equals(ONothingEncryption.NAME)) {
encryption = null;
} else {
encryption = OEncryptionFactory.INSTANCE.getEncryption(cfgEncryption, cfgEncryptionKey);
}
engine.create(valueSerializer, isAutomatic, keyTypes, nullValuesSupport, keySerializer, keySize, clustersToIndex,
engineProperties, metadata, encryption);
if (writeAheadLog != null) {
writeAheadLog.flush();
}
indexEngineNameMap.put(engineName, engine);
indexEngines.add(engine);
final OStorageConfigurationImpl.IndexEngineData engineData = new OStorageConfigurationImpl.IndexEngineData(engineName,
algorithm, indexType, durableInNonTxMode, version, serializerId, keySerializer.getId(), isAutomatic, keyTypes,
nullValuesSupport, keySize, cfgEncryption, cfgEncryptionKey, engineProperties);
((OStorageConfigurationImpl) configuration).addIndexEngine(engineName, engineData);
return indexEngines.size() - 1;
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot add index engine " + engineName + " in storage."), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private static int determineKeySize(OIndexDefinition indexDefinition) {
if (indexDefinition == null || indexDefinition instanceof ORuntimeKeyIndexDefinition) {
return 1;
} else {
return indexDefinition.getTypes().length;
}
}
private OBinarySerializer determineKeySerializer(OIndexDefinition indexDefinition) {
final OBinarySerializer keySerializer;
if (indexDefinition != null) {
if (indexDefinition instanceof ORuntimeKeyIndexDefinition) {
keySerializer = ((ORuntimeKeyIndexDefinition) indexDefinition).getSerializer();
} else {
if (indexDefinition.getTypes().length > 1) {
keySerializer = OCompositeKeySerializer.INSTANCE;
} else {
final OType keyType = indexDefinition.getTypes()[0];
if (keyType == OType.STRING && configuration.getBinaryFormatVersion() >= 13) {
return OUTF8Serializer.INSTANCE;
}
OCurrentStorageComponentsFactory currentStorageComponentsFactory = componentsFactory;
if (currentStorageComponentsFactory != null) {
keySerializer = currentStorageComponentsFactory.binarySerializerFactory.getObjectSerializer(keyType);
} else {
throw new IllegalStateException("Cannot load binary serializer, storage is not properly initialized");
}
}
}
} else {
keySerializer = new OSimpleKeySerializer();
}
return keySerializer;
}
public void deleteIndexEngine(int indexId) throws OInvalidIndexEngineIdException {
try {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
checkIndexId(indexId);
makeStorageDirty();
final OIndexEngine engine = indexEngines.get(indexId);
indexEngines.set(indexId, null);
engine.delete();
final String engineName = engine.getName();
indexEngineNameMap.remove(engineName);
((OStorageConfigurationImpl) configuration).deleteIndexEngine(engineName);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error on index deletion"), e);
} finally {
stateLock.releaseWriteLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private void checkIndexId(int indexId) throws OInvalidIndexEngineIdException {
if (indexId < 0 || indexId >= indexEngines.size() || indexEngines.get(indexId) == null) {
throw new OInvalidIndexEngineIdException("Engine with id " + indexId + " is not registered inside of storage");
}
}
public boolean indexContainsKey(int indexId, Object key) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doIndexContainsKey(indexId, key);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doIndexContainsKey(indexId, key);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private boolean doIndexContainsKey(int indexId, Object key) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.contains(key);
}
public boolean removeKeyFromIndex(int indexId, Object key) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doRemoveKeyFromIndex(indexId, key);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
return doRemoveKeyFromIndex(indexId, key);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private boolean doRemoveKeyFromIndex(int indexId, Object key) throws OInvalidIndexEngineIdException {
try {
checkIndexId(indexId);
makeStorageDirty();
final OIndexEngine engine = indexEngines.get(indexId);
return engine.remove(key);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during removal of entry with key " + key + " from index "), e);
}
}
public void clearIndex(int indexId) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
doClearIndex(indexId);
return;
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
doClearIndex(indexId);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private void doClearIndex(int indexId) throws OInvalidIndexEngineIdException {
try {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
makeStorageDirty();
engine.clear();
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during clearing of index"), e);
}
}
public Object getIndexValue(int indexId, Object key) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexValue(indexId, key);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexValue(indexId, key);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private Object doGetIndexValue(int indexId, Object key) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.get(key);
}
public OIndexEngine getIndexEngine(int indexId) throws OInvalidIndexEngineIdException {
try {
checkIndexId(indexId);
return indexEngines.get(indexId);
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public void updateIndexEntry(int indexId, Object key, OIndexKeyUpdater<Object> valueCreator)
throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
doUpdateIndexEntry(indexId, key, valueCreator);
return;
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
doUpdateIndexEntry(indexId, key, valueCreator);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public <T> T callIndexEngine(boolean atomicOperation, boolean readOperation, int indexId, OIndexEngineCallback<T> callback)
throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doCallIndexEngine(atomicOperation, readOperation, indexId, callback);
}
checkOpenness();
stateLock.acquireReadLock();
try {
return doCallIndexEngine(atomicOperation, readOperation, indexId, callback);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private <T> T doCallIndexEngine(boolean atomicOperation, boolean readOperation, int indexId, OIndexEngineCallback<T> callback)
throws OInvalidIndexEngineIdException, IOException {
checkIndexId(indexId);
boolean rollback = false;
if (atomicOperation) {
atomicOperationsManager.startAtomicOperation((String) null, true);
}
try {
if (!readOperation) {
makeStorageDirty();
}
final OIndexEngine engine = indexEngines.get(indexId);
return callback.callEngine(engine);
} catch (Exception e) {
rollback = true;
throw OException.wrapException(new OStorageException("Cannot put key value entry in index"), e);
} finally {
if (atomicOperation) {
atomicOperationsManager.endAtomicOperation(rollback);
}
}
}
private void doUpdateIndexEntry(int indexId, Object key, OIndexKeyUpdater<Object> valueCreator)
throws OInvalidIndexEngineIdException, IOException {
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
makeStorageDirty();
engine.update(key, valueCreator);
} catch (Exception e) {
rollback = true;
throw e;
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
}
public void putIndexValue(int indexId, Object key, Object value) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
doPutIndexValue(indexId, key, value);
return;
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
doPutIndexValue(indexId, key, value);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private void doPutIndexValue(int indexId, Object key, Object value) throws OInvalidIndexEngineIdException {
try {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
makeStorageDirty();
engine.put(key, value);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot put key " + key + " value " + value + " entry to the index"), e);
}
}
/**
* Puts the given value under the given key into this storage for the index with the given index id. Validates the operation using
* the provided validator.
*
* @param indexId the index id of the index to put the value into.
* @param key the key to put the value under.
* @param value the value to put.
* @param validator the operation validator.
*
* @return {@code true} if the validator allowed the put, {@code false} otherwise.
*
* @see OIndexEngine.Validator#validate(Object, Object, Object)
*/
@SuppressWarnings("UnusedReturnValue")
public boolean validatedPutIndexValue(int indexId, Object key, OIdentifiable value,
OIndexEngine.Validator<Object, OIdentifiable> validator) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doValidatedPutIndexValue(indexId, key, value, validator);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
checkLowDiskSpaceRequestsAndReadOnlyConditions();
return doValidatedPutIndexValue(indexId, key, value, validator);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private boolean doValidatedPutIndexValue(int indexId, Object key, OIdentifiable value,
OIndexEngine.Validator<Object, OIdentifiable> validator) throws OInvalidIndexEngineIdException {
try {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
makeStorageDirty();
return engine.validatedPut(key, value, validator);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot put key " + key + " value " + value + " entry to the index"), e);
}
}
public Object getIndexFirstKey(int indexId) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexFirstKey(indexId);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexFirstKey(indexId);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private Object doGetIndexFirstKey(int indexId) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.getFirstKey();
}
public Object getIndexLastKey(int indexId) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexFirstKey(indexId);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexLastKey(indexId);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private Object doGetIndexLastKey(int indexId) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.getLastKey();
}
public OIndexCursor iterateIndexEntriesBetween(int indexId, Object rangeFrom, boolean fromInclusive, Object rangeTo,
boolean toInclusive, boolean ascSortOrder, OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doIterateIndexEntriesBetween(indexId, rangeFrom, fromInclusive, rangeTo, toInclusive, ascSortOrder, transformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doIterateIndexEntriesBetween(indexId, rangeFrom, fromInclusive, rangeTo, toInclusive, ascSortOrder, transformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexCursor doIterateIndexEntriesBetween(int indexId, Object rangeFrom, boolean fromInclusive, Object rangeTo,
boolean toInclusive, boolean ascSortOrder, OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.iterateEntriesBetween(rangeFrom, fromInclusive, rangeTo, toInclusive, ascSortOrder, transformer);
}
public OIndexCursor iterateIndexEntriesMajor(int indexId, Object fromKey, boolean isInclusive, boolean ascSortOrder,
OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doIterateIndexEntriesMajor(indexId, fromKey, isInclusive, ascSortOrder, transformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doIterateIndexEntriesMajor(indexId, fromKey, isInclusive, ascSortOrder, transformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexCursor doIterateIndexEntriesMajor(int indexId, Object fromKey, boolean isInclusive, boolean ascSortOrder,
OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.iterateEntriesMajor(fromKey, isInclusive, ascSortOrder, transformer);
}
public OIndexCursor iterateIndexEntriesMinor(int indexId, final Object toKey, final boolean isInclusive, boolean ascSortOrder,
OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doIterateIndexEntriesMinor(indexId, toKey, isInclusive, ascSortOrder, transformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doIterateIndexEntriesMinor(indexId, toKey, isInclusive, ascSortOrder, transformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexCursor doIterateIndexEntriesMinor(int indexId, Object toKey, boolean isInclusive, boolean ascSortOrder,
OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.iterateEntriesMinor(toKey, isInclusive, ascSortOrder, transformer);
}
public OIndexCursor getIndexCursor(int indexId, OIndexEngine.ValuesTransformer valuesTransformer)
throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexCursor(indexId, valuesTransformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexCursor(indexId, valuesTransformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexCursor doGetIndexCursor(int indexId, OIndexEngine.ValuesTransformer valuesTransformer)
throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.cursor(valuesTransformer);
}
public OIndexCursor getIndexDescCursor(int indexId, OIndexEngine.ValuesTransformer valuesTransformer)
throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexDescCursor(indexId, valuesTransformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexDescCursor(indexId, valuesTransformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexCursor doGetIndexDescCursor(int indexId, OIndexEngine.ValuesTransformer valuesTransformer)
throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.descCursor(valuesTransformer);
}
public OIndexKeyCursor getIndexKeyCursor(int indexId) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexKeyCursor(indexId);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexKeyCursor(indexId);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private OIndexKeyCursor doGetIndexKeyCursor(int indexId) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.keyCursor();
}
public long getIndexSize(int indexId, OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doGetIndexSize(indexId, transformer);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doGetIndexSize(indexId, transformer);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private long doGetIndexSize(int indexId, OIndexEngine.ValuesTransformer transformer) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.size(transformer);
}
public boolean hasIndexRangeQuerySupport(int indexId) throws OInvalidIndexEngineIdException {
try {
if (transaction.get() != null) {
return doHasRangeQuerySupport(indexId);
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return doHasRangeQuerySupport(indexId);
} finally {
stateLock.releaseReadLock();
}
} catch (OInvalidIndexEngineIdException ie) {
throw logAndPrepareForRethrow(ie);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
private boolean doHasRangeQuerySupport(int indexId) throws OInvalidIndexEngineIdException {
checkIndexId(indexId);
final OIndexEngine engine = indexEngines.get(indexId);
return engine.hasRangeQuerySupport();
}
@Override
public void rollback(final OTransactionInternal clientTx) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
try {
checkOpenness();
assert transaction.get() != null;
if (transaction.get().getClientTx().getId() != clientTx.getId()) {
throw new OStorageException(
"Passed in and active transaction are different transactions. Passed in transaction cannot be rolled back.");
}
makeStorageDirty();
rollbackStorageTx();
OTransactionAbstract.updateCacheFromEntries(clientTx.getDatabase(), clientTx.getRecordOperations(), false);
txRollback.incrementAndGet();
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during transaction rollback"), e);
} finally {
transaction.set(null);
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Rollbacks the given micro-transaction.
*
* @param microTransaction the micro-transaction to rollback.
*/
public void rollback(OMicroTransaction microTransaction) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
try {
checkOpenness();
if (transaction.get() == null) {
return;
}
if (transaction.get().getMicroTransaction().getId() != microTransaction.getId()) {
throw new OStorageException(
"Passed in and active micro-transaction are different micro-transactions. Passed in micro-transaction cannot be "
+ "rolled back.");
}
makeStorageDirty();
rollbackStorageTx();
microTransaction.updateRecordCacheAfterRollback();
txRollback.incrementAndGet();
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during micro-transaction rollback"), e);
} finally {
transaction.set(null);
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final boolean checkForRecordValidity(final OPhysicalPosition ppos) {
try {
return ppos != null && !ORecordVersionHelper.isTombstone(ppos.recordVersion);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final void synch() {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
final long timer = Orient.instance().getProfiler().startChrono();
final long lockId = atomicOperationsManager.freezeAtomicOperations(null, null);
try {
checkOpenness();
if (jvmError.get() == null) {
for (OIndexEngine indexEngine : indexEngines) {
try {
if (indexEngine != null) {
indexEngine.flush();
}
} catch (Throwable t) {
OLogManager.instance().error(this, "Error while flushing index via index engine of class %s.", t,
indexEngine.getClass().getSimpleName());
}
}
if (writeAheadLog != null) {
makeFullCheckpoint();
return;
}
writeCache.flush();
clearStorageDirty();
} else {
OLogManager.instance().errorNoDb(this, "Sync can not be performed because of JVM error on storage", null);
}
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error on synch storage '" + name + "'"), e);
} finally {
atomicOperationsManager.releaseAtomicOperations(lockId);
//noinspection ResultOfMethodCallIgnored
Orient.instance().getProfiler().stopChrono("db." + name + ".synch", "Synch a database", timer, "db.*.synch");
}
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final String getPhysicalClusterNameById(final int iClusterId) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
if (iClusterId < 0 || iClusterId >= clusters.size()) {
return null;
}
return clusters.get(iClusterId) != null ? clusters.get(iClusterId).getName() : null;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int getDefaultClusterId() {
return defaultClusterId;
}
@Override
public final void setDefaultClusterId(final int defaultClusterId) {
this.defaultClusterId = defaultClusterId;
}
@Override
public final OCluster getClusterById(int iClusterId) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
if (iClusterId == ORID.CLUSTER_ID_INVALID)
// GET THE DEFAULT CLUSTER
{
iClusterId = defaultClusterId;
}
final OCluster cluster = doGetAndCheckCluster(iClusterId);
return cluster;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OCluster getClusterByName(final String clusterName) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = clusterMap.get(clusterName.toLowerCase(configuration.getLocaleInstance()));
if (cluster == null) {
throw new OStorageException("Cluster " + clusterName + " does not exist in database '" + name + "'");
}
return cluster;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final long getSize() {
try {
try {
long size = 0;
stateLock.acquireReadLock();
try {
for (OCluster c : clusters) {
if (c != null) {
size += c.getRecordsSize();
}
}
} finally {
stateLock.releaseReadLock();
}
return size;
} catch (IOException ioe) {
throw OException.wrapException(new OStorageException("Cannot calculate records size"), ioe);
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final int getClusters() {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
return clusterMap.size();
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final Set<OCluster> getClusterInstances() {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final Set<OCluster> result = new HashSet<>();
// ADD ALL THE CLUSTERS
for (OCluster c : clusters) {
if (c != null) {
result.add(c);
}
}
return result;
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Method that completes the cluster rename operation. <strong>IT WILL NOT RENAME A CLUSTER, IT JUST CHANGES THE NAME IN THE
* INTERNAL MAPPING</strong>
*/
public void renameCluster(final String oldName, final String newName) {
try {
clusterMap.put(newName.toLowerCase(configuration.getLocaleInstance()),
clusterMap.remove(oldName.toLowerCase(configuration.getLocaleInstance())));
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final boolean cleanOutRecord(final ORecordId recordId, final int recordVersion, final int iMode,
final ORecordCallback<Boolean> callback) {
return deleteRecord(recordId, recordVersion, iMode, callback).getResult();
}
@Override
public final boolean isFrozen() {
try {
return atomicOperationsManager.isFrozen();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final void freeze(final boolean throwException) {
try {
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
if (throwException) {
atomicOperationsManager
.freezeAtomicOperations(OModificationOperationProhibitedException.class, "Modification requests are prohibited");
} else {
atomicOperationsManager.freezeAtomicOperations(null, null);
}
final List<OFreezableStorageComponent> frozenIndexes = new ArrayList<>(indexEngines.size());
try {
for (OIndexEngine indexEngine : indexEngines) {
if (indexEngine instanceof OFreezableStorageComponent) {
((OFreezableStorageComponent) indexEngine).freeze(false);
frozenIndexes.add((OFreezableStorageComponent) indexEngine);
}
}
} catch (Exception e) {
// RELEASE ALL THE FROZEN INDEXES
for (OFreezableStorageComponent indexEngine : frozenIndexes) {
indexEngine.release();
}
throw OException.wrapException(new OStorageException("Error on freeze of storage '" + name + "'"), e);
}
synch();
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final void release() {
try {
for (OIndexEngine indexEngine : indexEngines) {
if (indexEngine instanceof OFreezableStorageComponent) {
((OFreezableStorageComponent) indexEngine).release();
}
}
atomicOperationsManager.releaseAtomicOperations(-1);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final boolean isRemote() {
return false;
}
public boolean wereDataRestoredAfterOpen() {
return wereDataRestoredAfterOpen;
}
public boolean wereNonTxOperationsPerformedInPreviousOpen() {
return wereNonTxOperationsPerformedInPreviousOpen;
}
@Override
public final void reload() {
try {
close();
open(null, null, null);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@SuppressWarnings("unused")
public String getMode() {
return mode;
}
@Override
public final void lowDiskSpace(OLowDiskSpaceInformation information) {
lowDiskSpace = information;
}
/**
* @inheritDoc
*/
@Override
public final void pageIsBroken(String fileName, long pageIndex) {
brokenPages.add(new OPair<>(fileName, pageIndex));
}
@Override
public final void requestCheckpoint() {
try {
if (!walVacuumInProgress.get() && walVacuumInProgress.compareAndSet(false, true)) {
fuzzyCheckpointExecutor.submit(new WALVacuum());
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
/**
* Executes the command request and return the result back.
*/
@Override
public final Object command(final OCommandRequestText iCommand) {
try {
while (true) {
try {
final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand);
// COPY THE CONTEXT FROM THE REQUEST
executor.setContext(iCommand.getContext());
executor.setProgressListener(iCommand.getProgressListener());
executor.parse(iCommand);
return executeCommand(iCommand, executor);
} catch (ORetryQueryException ignore) {
if (iCommand instanceof OQueryAbstract) {
final OQueryAbstract query = (OQueryAbstract) iCommand;
query.reset();
}
}
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee, false);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@SuppressWarnings("WeakerAccess")
public final Object executeCommand(final OCommandRequestText iCommand, final OCommandExecutor executor) {
try {
if (iCommand.isIdempotent() && !executor.isIdempotent()) {
throw new OCommandExecutionException("Cannot execute non idempotent command");
}
long beginTime = Orient.instance().getProfiler().startChrono();
try {
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().get();
// CALL BEFORE COMMAND
Iterable<ODatabaseListener> listeners = db.getListeners();
for (ODatabaseListener oDatabaseListener : listeners) {
oDatabaseListener.onBeforeCommand(iCommand, executor);
}
boolean foundInCache = false;
Object result = null;
if (iCommand.isCacheableResult() && executor.isCacheable() && iCommand.getParameters() == null) {
// TRY WITH COMMAND CACHE
result = db.getMetadata().getCommandCache().get(db.getUser(), iCommand.getText(), iCommand.getLimit());
if (result != null) {
foundInCache = true;
if (iCommand.getResultListener() != null) {
// INVOKE THE LISTENER IF ANY
if (result instanceof Collection) {
for (Object o : (Collection) result) {
iCommand.getResultListener().result(o);
}
} else {
iCommand.getResultListener().result(result);
}
// RESET THE RESULT TO AVOID TO SEND IT TWICE
result = null;
}
}
}
if (!foundInCache) {
// EXECUTE THE COMMAND
Map<Object, Object> params = iCommand.getParameters();
result = executor.execute(params);
if (result != null && iCommand.isCacheableResult() && executor.isCacheable() && (iCommand.getParameters() == null
|| iCommand.getParameters().isEmpty()))
// CACHE THE COMMAND RESULT
{
db.getMetadata().getCommandCache()
.put(db.getUser(), iCommand.getText(), result, iCommand.getLimit(), executor.getInvolvedClusters(),
System.currentTimeMillis() - beginTime);
}
}
// CALL AFTER COMMAND
for (ODatabaseListener oDatabaseListener : listeners) {
oDatabaseListener.onAfterCommand(iCommand, executor, result);
}
return result;
} catch (OException e) {
// PASS THROUGH
throw e;
} catch (Exception e) {
throw OException.wrapException(new OCommandExecutionException("Error on execution of command: " + iCommand), e);
} finally {
if (Orient.instance().getProfiler().isRecording()) {
final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db != null) {
final OSecurityUser user = db.getUser();
final String userString = user != null ? user.toString() : null;
//noinspection ResultOfMethodCallIgnored
Orient.instance().getProfiler()
.stopChrono("db." + ODatabaseRecordThreadLocal.instance().get().getName() + ".command." + iCommand.toString(),
"Command executed against the database", beginTime, "db.*.command.*", null, userString);
}
}
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee, false);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OPhysicalPosition[] higherPhysicalPositions(int currentClusterId, OPhysicalPosition physicalPosition) {
try {
if (currentClusterId == -1) {
return new OPhysicalPosition[0];
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = getClusterById(currentClusterId);
return cluster.higherPositions(physicalPosition);
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Cluster Id " + currentClusterId + " is invalid in storage '" + name + '\''), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OPhysicalPosition[] ceilingPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) {
try {
if (clusterId == -1) {
return new OPhysicalPosition[0];
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = getClusterById(clusterId);
return cluster.ceilingPositions(physicalPosition);
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Cluster Id " + clusterId + " is invalid in storage '" + name + '\''), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OPhysicalPosition[] lowerPhysicalPositions(int currentClusterId, OPhysicalPosition physicalPosition) {
try {
if (currentClusterId == -1) {
return new OPhysicalPosition[0];
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = getClusterById(currentClusterId);
return cluster.lowerPositions(physicalPosition);
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Cluster Id " + currentClusterId + " is invalid in storage '" + name + '\''), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final OPhysicalPosition[] floorPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) {
try {
if (clusterId == -1) {
return new OPhysicalPosition[0];
}
checkOpenness();
stateLock.acquireReadLock();
try {
checkOpenness();
final OCluster cluster = getClusterById(clusterId);
return cluster.floorPositions(physicalPosition);
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Cluster Id " + clusterId + " is invalid in storage '" + name + '\''), ioe);
} finally {
stateLock.releaseReadLock();
}
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public void acquireWriteLock(final ORID rid, long timeout) {
if (!modificationLock) {
throw new ODatabaseException(
"Record write locks are off by configuration, set the configuration \"storage.pessimisticLock\" to \""
+ OrientDBConfig.LOCK_TYPE_READWRITE + "\" for enable them");
}
try {
lockManager.acquireWriteLock(rid, timeout);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final void acquireWriteLock(final ORID rid) {
if (!modificationLock) {
throw new ODatabaseException(
"Record write locks are off by configuration, set the configuration \"storage.pessimisticLock\" to \""
+ OrientDBConfig.LOCK_TYPE_MODIFICATION + "\" for enable them");
}
try {
lockManager.acquireWriteLock(rid, 0);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final void releaseWriteLock(final ORID rid) {
try {
lockManager.releaseWriteLock(rid);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final void acquireReadLock(final ORID rid) {
if (!readLock) {
throw new ODatabaseException(
"Record read locks are off by configuration, set the configuration \"storage.pessimisticLock\" to \""
+ OrientDBConfig.LOCK_TYPE_READWRITE + "\" for enable them");
}
try {
lockManager.acquireReadLock(rid, 0);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public void acquireReadLock(final ORID rid, long timeout) {
if (!readLock) {
throw new ODatabaseException(
"Record read locks are off by configuration, set the configuration \"storage.pessimisticLock\" to \""
+ OrientDBConfig.LOCK_TYPE_READWRITE + "\" for enable them");
}
try {
lockManager.acquireReadLock(rid, timeout);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
public final void releaseReadLock(final ORID rid) {
try {
lockManager.releaseReadLock(rid);
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
}
}
@Override
public final ORecordConflictStrategy getConflictStrategy() {
return recordConflictStrategy;
}
@Override
public final void setConflictStrategy(final ORecordConflictStrategy conflictResolver) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
this.recordConflictStrategy = conflictResolver;
((OStorageConfigurationImpl) configuration).setConflictStrategy(conflictResolver.getName());
} finally {
stateLock.releaseWriteLock();
}
}
@SuppressWarnings("unused")
public AtomicLong getRecordScanned() {
return recordScanned;
}
@SuppressWarnings("unused")
protected abstract OLogSequenceNumber copyWALToIncrementalBackup(ZipOutputStream zipOutputStream, long startSegment)
throws IOException;
@SuppressWarnings("unused")
protected abstract boolean isWriteAllowedDuringIncrementalBackup();
@SuppressWarnings("unused")
public OStorageRecoverListener getRecoverListener() {
return recoverListener;
}
public void registerRecoverListener(final OStorageRecoverListener recoverListener) {
this.recoverListener = recoverListener;
}
@SuppressWarnings("unused")
public void unregisterRecoverListener(final OStorageRecoverListener recoverListener) {
if (this.recoverListener == recoverListener) {
this.recoverListener = null;
}
}
@SuppressWarnings("unused")
protected abstract File createWalTempDirectory();
@SuppressWarnings("unused")
protected abstract void addFileToDirectory(String name, InputStream stream, File directory) throws IOException;
@SuppressWarnings("unused")
protected abstract OWriteAheadLog createWalFromIBUFiles(File directory) throws IOException;
/**
* Checks if the storage is open. If it's closed an exception is raised.
*/
@SuppressWarnings("WeakerAccess")
protected final void checkOpenness() {
if (status != STATUS.OPEN) {
throw new OStorageException("Storage " + name + " is not opened.");
}
}
protected void makeFuzzyCheckpoint() {
if (writeAheadLog == null) {
return;
}
//check every 1 ms.
while (!stateLock.tryAcquireReadLock(1_000_000)) {
if (status != STATUS.OPEN) {
return;
}
}
try {
if (status != STATUS.OPEN || writeAheadLog == null) {
return;
}
OLogSequenceNumber beginLSN = writeAheadLog.begin();
OLogSequenceNumber endLSN = writeAheadLog.end();
final Long minLSNSegment = writeCache.getMinimalNotFlushedSegment();
final long fuzzySegment;
if (minLSNSegment != null) {
fuzzySegment = minLSNSegment;
} else {
if (endLSN == null) {
return;
}
fuzzySegment = endLSN.getSegment();
}
OLogManager.instance().infoNoDb(this,
"Before fuzzy checkpoint: min LSN segment is " + minLSNSegment + ", WAL begin is " + beginLSN + ", WAL end is " + endLSN
+ ", fuzzy segment is " + fuzzySegment);
if (fuzzySegment > beginLSN.getSegment() && beginLSN.getSegment() < endLSN.getSegment()) {
OLogManager.instance().infoNoDb(this, "Making fuzzy checkpoint");
writeCache.makeFuzzyCheckpoint(fuzzySegment);
beginLSN = writeAheadLog.begin();
endLSN = writeAheadLog.end();
OLogManager.instance().infoNoDb(this, "After fuzzy checkpoint: WAL begin is " + beginLSN + " WAL end is " + endLSN);
} else {
OLogManager.instance().infoNoDb(this, "No reason to make fuzzy checkpoint");
}
} catch (IOException ioe) {
throw OException.wrapException(new OIOException("Error during fuzzy checkpoint"), ioe);
} finally {
stateLock.releaseReadLock();
}
}
protected void makeFullCheckpoint() {
final OSessionStoragePerformanceStatistic statistic = performanceStatisticManager.getSessionPerformanceStatistic();
if (statistic != null) {
statistic.startFullCheckpointTimer();
}
try {
if (writeAheadLog == null) {
return;
}
try {
writeAheadLog.flush();
//so we will be able to cut almost all the log
writeAheadLog.appendNewSegment();
final OLogSequenceNumber lastLSN = writeAheadLog.logFullCheckpointStart();
writeCache.flush();
writeAheadLog.logFullCheckpointEnd();
writeAheadLog.flush();
writeAheadLog.cutTill(lastLSN);
if (jvmError.get() == null) {
clearStorageDirty();
}
} catch (IOException ioe) {
throw OException.wrapException(new OStorageException("Error during checkpoint creation for storage " + name), ioe);
}
fullCheckpointCount.increment();
} finally {
if (statistic != null) {
statistic.stopFullCheckpointTimer();
}
}
}
public long getFullCheckpointCount() {
return fullCheckpointCount.sum();
}
protected void preOpenSteps() throws IOException {
}
@SuppressWarnings({ "WeakerAccess", "EmptyMethod" })
protected final void postCreateSteps() {
}
protected void preCreateSteps() throws IOException {
}
protected abstract void initWalAndDiskCache(OContextConfiguration contextConfiguration) throws IOException, InterruptedException;
protected abstract void postCloseSteps(@SuppressWarnings("unused") boolean onDelete, boolean jvmError) throws IOException;
@SuppressWarnings("EmptyMethod")
protected void postCloseStepsAfterLock(Map<String, Object> params) {
}
@SuppressWarnings({ "EmptyMethod", "WeakerAccess" })
protected Map<String, Object> preCloseSteps() {
return new HashMap<>();
}
protected void postDeleteSteps() {
}
protected void makeStorageDirty() throws IOException {
}
protected void clearStorageDirty() throws IOException {
}
protected boolean isDirty() {
return false;
}
private ORawBuffer readRecordIfNotLatest(final OCluster cluster, final ORecordId rid, final int recordVersion)
throws ORecordNotFoundException {
checkOpenness();
if (!rid.isPersistent()) {
throw new ORecordNotFoundException(rid,
"Cannot read record " + rid + " since the position is invalid in database '" + name + '\'');
}
if (transaction.get() != null) {
return doReadRecordIfNotLatest(cluster, rid, recordVersion);
}
stateLock.acquireReadLock();
try {
if (readLock) {
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db == null || !((OTransactionAbstract) db.getTransaction()).getLockedRecords().contains(rid)) {
acquireReadLock(rid);
}
}
ORawBuffer buff;
checkOpenness();
buff = doReadRecordIfNotLatest(cluster, rid, recordVersion);
return buff;
} finally {
try {
if (readLock) {
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db == null || !((OTransactionAbstract) db.getTransaction()).getLockedRecords().contains(rid)) {
releaseReadLock(rid);
}
}
} finally {
stateLock.releaseReadLock();
}
}
}
private ORawBuffer readRecord(final OCluster clusterSegment, final ORecordId rid, boolean prefetchRecords) {
checkOpenness();
if (!rid.isPersistent()) {
throw new ORecordNotFoundException(rid,
"Cannot read record " + rid + " since the position is invalid in database '" + name + '\'');
}
if (transaction.get() != null) {
// Disabled this assert have no meaning anymore
// assert iLockingStrategy.equals(LOCKING_STRATEGY.DEFAULT);
return doReadRecord(clusterSegment, rid, prefetchRecords);
}
stateLock.acquireReadLock();
try {
if (readLock) {
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db == null || !((OTransactionAbstract) db.getTransaction()).getLockedRecords().contains(rid)) {
acquireReadLock(rid);
}
}
checkOpenness();
return doReadRecord(clusterSegment, rid, prefetchRecords);
} finally {
try {
if (readLock) {
ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined();
if (db == null || !((OTransactionAbstract) db.getTransaction()).getLockedRecords().contains(rid)) {
releaseReadLock(rid);
}
}
} finally {
stateLock.releaseReadLock();
}
}
}
private void endStorageTx(final OTransactionInternal txi, final Collection<ORecordOperation> recordOperations)
throws IOException {
atomicOperationsManager.endAtomicOperation(false);
assert OAtomicOperationsManager.getCurrentOperation() == null;
OTransactionAbstract.updateCacheFromEntries(txi.getDatabase(), recordOperations, true);
txCommit.incrementAndGet();
}
private void startStorageTx(OTransactionInternal clientTx) throws IOException {
final OStorageTransaction storageTx = transaction.get();
assert storageTx == null || storageTx.getClientTx().getId() == clientTx.getId();
assert OAtomicOperationsManager.getCurrentOperation() == null;
transaction.set(new OStorageTransaction(clientTx));
try {
atomicOperationsManager.startAtomicOperation((String) null, true);
} catch (RuntimeException e) {
transaction.set(null);
throw e;
}
}
private void rollbackStorageTx() throws IOException {
assert transaction.get() != null;
atomicOperationsManager.endAtomicOperation(true);
assert OAtomicOperationsManager.getCurrentOperation() == null;
}
private void recoverIfNeeded() throws Exception {
if (isDirty()) {
OLogManager.instance().warn(this, "Storage '" + name + "' was not closed properly. Will try to recover from write ahead log");
try {
wereDataRestoredAfterOpen = restoreFromWAL() != null;
if (recoverListener != null) {
recoverListener.onStorageRecover();
}
makeFullCheckpoint();
} catch (Exception e) {
OLogManager.instance().error(this, "Exception during storage data restore", e);
throw e;
}
OLogManager.instance().info(this, "Storage data recover was completed");
}
}
private OStorageOperationResult<OPhysicalPosition> doCreateRecord(final ORecordId rid, final byte[] content, int recordVersion,
final byte recordType, final ORecordCallback<Long> callback, final OCluster cluster, final OPhysicalPosition allocated) {
if (content == null) {
throw new IllegalArgumentException("Record is null");
}
try {
if (recordVersion > -1) {
recordVersion++;
} else {
recordVersion = 0;
}
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
OPhysicalPosition ppos;
try {
ppos = cluster.createRecord(content, recordVersion, recordType, allocated);
rid.setClusterPosition(ppos.clusterPosition);
final ORecordSerializationContext context = ORecordSerializationContext.getContext();
if (context != null) {
context.executeOperations(this);
}
} catch (Exception e) {
rollback = true;
OLogManager.instance().error(this, "Error on creating record in cluster: " + cluster, e);
throw ODatabaseException.wrapException(new OStorageException("Error during creation of record"), e);
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
if (callback != null) {
callback.call(rid, ppos.clusterPosition);
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance().debug(this, "Created record %s v.%s size=%d bytes", rid, recordVersion, content.length);
}
recordCreated.incrementAndGet();
return new OStorageOperationResult<>(ppos);
} catch (IOException ioe) {
throw OException.wrapException(
new OStorageException("Error during record deletion in cluster " + (cluster != null ? cluster.getName() : "")), ioe);
}
}
private OStorageOperationResult<Integer> doUpdateRecord(final ORecordId rid, final boolean updateContent, byte[] content,
final int version, final byte recordType, final ORecordCallback<Integer> callback, final OCluster cluster) {
Orient.instance().getProfiler().startChrono();
try {
final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition()));
if (!checkForRecordValidity(ppos)) {
final int recordVersion = -1;
if (callback != null) {
callback.call(rid, recordVersion);
}
return new OStorageOperationResult<>(recordVersion);
}
boolean contentModified = false;
if (updateContent) {
final AtomicInteger recVersion = new AtomicInteger(version);
final AtomicInteger dbVersion = new AtomicInteger(ppos.recordVersion);
final byte[] newContent = checkAndIncrementVersion(cluster, rid, recVersion, dbVersion, content, recordType);
ppos.recordVersion = dbVersion.get();
// REMOVED BECAUSE DISTRIBUTED COULD UNDO AN OPERATION RESTORING A LOWER VERSION
// assert ppos.recordVersion >= oldVersion;
if (newContent != null) {
contentModified = true;
content = newContent;
}
}
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
if (updateContent) {
cluster.updateRecord(rid.getClusterPosition(), content, ppos.recordVersion, recordType);
}
final ORecordSerializationContext context = ORecordSerializationContext.getContext();
if (context != null) {
context.executeOperations(this);
}
} catch (Exception e) {
rollback = true;
OLogManager.instance().error(this, "Error on updating record " + rid + " (cluster: " + cluster + ")", e);
throw OException
.wrapException(new OStorageException("Error on updating record " + rid + " (cluster: " + cluster.getName() + ")"), e);
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
//if we do not update content of the record we should keep version of the record the same
//otherwise we would have issues when two records may have the same version but different content
int newRecordVersion;
if (updateContent) {
newRecordVersion = ppos.recordVersion;
} else {
newRecordVersion = version;
}
if (callback != null) {
callback.call(rid, newRecordVersion);
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance().debug(this, "Updated record %s v.%s size=%d", rid, newRecordVersion, content.length);
}
recordUpdated.incrementAndGet();
if (contentModified) {
return new OStorageOperationResult<>(newRecordVersion, content, false);
} else {
return new OStorageOperationResult<>(newRecordVersion);
}
} catch (OConcurrentModificationException e) {
recordConflict.incrementAndGet();
throw e;
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Error on updating record " + rid + " (cluster: " + cluster.getName() + ")"), ioe);
}
}
private OStorageOperationResult<Integer> doRecycleRecord(final ORecordId rid, byte[] content, final int version,
final OCluster cluster, final byte recordType) {
try {
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
cluster.recycleRecord(rid.getClusterPosition(), content, version, recordType);
final ORecordSerializationContext context = ORecordSerializationContext.getContext();
if (context != null) {
context.executeOperations(this);
}
} catch (Exception e) {
rollback = true;
throw e;
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance().debug(this, "Recycled record %s v.%s size=%d", rid, version, content.length);
}
return new OStorageOperationResult<>(version, content, false);
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error on recycling record " + rid + " (cluster: " + cluster + ")", ioe);
throw OException
.wrapException(new OStorageException("Error on recycling record " + rid + " (cluster: " + cluster + ")"), ioe);
}
}
private OStorageOperationResult<Boolean> doDeleteRecord(ORecordId rid, final int version, OCluster cluster) {
Orient.instance().getProfiler().startChrono();
try {
final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition()));
if (ppos == null) {
// ALREADY DELETED
return new OStorageOperationResult<>(false);
}
// MVCC TRANSACTION: CHECK IF VERSION IS THE SAME
if (version > -1 && ppos.recordVersion != version) {
recordConflict.incrementAndGet();
if (OFastConcurrentModificationException.enabled()) {
throw OFastConcurrentModificationException.instance();
} else {
throw new OConcurrentModificationException(rid, ppos.recordVersion, version, ORecordOperation.DELETED);
}
}
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
cluster.deleteRecord(ppos.clusterPosition);
final ORecordSerializationContext context = ORecordSerializationContext.getContext();
if (context != null) {
context.executeOperations(this);
}
} catch (Exception e) {
rollback = true;
throw e;
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance().debug(this, "Deleted record %s v.%s", rid, version);
}
recordDeleted.incrementAndGet();
return new OStorageOperationResult<>(true);
} catch (IOException ioe) {
throw OException
.wrapException(new OStorageException("Error on deleting record " + rid + "( cluster: " + cluster.getName() + ")"), ioe);
}
}
private OStorageOperationResult<Boolean> doHideMethod(ORecordId rid, OCluster cluster) {
try {
final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition()));
if (ppos == null) {
// ALREADY HIDDEN
return new OStorageOperationResult<>(false);
}
makeStorageDirty();
boolean rollback = false;
atomicOperationsManager.startAtomicOperation((String) null, true);
try {
cluster.hideRecord(ppos.clusterPosition);
final ORecordSerializationContext context = ORecordSerializationContext.getContext();
if (context != null) {
context.executeOperations(this);
}
} catch (Exception e) {
rollback = true;
throw e;
} finally {
atomicOperationsManager.endAtomicOperation(rollback);
}
return new OStorageOperationResult<>(true);
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error on deleting record " + rid + "( cluster: " + cluster + ")", ioe);
throw OException.wrapException(new OStorageException("Error on deleting record " + rid + "( cluster: " + cluster + ")"), ioe);
}
}
private ORawBuffer doReadRecord(final OCluster clusterSegment, final ORecordId rid, boolean prefetchRecords) {
try {
final ORawBuffer buff = clusterSegment.readRecord(rid.getClusterPosition(), prefetchRecords);
if (buff != null && OLogManager.instance().isDebugEnabled()) {
OLogManager.instance()
.debug(this, "Read record %s v.%s size=%d bytes", rid, buff.version, buff.buffer != null ? buff.buffer.length : 0);
}
recordRead.incrementAndGet();
return buff;
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during read of record with rid = " + rid), e);
}
}
private static ORawBuffer doReadRecordIfNotLatest(final OCluster cluster, final ORecordId rid, final int recordVersion)
throws ORecordNotFoundException {
try {
return cluster.readRecordIfVersionIsNotLatest(rid.getClusterPosition(), recordVersion);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during read of record with rid = " + rid), e);
}
}
private int createClusterFromConfig(final OStorageClusterConfiguration config) throws IOException {
OCluster cluster = clusterMap.get(config.getName().toLowerCase(configuration.getLocaleInstance()));
if (cluster != null) {
cluster.configure(this, config);
return -1;
}
if (config.getStatus() == OStorageClusterConfiguration.STATUS.ONLINE) {
cluster = OPaginatedClusterFactory
.createCluster(config.getName(), configuration.getVersion(), config.getBinaryVersion(), this);
} else {
cluster = new OOfflineCluster(this, config.getId(), config.getName());
}
cluster.configure(this, config);
return registerCluster(cluster);
}
private void setCluster(int id, OCluster cluster) {
if (clusters.size() <= id) {
while (clusters.size() < id) {
clusters.add(null);
}
clusters.add(cluster);
} else {
clusters.set(id, cluster);
}
}
/**
* Register the cluster internally.
*
* @param cluster OCluster implementation
*
* @return The id (physical position into the array) of the new cluster just created. First is 0.
*/
private int registerCluster(final OCluster cluster) {
final int id;
if (cluster != null) {
// CHECK FOR DUPLICATION OF NAMES
if (clusterMap.containsKey(cluster.getName().toLowerCase(configuration.getLocaleInstance()))) {
throw new OConfigurationException(
"Cannot add cluster '" + cluster.getName() + "' because it is already registered in database '" + name + "'");
}
// CREATE AND ADD THE NEW REF SEGMENT
clusterMap.put(cluster.getName().toLowerCase(configuration.getLocaleInstance()), cluster);
id = cluster.getId();
} else {
id = clusters.size();
}
setCluster(id, cluster);
return id;
}
private int doAddCluster(String clusterName, Object[] parameters) throws IOException {
// FIND THE FIRST AVAILABLE CLUSTER ID
int clusterPos = clusters.size();
for (int i = 0; i < clusters.size(); ++i) {
if (clusters.get(i) == null) {
clusterPos = i;
break;
}
}
return addClusterInternal(clusterName, clusterPos, parameters);
}
private int addClusterInternal(String clusterName, int clusterPos, Object... parameters) throws IOException {
final OCluster cluster;
if (clusterName != null) {
clusterName = clusterName.toLowerCase(configuration.getLocaleInstance());
cluster = OPaginatedClusterFactory
.createCluster(clusterName, configuration.getVersion(), OPaginatedCluster.getLatestBinaryVersion(), this);
cluster.configure(this, clusterPos, clusterName, parameters);
} else {
cluster = null;
}
int createdClusterId = -1;
if (cluster != null) {
if (!cluster.exists()) {
cluster.create(-1);
} else {
cluster.open();
}
if (writeAheadLog != null) {
writeAheadLog.flush();
}
createdClusterId = registerCluster(cluster);
((OPaginatedCluster) cluster).registerInStorageConfig((OStorageConfigurationImpl) configuration);
((OStorageConfigurationImpl) configuration).update();
}
if (OLogManager.instance().isDebugEnabled()) {
OLogManager.instance()
.debug(this, "Created cluster '%s' in database '%s' with id %d. Clusters: %s", clusterName, url, createdClusterId,
clusters);
}
return createdClusterId;
}
private void doClose(boolean force, boolean onDelete) {
if (!force && !onDelete) {
return;
}
if (status == STATUS.CLOSED) {
return;
}
final long timer = Orient.instance().getProfiler().startChrono();
Map<String, Object> params = new HashMap<>();
stateLock.acquireWriteLock();
try {
if (status == STATUS.CLOSED) {
return;
}
status = STATUS.CLOSING;
if (jvmError.get() == null) {
readCache.storeCacheState(writeCache);
if (!onDelete && jvmError.get() == null) {
makeFullCheckpoint();
}
params = preCloseSteps();
sbTreeCollectionManager.close();
// we close all files inside cache system so we only clear cluster metadata
clusters.clear();
clusterMap.clear();
// we close all files inside cache system so we only clear index metadata and close non core indexes
for (OIndexEngine engine : indexEngines) {
if (engine != null && !(engine instanceof OSBTreeIndexEngine || engine instanceof OHashTableIndexEngine
|| engine instanceof OPrefixBTreeIndexEngine)) {
if (onDelete) {
engine.delete();
} else {
engine.close();
}
}
}
indexEngines.clear();
indexEngineNameMap.clear();
if (getConfiguration() != null) {
if (onDelete) {
((OStorageConfigurationImpl) configuration).delete();
} else {
((OStorageConfigurationImpl) configuration).close();
}
}
super.close(force, onDelete);
if (writeCache != null) {
writeCache.removeLowDiskSpaceListener(this);
writeCache.removeBackgroundExceptionListener(this);
writeCache.removePageIsBrokenListener(this);
}
if (writeAheadLog != null) {
writeAheadLog.removeFullCheckpointListener(this);
writeAheadLog.removeLowDiskSpaceListener(this);
}
if (readCache != null) {
if (!onDelete) {
readCache.closeStorage(writeCache);
} else {
readCache.deleteStorage(writeCache);
}
}
if (writeAheadLog != null) {
if (onDelete) {
writeAheadLog.delete();
} else {
writeAheadLog.close();
}
}
try {
performanceStatisticManager.unregisterMBean(name, id);
} catch (Exception e) {
OLogManager.instance().error(this, "MBean for write cache cannot be unregistered", e);
}
postCloseSteps(onDelete, jvmError.get() != null);
transaction = null;
} else {
OLogManager.instance()
.errorNoDb(this, "Because of JVM error happened inside of storage it can not be properly closed", null);
}
status = STATUS.CLOSED;
} catch (IOException e) {
final String message = "Error on closing of storage '" + name;
OLogManager.instance().error(this, message, e);
throw OException.wrapException(new OStorageException(message), e);
} finally {
//noinspection ResultOfMethodCallIgnored
Orient.instance().getProfiler().stopChrono("db." + name + ".close", "Close a database", timer, "db.*.close");
stateLock.releaseWriteLock();
}
postCloseStepsAfterLock(params);
}
@SuppressWarnings("unused")
protected void closeClusters(boolean onDelete) throws IOException {
for (OCluster cluster : clusters) {
if (cluster != null) {
cluster.close(!onDelete);
}
}
clusters.clear();
clusterMap.clear();
}
@SuppressWarnings("unused")
protected void closeIndexes(boolean onDelete) {
for (OIndexEngine engine : indexEngines) {
if (engine != null) {
if (onDelete) {
try {
engine.delete();
} catch (IOException e) {
OLogManager.instance().error(this, "Can not delete index engine " + engine.getName(), e);
}
} else {
engine.close();
}
}
}
indexEngines.clear();
indexEngineNameMap.clear();
}
@SuppressFBWarnings(value = "PZLA_PREFER_ZERO_LENGTH_ARRAYS")
private byte[] checkAndIncrementVersion(final OCluster iCluster, final ORecordId rid, final AtomicInteger version,
final AtomicInteger iDatabaseVersion, final byte[] iRecordContent, final byte iRecordType) {
final int v = version.get();
switch (v) {
// DOCUMENT UPDATE, NO VERSION CONTROL
case -1:
iDatabaseVersion.incrementAndGet();
break;
// DOCUMENT UPDATE, NO VERSION CONTROL, NO VERSION UPDATE
case -2:
break;
default:
// MVCC CONTROL AND RECORD UPDATE OR WRONG VERSION VALUE
// MVCC TRANSACTION: CHECK IF VERSION IS THE SAME
if (v < -2) {
// OVERWRITE VERSION: THIS IS USED IN CASE OF FIX OF RECORDS IN DISTRIBUTED MODE
version.set(ORecordVersionHelper.clearRollbackMode(v));
iDatabaseVersion.set(version.get());
} else if (v != iDatabaseVersion.get()) {
final ORecordConflictStrategy strategy =
iCluster.getRecordConflictStrategy() != null ? iCluster.getRecordConflictStrategy() : recordConflictStrategy;
return strategy.onUpdate(this, iRecordType, rid, v, iRecordContent, iDatabaseVersion);
} else
// OK, INCREMENT DB VERSION
{
iDatabaseVersion.incrementAndGet();
}
}
return null;
}
private void commitEntry(final ORecordOperation txEntry, final OPhysicalPosition allocated, ORecordSerializer serializer) {
final ORecord rec = txEntry.getRecord();
if (txEntry.type != ORecordOperation.DELETED && !rec.isDirty())
// NO OPERATION
{
return;
}
ORecordId rid = (ORecordId) rec.getIdentity();
if (txEntry.type == ORecordOperation.UPDATED && rid.isNew())
// OVERWRITE OPERATION AS CREATE
{
txEntry.type = ORecordOperation.CREATED;
}
ORecordSerializationContext.pushContext();
try {
final OCluster cluster = getClusterById(rid.getClusterId());
if (cluster.getName().equals(OMetadataDefault.CLUSTER_INDEX_NAME) || cluster.getName()
.equals(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME))
// AVOID TO COMMIT INDEX STUFF
{
return;
}
switch (txEntry.type) {
case ORecordOperation.LOADED:
break;
case ORecordOperation.CREATED: {
final byte[] stream = serializer.toStream(rec, false);
if (allocated != null) {
final OPhysicalPosition ppos;
final byte recordType = ORecordInternal.getRecordType(rec);
ppos = doCreateRecord(rid, stream, rec.getVersion(), recordType, null, cluster, allocated).getResult();
ORecordInternal.setVersion(rec, ppos.recordVersion);
} else {
// USE -2 AS VERSION TO AVOID INCREMENTING THE VERSION
final OStorageOperationResult<Integer> updateRes = updateRecord(rid, ORecordInternal.isContentChanged(rec), stream, -2,
ORecordInternal.getRecordType(rec), -1, null);
ORecordInternal.setVersion(rec, updateRes.getResult());
if (updateRes.getModifiedRecordContent() != null) {
ORecordInternal.fill(rec, rid, updateRes.getResult(), updateRes.getModifiedRecordContent(), false);
}
}
break;
}
case ORecordOperation.UPDATED: {
final byte[] stream = serializer.toStream(rec, false);
final OStorageOperationResult<Integer> updateRes = doUpdateRecord(rid, ORecordInternal.isContentChanged(rec), stream,
rec.getVersion(), ORecordInternal.getRecordType(rec), null, cluster);
txEntry.setResultData(updateRes.getResult());
ORecordInternal.setVersion(rec, updateRes.getResult());
if (updateRes.getModifiedRecordContent() != null) {
ORecordInternal.fill(rec, rid, updateRes.getResult(), updateRes.getModifiedRecordContent(), false);
}
break;
}
case ORecordOperation.DELETED: {
if (rec instanceof ODocument) {
ORidBagDeleter.deleteAllRidBags((ODocument) rec);
}
deleteRecord(rid, rec.getVersion(), -1, null);
break;
}
default:
throw new OStorageException("Unknown record operation " + txEntry.type);
}
} finally {
ORecordSerializationContext.pullContext();
}
// RESET TRACKING
if (rec instanceof ODocument && ((ODocument) rec).isTrackingChanges()) {
ODocumentInternal.clearTrackData(((ODocument) rec));
}
ORecordInternal.unsetDirty(rec);
}
private void checkClusterSegmentIndexRange(final int iClusterId) {
if (iClusterId < 0 || iClusterId > clusters.size() - 1) {
throw new IllegalArgumentException("Cluster segment #" + iClusterId + " does not exist in database '" + name + "'");
}
}
private OLogSequenceNumber restoreFromWAL() throws IOException {
if (writeAheadLog == null) {
OLogManager.instance().error(this, "Restore is not possible because write ahead logging is switched off.", null);
return null;
}
if (writeAheadLog.begin() == null) {
OLogManager.instance().error(this, "Restore is not possible because write ahead log is empty.", null);
return null;
}
OLogManager.instance().info(this, "Looking for last checkpoint...");
final OLogSequenceNumber end = writeAheadLog.end();
if (end == null) {
OLogManager.instance().errorNoDb(this, "WAL is empty, there is nothing not restore", null);
return null;
}
writeAheadLog.addCutTillLimit(end);
try {
OLogSequenceNumber lastCheckPoint;
try {
lastCheckPoint = writeAheadLog.getLastCheckpoint();
} catch (OWALPageBrokenException ignore) {
lastCheckPoint = null;
}
if (lastCheckPoint == null) {
OLogManager.instance().info(this, "Checkpoints are absent, the restore will start from the beginning.");
return restoreFromBeginning();
}
List<OWriteableWALRecord> checkPointRecord;
try {
checkPointRecord = writeAheadLog.read(lastCheckPoint, 1);
} catch (OWALPageBrokenException ignore) {
checkPointRecord = Collections.emptyList();
}
if (checkPointRecord.isEmpty()) {
OLogManager.instance().info(this, "Checkpoints are absent, the restore will start from the beginning.");
return restoreFromBeginning();
}
if (checkPointRecord.get(0) instanceof OFuzzyCheckpointStartRecord) {
OLogManager.instance().info(this, "Found FUZZY checkpoint.");
boolean fuzzyCheckPointIsComplete = checkFuzzyCheckPointIsComplete(lastCheckPoint);
if (!fuzzyCheckPointIsComplete) {
OLogManager.instance().warn(this, "FUZZY checkpoint is not complete.");
OLogSequenceNumber previousCheckpoint = ((OFuzzyCheckpointStartRecord) checkPointRecord.get(0)).getPreviousCheckpoint();
checkPointRecord = Collections.emptyList();
if (previousCheckpoint != null) {
checkPointRecord = writeAheadLog.read(previousCheckpoint, 1);
}
if (!checkPointRecord.isEmpty()) {
OLogManager.instance().warn(this, "Restore will start from the previous checkpoint.");
return restoreFromCheckPoint((OAbstractCheckPointStartRecord) checkPointRecord.get(0));
} else {
OLogManager.instance().warn(this, "Restore will start from the beginning.");
return restoreFromBeginning();
}
} else {
return restoreFromCheckPoint((OAbstractCheckPointStartRecord) checkPointRecord.get(0));
}
}
if (checkPointRecord.get(0) instanceof OFullCheckpointStartRecord) {
OLogManager.instance().info(this, "FULL checkpoint found.");
boolean fullCheckPointIsComplete = checkFullCheckPointIsComplete(lastCheckPoint);
if (!fullCheckPointIsComplete) {
OLogManager.instance().warn(this, "FULL checkpoint has not completed.");
OLogSequenceNumber previousCheckpoint = ((OFullCheckpointStartRecord) checkPointRecord.get(0)).getPreviousCheckpoint();
checkPointRecord = Collections.emptyList();
if (previousCheckpoint != null) {
checkPointRecord = writeAheadLog.read(previousCheckpoint, 1);
}
if (!checkPointRecord.isEmpty()) {
OLogManager.instance().warn(this, "Restore will start from the previous checkpoint.");
return restoreFromCheckPoint((OAbstractCheckPointStartRecord) checkPointRecord.get(0));
} else {
OLogManager.instance().warn(this, "Restore will start from the beginning.");
return restoreFromBeginning();
}
} else {
return restoreFromCheckPoint((OAbstractCheckPointStartRecord) checkPointRecord.get(0));
}
}
throw new OStorageException("Unknown checkpoint record type " + checkPointRecord.get(0).getClass().getName());
} finally {
writeAheadLog.removeCutTillLimit(end);
}
}
private boolean checkFullCheckPointIsComplete(OLogSequenceNumber lastCheckPoint) throws IOException {
try {
List<OWriteableWALRecord> walRecords = writeAheadLog.next(lastCheckPoint, 10);
while (!walRecords.isEmpty()) {
for (OWriteableWALRecord walRecord : walRecords) {
if (walRecord instanceof OCheckpointEndRecord) {
return true;
}
}
walRecords = writeAheadLog.next(walRecords.get(walRecords.size() - 1).getLsn(), 10);
}
} catch (OWALPageBrokenException ignore) {
return false;
}
return false;
}
@Override
public String incrementalBackup(String backupDirectory, OCallable<Void, Void> started) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Incremental backup is supported only in enterprise version");
}
@Override
public void restoreFromIncrementalBackup(String filePath) {
throw new UnsupportedOperationException("Incremental backup is supported only in enterprise version");
}
private boolean checkFuzzyCheckPointIsComplete(OLogSequenceNumber lastCheckPoint) throws IOException {
try {
List<OWriteableWALRecord> walRecords = writeAheadLog.next(lastCheckPoint, 10);
while (!walRecords.isEmpty()) {
for (OWriteableWALRecord walRecord : walRecords) {
if (walRecord instanceof OFuzzyCheckpointEndRecord) {
return true;
}
}
walRecords = writeAheadLog.next(walRecords.get(walRecords.size() - 1).getLsn(), 10);
}
} catch (OWALPageBrokenException ignore) {
return false;
}
return false;
}
private OLogSequenceNumber restoreFromCheckPoint(OAbstractCheckPointStartRecord checkPointRecord) throws IOException {
if (checkPointRecord instanceof OFuzzyCheckpointStartRecord) {
return restoreFromFuzzyCheckPoint((OFuzzyCheckpointStartRecord) checkPointRecord);
}
if (checkPointRecord instanceof OFullCheckpointStartRecord) {
return restoreFromFullCheckPoint((OFullCheckpointStartRecord) checkPointRecord);
}
throw new OStorageException("Unknown checkpoint record type " + checkPointRecord.getClass().getName());
}
private OLogSequenceNumber restoreFromFullCheckPoint(OFullCheckpointStartRecord checkPointRecord) throws IOException {
OLogManager.instance().info(this, "Data restore procedure from full checkpoint is started. Restore is performed from LSN %s",
checkPointRecord.getLsn());
final OLogSequenceNumber lsn = writeAheadLog.next(checkPointRecord.getLsn(), 1).get(0).getLsn();
return restoreFrom(lsn, writeAheadLog);
}
private OLogSequenceNumber restoreFromFuzzyCheckPoint(OFuzzyCheckpointStartRecord checkPointRecord) throws IOException {
OLogManager.instance().infoNoDb(this, "Data restore procedure from FUZZY checkpoint is started.");
OLogSequenceNumber flushedLsn = checkPointRecord.getFlushedLsn();
if (flushedLsn.compareTo(writeAheadLog.begin()) < 0) {
OLogManager.instance().errorNoDb(this,
"Fuzzy checkpoint points to removed part of the log, " + "will try to restore data from the rest of the WAL", null);
flushedLsn = writeAheadLog.begin();
}
return restoreFrom(flushedLsn, writeAheadLog);
}
private OLogSequenceNumber restoreFromBeginning() throws IOException {
OLogManager.instance().info(this, "Data restore procedure is started.");
OLogSequenceNumber lsn = writeAheadLog.begin();
return restoreFrom(lsn, writeAheadLog);
}
@SuppressWarnings("WeakerAccess")
protected final OLogSequenceNumber restoreFrom(OLogSequenceNumber lsn, OWriteAheadLog writeAheadLog) throws IOException {
OLogSequenceNumber logSequenceNumber = null;
OModifiableBoolean atLeastOnePageUpdate = new OModifiableBoolean();
long recordsProcessed = 0;
final int reportBatchSize = OGlobalConfiguration.WAL_REPORT_AFTER_OPERATIONS_DURING_RESTORE.getValueAsInteger();
final Map<OOperationUnitId, List<OWALRecord>> operationUnits = new HashMap<>();
long lastReportTime = 0;
try {
List<OWriteableWALRecord> records = writeAheadLog.read(lsn, 1_000);
while (!records.isEmpty()) {
for (OWriteableWALRecord walRecord : records) {
logSequenceNumber = walRecord.getLsn();
if (walRecord instanceof OAtomicUnitEndRecord) {
OAtomicUnitEndRecord atomicUnitEndRecord = (OAtomicUnitEndRecord) walRecord;
List<OWALRecord> atomicUnit = operationUnits.remove(atomicUnitEndRecord.getOperationUnitId());
// in case of data restore from fuzzy checkpoint part of operations may be already flushed to the disk
if (atomicUnit != null) {
atomicUnit.add(walRecord);
restoreAtomicUnit(atomicUnit, atLeastOnePageUpdate);
}
} else if (walRecord instanceof OAtomicUnitStartRecord) {
List<OWALRecord> operationList = new ArrayList<>();
assert !operationUnits.containsKey(((OAtomicUnitStartRecord) walRecord).getOperationUnitId());
operationUnits.put(((OAtomicUnitStartRecord) walRecord).getOperationUnitId(), operationList);
operationList.add(walRecord);
} else if (walRecord instanceof OOperationUnitRecord) {
OOperationUnitRecord operationUnitRecord = (OOperationUnitRecord) walRecord;
List<OWALRecord> operationList = operationUnits.get(operationUnitRecord.getOperationUnitId());
if (operationList == null || operationList.isEmpty()) {
OLogManager.instance().errorNoDb(this, "'Start transaction' record is absent for atomic operation", null);
if (operationList == null) {
operationList = new ArrayList<>();
operationUnits.put(operationUnitRecord.getOperationUnitId(), operationList);
}
}
operationList.add(operationUnitRecord);
} else if (walRecord instanceof ONonTxOperationPerformedWALRecord) {
if (!wereNonTxOperationsPerformedInPreviousOpen) {
OLogManager.instance()
.warnNoDb(this, "Non tx operation was used during data modification we will need index rebuild.");
wereNonTxOperationsPerformedInPreviousOpen = true;
}
} else {
OLogManager.instance().warnNoDb(this, "Record %s will be skipped during data restore", walRecord);
}
recordsProcessed++;
final long currentTime = System.currentTimeMillis();
if (reportBatchSize > 0 && recordsProcessed % reportBatchSize == 0
|| currentTime - lastReportTime > WAL_RESTORE_REPORT_INTERVAL) {
OLogManager.instance()
.infoNoDb(this, "%d operations were processed, current LSN is %s last LSN is %s", recordsProcessed, lsn,
writeAheadLog.end());
lastReportTime = currentTime;
}
}
records = writeAheadLog.next(records.get(records.size() - 1).getLsn(), 1_000);
}
} catch (OWALPageBrokenException e) {
OLogManager.instance()
.errorNoDb(this, "Data restore was paused because broken WAL page was found. The rest of changes will be rolled back.",
e);
} catch (RuntimeException e) {
OLogManager.instance().errorNoDb(this,
"Data restore was paused because of exception. The rest of changes will be rolled back and WAL files will be backed up."
+ " Please report issue about this exception to bug tracker and provide WAL files which are backed up in 'wal_backup' directory.",
e);
backUpWAL(e);
}
if (atLeastOnePageUpdate.getValue()) {
return logSequenceNumber;
}
return null;
}
private void backUpWAL(Exception e) {
try {
final File rootDir = new File(getConfiguration().getDirectory());
final File backUpDir = new File(rootDir, "wal_backup");
if (!backUpDir.exists()) {
final boolean created = backUpDir.mkdir();
if (!created) {
OLogManager.instance().error(this, "Cannot create directory for backup files " + backUpDir.getAbsolutePath(), null);
return;
}
}
final Date date = new Date();
final SimpleDateFormat dateFormat = new SimpleDateFormat("dd_MM_yy_HH_mm_ss");
final String strDate = dateFormat.format(date);
final String archiveName = "wal_backup_" + strDate + ".zip";
final String metadataName = "wal_metadata_" + strDate + ".txt";
final File archiveFile = new File(backUpDir, archiveName);
if (!archiveFile.createNewFile()) {
OLogManager.instance().error(this, "Cannot create backup file " + archiveFile.getAbsolutePath(), null);
return;
}
try (final FileOutputStream archiveOutputStream = new FileOutputStream(archiveFile)) {
try (final ZipOutputStream archiveZipOutputStream = new ZipOutputStream(new BufferedOutputStream(archiveOutputStream))) {
final ZipEntry metadataEntry = new ZipEntry(metadataName);
archiveZipOutputStream.putNextEntry(metadataEntry);
final PrintWriter metadataFileWriter = new PrintWriter(
new OutputStreamWriter(archiveZipOutputStream, StandardCharsets.UTF_8));
metadataFileWriter.append("Storage name : ").append(getName()).append("\r\n");
metadataFileWriter.append("Date : ").append(strDate).append("\r\n");
metadataFileWriter.append("Stacktrace : \r\n");
e.printStackTrace(metadataFileWriter);
metadataFileWriter.flush();
archiveZipOutputStream.closeEntry();
final List<String> walPaths = ((OCASDiskWriteAheadLog) writeAheadLog).getWalFiles();
for (String walSegment : walPaths) {
archiveEntry(archiveZipOutputStream, walSegment);
}
archiveEntry(archiveZipOutputStream, ((OCASDiskWriteAheadLog) writeAheadLog).getWMRFile().toString());
}
}
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error during WAL backup", ioe);
}
}
private static void archiveEntry(ZipOutputStream archiveZipOutputStream, String walSegment) throws IOException {
final File walFile = new File(walSegment);
final ZipEntry walZipEntry = new ZipEntry(walFile.getName());
archiveZipOutputStream.putNextEntry(walZipEntry);
try {
try (FileInputStream walInputStream = new FileInputStream(walFile)) {
try (BufferedInputStream walBufferedInputStream = new BufferedInputStream(walInputStream)) {
final byte[] buffer = new byte[1024];
int readBytes;
while ((readBytes = walBufferedInputStream.read(buffer)) > -1) {
archiveZipOutputStream.write(buffer, 0, readBytes);
}
}
}
} finally {
archiveZipOutputStream.closeEntry();
}
}
@SuppressWarnings("WeakerAccess")
protected final void restoreAtomicUnit(List<OWALRecord> atomicUnit, OModifiableBoolean atLeastOnePageUpdate) throws IOException {
assert atomicUnit.get(atomicUnit.size() - 1) instanceof OAtomicUnitEndRecord;
for (OWALRecord walRecord : atomicUnit) {
if (walRecord instanceof OFileDeletedWALRecord) {
OFileDeletedWALRecord fileDeletedWALRecord = (OFileDeletedWALRecord) walRecord;
if (writeCache.exists(fileDeletedWALRecord.getFileId())) {
readCache.deleteFile(fileDeletedWALRecord.getFileId(), writeCache);
}
} else if (walRecord instanceof OFileCreatedWALRecord) {
OFileCreatedWALRecord fileCreatedCreatedWALRecord = (OFileCreatedWALRecord) walRecord;
if (!writeCache.exists(fileCreatedCreatedWALRecord.getFileName())) {
readCache.addFile(fileCreatedCreatedWALRecord.getFileName(), fileCreatedCreatedWALRecord.getFileId(), writeCache);
}
} else if (walRecord instanceof OUpdatePageRecord) {
final OUpdatePageRecord updatePageRecord = (OUpdatePageRecord) walRecord;
long fileId = updatePageRecord.getFileId();
if (!writeCache.exists(fileId)) {
String fileName = writeCache.restoreFileById(fileId);
if (fileName == null) {
throw new OStorageException(
"File with id " + fileId + " was deleted from storage, the rest of operations can not be restored");
} else {
OLogManager.instance().warn(this, "Previously deleted file with name " + fileName
+ " was deleted but new empty file was added to continue restore process");
}
}
final long pageIndex = updatePageRecord.getPageIndex();
fileId = writeCache.externalFileId(writeCache.internalFileId(fileId));
OCacheEntry cacheEntry = readCache.loadForWrite(fileId, pageIndex, true, writeCache, 1, false, null);
if (cacheEntry == null) {
do {
if (cacheEntry != null) {
readCache.releaseFromWrite(cacheEntry, writeCache);
}
cacheEntry = readCache.allocateNewPage(fileId, writeCache, false, null, false);
} while (cacheEntry.getPageIndex() != pageIndex);
}
try {
ODurablePage durablePage = new ODurablePage(cacheEntry);
durablePage.restoreChanges(updatePageRecord.getChanges());
durablePage.setLsn(updatePageRecord.getLsn());
} finally {
readCache.releaseFromWrite(cacheEntry, writeCache);
}
atLeastOnePageUpdate.setValue(true);
} else if (walRecord instanceof OAtomicUnitStartRecord) {
//noinspection UnnecessaryContinue
continue;
} else if (walRecord instanceof OAtomicUnitEndRecord) {
//noinspection UnnecessaryContinue
continue;
} else {
OLogManager.instance()
.error(this, "Invalid WAL record type was passed %s. Given record will be skipped.", null, walRecord.getClass());
assert false : "Invalid WAL record type was passed " + walRecord.getClass().getName();
}
}
}
/**
* Method which is called before any data modification operation to check alarm conditions such as: <ol> <li>Low disk space</li>
* <li>Exception during data flush in background threads</li> <li>Broken files</li> </ol>
* If one of those conditions are satisfied data modification operation is aborted and storage is switched in "read only" mode.
*/
private void checkLowDiskSpaceRequestsAndReadOnlyConditions() {
if (transaction.get() != null) {
return;
}
if (lowDiskSpace != null) {
if (checkpointInProgress.compareAndSet(false, true)) {
try {
if (writeCache.checkLowDiskSpace()) {
OLogManager.instance().error(this, "Not enough disk space, force sync will be called", null);
synch();
if (writeCache.checkLowDiskSpace()) {
throw new OLowDiskSpaceException("Error occurred while executing a write operation to database '" + name
+ "' due to limited free space on the disk (" + (lowDiskSpace.freeSpace / (1024 * 1024))
+ " MB). The database is now working in read-only mode."
+ " Please close the database (or stop OrientDB), make room on your hard drive and then reopen the database. "
+ "The minimal required space is " + (lowDiskSpace.requiredSpace / (1024 * 1024)) + " MB. "
+ "Required space is now set to " + getConfiguration().getContextConfiguration()
.getValueAsInteger(OGlobalConfiguration.DISK_CACHE_FREE_SPACE_LIMIT)
+ "MB (you can change it by setting parameter " + OGlobalConfiguration.DISK_CACHE_FREE_SPACE_LIMIT.getKey()
+ ") .");
} else {
lowDiskSpace = null;
}
} else {
lowDiskSpace = null;
}
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error during low disk space handling"), e);
} finally {
checkpointInProgress.set(false);
}
}
}
checkReadOnlyConditions();
}
public final void checkReadOnlyConditions() {
if (dataFlushException != null) {
throw OException.wrapException(new OStorageException(
"Error in data flush background thread, please restart database and send full stack trace inside of bug report"),
dataFlushException);
}
if (!brokenPages.isEmpty()) {
//order pages by file and index
final Map<String, SortedSet<Long>> pagesByFile = new HashMap<>();
for (OPair<String, Long> brokenPage : brokenPages) {
final SortedSet<Long> sortedPages = pagesByFile.computeIfAbsent(brokenPage.key, (fileName) -> new TreeSet<>());
sortedPages.add(brokenPage.value);
}
final StringBuilder brokenPagesList = new StringBuilder();
brokenPagesList.append("[");
for (String fileName : pagesByFile.keySet()) {
brokenPagesList.append('\'').append(fileName).append("' :");
final SortedSet<Long> pageIndexes = pagesByFile.get(fileName);
final long lastPage = pageIndexes.last();
for (Long pageIndex : pagesByFile.get(fileName)) {
brokenPagesList.append(pageIndex);
if (pageIndex != lastPage) {
brokenPagesList.append(", ");
}
}
brokenPagesList.append(";");
}
brokenPagesList.append("]");
throw new OPageIsBrokenException("Following files and pages are detected to be broken " + brokenPagesList + ", storage is "
+ "switched to 'read only' mode. Any modification operations are prohibited. "
+ "To restore database and make it fully operational you may export and import database " + "to and from JSON.");
}
if (jvmError.get() != null) {
throw new OJVMErrorException("JVM error '" + jvmError.get().getClass().getSimpleName() + " : " + jvmError.get().getMessage()
+ "' occurred during data processing, storage is switched to 'read-only' mode. "
+ "To prevent this exception please restart the JVM and check data consistency by calling of 'check database' "
+ "command from database console.");
}
}
@SuppressWarnings("unused")
public void setStorageConfigurationUpdateListener(OStorageConfigurationUpdateListener storageConfigurationUpdateListener) {
stateLock.acquireWriteLock();
try {
checkOpenness();
((OStorageConfigurationImpl) configuration).setConfigurationUpdateListener(storageConfigurationUpdateListener);
} finally {
stateLock.releaseWriteLock();
}
}
@SuppressWarnings("unused")
protected static Map<Integer, List<ORecordId>> getRidsGroupedByCluster(final Collection<ORecordId> iRids) {
final Map<Integer, List<ORecordId>> ridsPerCluster = new HashMap<>();
for (ORecordId rid : iRids) {
List<ORecordId> rids = ridsPerCluster.computeIfAbsent(rid.getClusterId(), k -> new ArrayList<>(iRids.size()));
rids.add(rid);
}
return ridsPerCluster;
}
private static void lockIndexes(final TreeMap<String, OTransactionIndexChanges> indexes) {
for (OTransactionIndexChanges changes : indexes.values()) {
assert changes.changesPerKey instanceof TreeMap;
final OIndexInternal<?> index = changes.getAssociatedIndex();
final List<Object> orderedIndexNames = new ArrayList<>(changes.changesPerKey.keySet());
if (orderedIndexNames.size() > 1) {
orderedIndexNames.sort((o1, o2) -> {
String i1 = index.getIndexNameByKey(o1);
String i2 = index.getIndexNameByKey(o2);
return i1.compareTo(i2);
});
}
boolean fullyLocked = false;
for (Object key : orderedIndexNames) {
if (index.acquireAtomicExclusiveLock(key)) {
fullyLocked = true;
break;
}
}
if (!fullyLocked && !changes.nullKeyChanges.entries.isEmpty()) {
index.acquireAtomicExclusiveLock(null);
}
}
}
private static void lockClusters(final TreeMap<Integer, OCluster> clustersToLock) {
for (OCluster cluster : clustersToLock.values()) {
cluster.acquireAtomicExclusiveLock();
}
}
private void lockRidBags(final TreeMap<Integer, OCluster> clusters, final TreeMap<String, OTransactionIndexChanges> indexes,
OIndexManager manager) {
final OAtomicOperation atomicOperation = OAtomicOperationsManager.getCurrentOperation();
for (Integer clusterId : clusters.keySet()) {
atomicOperationsManager
.acquireExclusiveLockTillOperationComplete(atomicOperation, OSBTreeCollectionManagerAbstract.generateLockName(clusterId));
}
for (Map.Entry<String, OTransactionIndexChanges> entry : indexes.entrySet()) {
final String indexName = entry.getKey();
final OIndexInternal<?> index = entry.getValue().resolveAssociatedIndex(indexName, manager);
if (!index.isUnique()) {
atomicOperationsManager
.acquireExclusiveLockTillOperationComplete(atomicOperation, OIndexRIDContainerSBTree.generateLockName(indexName));
}
}
}
private void registerProfilerHooks() {
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".createRecord", "Number of created records", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordCreated), "db.*.createRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".readRecord", "Number of read records", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordRead), "db.*.readRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".updateRecord", "Number of updated records", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordUpdated), "db.*.updateRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".deleteRecord", "Number of deleted records", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordDeleted), "db.*.deleteRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".scanRecord", "Number of read scanned", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordScanned), "db.*.scanRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".recyclePosition", "Number of recycled records", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(recordRecycled), "db.*.recyclePosition");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".conflictRecord", "Number of conflicts during updating and deleting records",
OProfiler.METRIC_TYPE.COUNTER, new AtomicLongOProfilerHookValue(recordConflict), "db.*.conflictRecord");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".txBegun", "Number of transactions begun", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(txBegun), "db.*.txBegun");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".txCommit", "Number of committed transactions", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(txCommit), "db.*.txCommit");
Orient.instance().getProfiler()
.registerHookValue("db." + this.name + ".txRollback", "Number of rolled back transactions", OProfiler.METRIC_TYPE.COUNTER,
new AtomicLongOProfilerHookValue(txRollback), "db.*.txRollback");
}
protected final RuntimeException logAndPrepareForRethrow(RuntimeException runtimeException) {
if (!(runtimeException instanceof OHighLevelException || runtimeException instanceof ONeedRetryException)) {
OLogManager.instance()
.errorStorage(this, "Exception `%08X` in storage `%s`: %s", runtimeException, System.identityHashCode(runtimeException),
getURL(), OConstants.getVersion());
}
return runtimeException;
}
protected final Error logAndPrepareForRethrow(Error error) {
return logAndPrepareForRethrow(error, true);
}
private Error logAndPrepareForRethrow(Error error, boolean putInReadOnlyMode) {
if (!(error instanceof OHighLevelException)) {
OLogManager.instance()
.errorStorage(this, "Exception `%08X` in storage `%s`: %s", error, System.identityHashCode(error), getURL(),
OConstants.getVersion());
}
if (putInReadOnlyMode) {
handleJVMError(error);
}
return error;
}
protected final RuntimeException logAndPrepareForRethrow(Throwable throwable) {
if (!(throwable instanceof OHighLevelException || throwable instanceof ONeedRetryException)) {
OLogManager.instance()
.errorStorage(this, "Exception `%08X` in storage `%s`: %s", throwable, System.identityHashCode(throwable), getURL(),
OConstants.getVersion());
}
return new RuntimeException(throwable);
}
private OInvalidIndexEngineIdException logAndPrepareForRethrow(OInvalidIndexEngineIdException exception) {
OLogManager.instance()
.errorStorage(this, "Exception `%08X` in storage `%s` : %s", exception, System.identityHashCode(exception), getURL(),
OConstants.getVersion());
return exception;
}
private static final class FuzzyCheckpointThreadFactory implements ThreadFactory {
@Override
public final Thread newThread(Runnable r) {
Thread thread = new Thread(storageThreadGroup, r);
thread.setDaemon(true);
thread.setUncaughtExceptionHandler(new OUncaughtExceptionHandler());
return thread;
}
}
private final class WALVacuum implements Runnable {
WALVacuum() {
}
@Override
public void run() {
stateLock.acquireReadLock();
try {
if (status == STATUS.CLOSED) {
return;
}
final long[] nonActiveSegments = writeAheadLog.nonActiveSegments();
if (nonActiveSegments.length == 0) {
return;
}
long flushTillSegmentId;
if (nonActiveSegments.length == 1) {
flushTillSegmentId = writeAheadLog.activeSegment();
} else {
flushTillSegmentId = (nonActiveSegments[0] + nonActiveSegments[nonActiveSegments.length - 1]) / 2;
}
long minDirtySegment;
do {
writeCache.flushTillSegment(flushTillSegmentId);
//we should take min lsn BEFORE min write cache LSN call
//to avoid case when new data are changed before call
OLogSequenceNumber endLSN = writeAheadLog.end();
Long minLSNSegment = writeCache.getMinimalNotFlushedSegment();
if (minLSNSegment == null) {
minDirtySegment = endLSN.getSegment();
} else {
minDirtySegment = minLSNSegment;
}
} while (minDirtySegment < flushTillSegmentId);
writeCache.makeFuzzyCheckpoint(minDirtySegment);
} catch (Exception e) {
dataFlushException = e;
OLogManager.instance().error(this, "Error during flushing of data for fuzzy checkpoint", e);
} finally {
stateLock.releaseReadLock();
walVacuumInProgress.set(false);
}
}
}
@Override
public final OStorageConfiguration getConfiguration() {
return configuration;
}
@Override
public final void setSchemaRecordId(String schemaRecordId) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setSchemaRecordId(schemaRecordId);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setDateFormat(String dateFormat) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setDateFormat(dateFormat);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setTimeZone(TimeZone timeZoneValue) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setTimeZone(timeZoneValue);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setLocaleLanguage(String locale) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setLocaleLanguage(locale);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setCharset(String charset) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setCharset(charset);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setIndexMgrRecordId(String indexMgrRecordId) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setIndexMgrRecordId(indexMgrRecordId);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setDateTimeFormat(String dateTimeFormat) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setDateTimeFormat(dateTimeFormat);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setLocaleCountry(String localeCountry) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setLocaleCountry(localeCountry);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setClusterSelection(String clusterSelection) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setClusterSelection(clusterSelection);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setMinimumClusters(int minimumClusters) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setMinimumClusters(minimumClusters);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setValidation(boolean validation) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setValidation(validation);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void removeProperty(String property) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.removeProperty(property);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setProperty(String property, String value) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setProperty(property, value);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void setRecordSerializer(String recordSerializer, int version) {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.setRecordSerializer(recordSerializer);
storageConfiguration.setRecordSerializerVersion(version);
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public final void clearProperties() {
checkOpenness();
stateLock.acquireWriteLock();
try {
checkOpenness();
final OStorageConfigurationImpl storageConfiguration = (OStorageConfigurationImpl) configuration;
storageConfiguration.clearProperties();
storageConfiguration.update();
} catch (RuntimeException ee) {
throw logAndPrepareForRethrow(ee);
} catch (Error ee) {
throw logAndPrepareForRethrow(ee);
} catch (Throwable t) {
throw logAndPrepareForRethrow(t);
} finally {
stateLock.releaseWriteLock();
}
}
}
| Set log level to DEBUG for fuzzy checkpoint logs
| core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OAbstractPaginatedStorage.java | Set log level to DEBUG for fuzzy checkpoint logs | <ide><path>ore/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OAbstractPaginatedStorage.java
<ide> fuzzySegment = endLSN.getSegment();
<ide> }
<ide>
<del> OLogManager.instance().infoNoDb(this,
<add> OLogManager.instance().debugNoDb(this,
<ide> "Before fuzzy checkpoint: min LSN segment is " + minLSNSegment + ", WAL begin is " + beginLSN + ", WAL end is " + endLSN
<del> + ", fuzzy segment is " + fuzzySegment);
<add> + ", fuzzy segment is " + fuzzySegment, null);
<ide>
<ide> if (fuzzySegment > beginLSN.getSegment() && beginLSN.getSegment() < endLSN.getSegment()) {
<ide> OLogManager.instance().infoNoDb(this, "Making fuzzy checkpoint");
<ide> beginLSN = writeAheadLog.begin();
<ide> endLSN = writeAheadLog.end();
<ide>
<del> OLogManager.instance().infoNoDb(this, "After fuzzy checkpoint: WAL begin is " + beginLSN + " WAL end is " + endLSN);
<add> OLogManager.instance().debugNoDb(this, "After fuzzy checkpoint: WAL begin is " + beginLSN + " WAL end is " + endLSN, null);
<ide> } else {
<del> OLogManager.instance().infoNoDb(this, "No reason to make fuzzy checkpoint");
<add> OLogManager.instance().debugNoDb(this, "No reason to make fuzzy checkpoint", null);
<ide> }
<ide> } catch (IOException ioe) {
<ide> throw OException.wrapException(new OIOException("Error during fuzzy checkpoint"), ioe); |
|
Java | apache-2.0 | 5d13c00a7ac07a6f64ef9ff206a4058e5ce249bc | 0 | dkincade/pentaho-kettle,lgrill-pentaho/pentaho-kettle,aminmkhan/pentaho-kettle,MikhailHubanau/pentaho-kettle,YuryBY/pentaho-kettle,mdamour1976/pentaho-kettle,nicoben/pentaho-kettle,pentaho/pentaho-kettle,tkafalas/pentaho-kettle,stepanovdg/pentaho-kettle,nantunes/pentaho-kettle,brosander/pentaho-kettle,cjsonger/pentaho-kettle,pminutillo/pentaho-kettle,airy-ict/pentaho-kettle,rmansoor/pentaho-kettle,mkambol/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,EcoleKeine/pentaho-kettle,pavel-sakun/pentaho-kettle,YuryBY/pentaho-kettle,wseyler/pentaho-kettle,andrei-viaryshka/pentaho-kettle,yshakhau/pentaho-kettle,pedrofvteixeira/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,kurtwalker/pentaho-kettle,stepanovdg/pentaho-kettle,mbatchelor/pentaho-kettle,SergeyTravin/pentaho-kettle,stevewillcock/pentaho-kettle,mdamour1976/pentaho-kettle,skofra0/pentaho-kettle,SergeyTravin/pentaho-kettle,pymjer/pentaho-kettle,emartin-pentaho/pentaho-kettle,kurtwalker/pentaho-kettle,DFieldFL/pentaho-kettle,rmansoor/pentaho-kettle,rfellows/pentaho-kettle,CapeSepias/pentaho-kettle,graimundo/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,MikhailHubanau/pentaho-kettle,pymjer/pentaho-kettle,DFieldFL/pentaho-kettle,rmansoor/pentaho-kettle,andrei-viaryshka/pentaho-kettle,denisprotopopov/pentaho-kettle,YuryBY/pentaho-kettle,ViswesvarSekar/pentaho-kettle,dkincade/pentaho-kettle,pedrofvteixeira/pentaho-kettle,gretchiemoran/pentaho-kettle,ddiroma/pentaho-kettle,GauravAshara/pentaho-kettle,matrix-stone/pentaho-kettle,aminmkhan/pentaho-kettle,denisprotopopov/pentaho-kettle,e-cuellar/pentaho-kettle,brosander/pentaho-kettle,aminmkhan/pentaho-kettle,eayoungs/pentaho-kettle,ivanpogodin/pentaho-kettle,drndos/pentaho-kettle,bmorrise/pentaho-kettle,matrix-stone/pentaho-kettle,airy-ict/pentaho-kettle,codek/pentaho-kettle,matthewtckr/pentaho-kettle,nanata1115/pentaho-kettle,yshakhau/pentaho-kettle,flbrino/pentaho-kettle,skofra0/pentaho-kettle,lgrill-pentaho/pentaho-kettle,hudak/pentaho-kettle,birdtsai/pentaho-kettle,ddiroma/pentaho-kettle,alina-ipatina/pentaho-kettle,roboguy/pentaho-kettle,nantunes/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,matthewtckr/pentaho-kettle,cjsonger/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,akhayrutdinov/pentaho-kettle,alina-ipatina/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,gretchiemoran/pentaho-kettle,birdtsai/pentaho-kettle,stevewillcock/pentaho-kettle,Advent51/pentaho-kettle,pymjer/pentaho-kettle,HiromuHota/pentaho-kettle,wseyler/pentaho-kettle,drndos/pentaho-kettle,drndos/pentaho-kettle,matrix-stone/pentaho-kettle,ddiroma/pentaho-kettle,eayoungs/pentaho-kettle,flbrino/pentaho-kettle,roboguy/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,ViswesvarSekar/pentaho-kettle,CapeSepias/pentaho-kettle,matrix-stone/pentaho-kettle,rfellows/pentaho-kettle,HiromuHota/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,stepanovdg/pentaho-kettle,tkafalas/pentaho-kettle,ViswesvarSekar/pentaho-kettle,stevewillcock/pentaho-kettle,cjsonger/pentaho-kettle,CapeSepias/pentaho-kettle,Advent51/pentaho-kettle,marcoslarsen/pentaho-kettle,alina-ipatina/pentaho-kettle,ma459006574/pentaho-kettle,emartin-pentaho/pentaho-kettle,skofra0/pentaho-kettle,pminutillo/pentaho-kettle,sajeetharan/pentaho-kettle,roboguy/pentaho-kettle,andrei-viaryshka/pentaho-kettle,marcoslarsen/pentaho-kettle,aminmkhan/pentaho-kettle,bmorrise/pentaho-kettle,mattyb149/pentaho-kettle,pentaho/pentaho-kettle,stepanovdg/pentaho-kettle,alina-ipatina/pentaho-kettle,denisprotopopov/pentaho-kettle,matthewtckr/pentaho-kettle,pminutillo/pentaho-kettle,mkambol/pentaho-kettle,ivanpogodin/pentaho-kettle,sajeetharan/pentaho-kettle,MikhailHubanau/pentaho-kettle,kurtwalker/pentaho-kettle,mattyb149/pentaho-kettle,EcoleKeine/pentaho-kettle,yshakhau/pentaho-kettle,zlcnju/kettle,tkafalas/pentaho-kettle,mbatchelor/pentaho-kettle,pavel-sakun/pentaho-kettle,birdtsai/pentaho-kettle,pedrofvteixeira/pentaho-kettle,e-cuellar/pentaho-kettle,marcoslarsen/pentaho-kettle,tmcsantos/pentaho-kettle,mbatchelor/pentaho-kettle,lgrill-pentaho/pentaho-kettle,GauravAshara/pentaho-kettle,ma459006574/pentaho-kettle,nanata1115/pentaho-kettle,dkincade/pentaho-kettle,pymjer/pentaho-kettle,ivanpogodin/pentaho-kettle,ma459006574/pentaho-kettle,ma459006574/pentaho-kettle,e-cuellar/pentaho-kettle,emartin-pentaho/pentaho-kettle,nicoben/pentaho-kettle,Advent51/pentaho-kettle,tmcsantos/pentaho-kettle,denisprotopopov/pentaho-kettle,zlcnju/kettle,akhayrutdinov/pentaho-kettle,flbrino/pentaho-kettle,EcoleKeine/pentaho-kettle,mattyb149/pentaho-kettle,ivanpogodin/pentaho-kettle,sajeetharan/pentaho-kettle,roboguy/pentaho-kettle,wseyler/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,zlcnju/kettle,bmorrise/pentaho-kettle,brosander/pentaho-kettle,eayoungs/pentaho-kettle,jbrant/pentaho-kettle,dkincade/pentaho-kettle,jbrant/pentaho-kettle,jbrant/pentaho-kettle,YuryBY/pentaho-kettle,mdamour1976/pentaho-kettle,tmcsantos/pentaho-kettle,tmcsantos/pentaho-kettle,cjsonger/pentaho-kettle,nicoben/pentaho-kettle,codek/pentaho-kettle,SergeyTravin/pentaho-kettle,lgrill-pentaho/pentaho-kettle,airy-ict/pentaho-kettle,gretchiemoran/pentaho-kettle,tkafalas/pentaho-kettle,ccaspanello/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,pavel-sakun/pentaho-kettle,matthewtckr/pentaho-kettle,mdamour1976/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,kurtwalker/pentaho-kettle,pedrofvteixeira/pentaho-kettle,jbrant/pentaho-kettle,pminutillo/pentaho-kettle,nicoben/pentaho-kettle,bmorrise/pentaho-kettle,mbatchelor/pentaho-kettle,ccaspanello/pentaho-kettle,pavel-sakun/pentaho-kettle,sajeetharan/pentaho-kettle,graimundo/pentaho-kettle,EcoleKeine/pentaho-kettle,rfellows/pentaho-kettle,ddiroma/pentaho-kettle,DFieldFL/pentaho-kettle,codek/pentaho-kettle,SergeyTravin/pentaho-kettle,stevewillcock/pentaho-kettle,mkambol/pentaho-kettle,brosander/pentaho-kettle,rmansoor/pentaho-kettle,nanata1115/pentaho-kettle,e-cuellar/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,akhayrutdinov/pentaho-kettle,CapeSepias/pentaho-kettle,DFieldFL/pentaho-kettle,graimundo/pentaho-kettle,airy-ict/pentaho-kettle,zlcnju/kettle,akhayrutdinov/pentaho-kettle,GauravAshara/pentaho-kettle,graimundo/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,mattyb149/pentaho-kettle,drndos/pentaho-kettle,pentaho/pentaho-kettle,pentaho/pentaho-kettle,birdtsai/pentaho-kettle,marcoslarsen/pentaho-kettle,hudak/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,hudak/pentaho-kettle,Advent51/pentaho-kettle,wseyler/pentaho-kettle,GauravAshara/pentaho-kettle,hudak/pentaho-kettle,nantunes/pentaho-kettle,nantunes/pentaho-kettle,emartin-pentaho/pentaho-kettle,ccaspanello/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,skofra0/pentaho-kettle,flbrino/pentaho-kettle,mkambol/pentaho-kettle,HiromuHota/pentaho-kettle,yshakhau/pentaho-kettle,codek/pentaho-kettle,gretchiemoran/pentaho-kettle,ccaspanello/pentaho-kettle,HiromuHota/pentaho-kettle,eayoungs/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,nanata1115/pentaho-kettle,ViswesvarSekar/pentaho-kettle | /* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.*/
package org.pentaho.di.job.entries.eval;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;
import java.util.List;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryType;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.w3c.dom.Node;
/**
* Job entry type to evaluate the result of a previous job entry.
* It uses a piece of javascript to do this.
*
* @author Matt
* @since 5-11-2003
*/
public class JobEntryEval extends JobEntryBase implements Cloneable, JobEntryInterface {
private String script;
public JobEntryEval(String n, String scr) {
super(n, ""); //$NON-NLS-1$
script = scr;
setID(-1L);
setJobEntryType(JobEntryType.EVAL);
}
public JobEntryEval() {
this("", ""); //$NON-NLS-1$ //$NON-NLS-2$
}
public JobEntryEval(JobEntryBase jeb) {
super(jeb);
}
public Object clone() {
JobEntryEval je = (JobEntryEval) super.clone();
return je;
}
public String getXML() {
StringBuffer retval = new StringBuffer();
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("script", script)); //$NON-NLS-1$ //$NON-NLS-2$
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException {
try {
super.loadXML(entrynode, databases, slaveServers);
script = XMLHandler.getTagValue(entrynode, "script"); //$NON-NLS-1$
} catch (Exception e) {
throw new KettleXMLException(Messages.getString("JobEntryEval.UnableToLoadFromXml"), e); //$NON-NLS-1$
}
}
public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException {
try {
super.loadRep(rep, id_jobentry, databases, slaveServers);
script = rep.getJobEntryAttributeString(id_jobentry, "script"); //$NON-NLS-1$
} catch (KettleDatabaseException dbe) {
throw new KettleException(
Messages.getString("JobEntryEval.UnableToLoadFromRepo", String.valueOf(id_jobentry)), dbe); //$NON-NLS-1$
}
}
// Save the attributes of this job entry
//
public void saveRep(Repository rep, long id_job) throws KettleException {
try {
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "script", script); //$NON-NLS-1$
} catch (KettleDatabaseException dbe) {
throw new KettleException(Messages.getString("JobEntryEval.UnableToSaveToRepo", String.valueOf(id_job)), //$NON-NLS-1$
dbe);
}
}
public void setScript(String s) {
script = s;
}
public String getScript() {
return script;
}
/**
* Evaluate the result of the execution of previous job entry.
* @param result The result to evaulate.
* @param prev_result the previous result
* @param parentJob the parent job
* @return The boolean result of the evaluation script.
*/
public boolean evaluate(Result result, Job parentJob, Result prev_result) {
LogWriter log = LogWriter.getInstance();
Context cx;
Scriptable scope;
String debug = "start"; //$NON-NLS-1$
cx = Context.enter();
debug = "try"; //$NON-NLS-1$
try {
scope = cx.initStandardObjects(null);
debug = "Long"; //$NON-NLS-1$
Long errors = new Long(result.getNrErrors());
Long lines_input = new Long(result.getNrLinesInput());
Long lines_output = new Long(result.getNrLinesOutput());
Long lines_updated = new Long(result.getNrLinesUpdated());
Long lines_rejected = new Long(result.getNrLinesRejected());
Long lines_read = new Long(result.getNrLinesRead());
Long lines_written = new Long(result.getNrLinesWritten());
Long exit_status = new Long(result.getExitStatus());
Long files_retrieved = new Long(result.getNrFilesRetrieved());
Long nr = new Long(result.getEntryNr());
debug = "scope.put"; //$NON-NLS-1$
scope.put("errors", scope, errors); //$NON-NLS-1$
scope.put("lines_input", scope, lines_input); //$NON-NLS-1$
scope.put("lines_output", scope, lines_output); //$NON-NLS-1$
scope.put("lines_updated", scope, lines_updated); //$NON-NLS-1$
scope.put("lines_rejected", scope, lines_rejected); //$NON-NLS-1$
scope.put("lines_read", scope, lines_read); //$NON-NLS-1$
scope.put("lines_written", scope, lines_written); //$NON-NLS-1$
scope.put("files_retrieved", scope, files_retrieved); //$NON-NLS-1$
scope.put("exit_status", scope, exit_status); //$NON-NLS-1$
scope.put("nr", scope, nr); //$NON-NLS-1$
scope.put("is_windows", scope, Boolean.valueOf(Const.isWindows())); //$NON-NLS-1$
Object array[] = null;
if (result.getRows() != null) {
array = result.getRows().toArray();
}
scope.put("rows", scope, array); //$NON-NLS-1$
scope.put("parent_job", scope, parentJob); //$NON-NLS-1$
scope.put("previous_result", scope, prev_result); //$NON-NLS-1$
try {
debug = "cx.evaluateString()"; //$NON-NLS-1$
Object res = cx.evaluateString(scope, this.script, "<cmd>", 1, null); //$NON-NLS-1$
debug = "toBoolean"; //$NON-NLS-1$
boolean retval = Context.toBoolean(res);
// System.out.println(result.toString()+" + ["+this.script+"] --> "+retval);
result.setNrErrors(0);
return retval;
} catch (Exception e) {
result.setNrErrors(1);
log.logError(toString(), Messages.getString("JobEntryEval.CouldNotCompile", e.toString())); //$NON-NLS-1$
return false;
}
} catch (Exception e) {
result.setNrErrors(1);
log.logError(toString(), Messages.getString("JobEntryEval.ErrorEvaluating", debug, e.toString())); //$NON-NLS-1$
return false;
} finally {
Context.exit();
}
}
/**
* Execute this job entry and return the result.
* In this case it means, just set the result boolean in the Result class.
* @param prev_result The result of the previous execution
* @return The Result of the execution.
*/
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
prev_result.setResult(evaluate(prev_result, parentJob, prev_result));
return prev_result;
}
public boolean resetErrorsBeforeExecution() {
// we should be able to evaluate the errors in
// the previous jobentry.
return false;
}
public boolean evaluates() {
return true;
}
public boolean isUnconditional() {
return false;
}
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta)
{
andValidator().validate(this, "script", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
}
} | src/org/pentaho/di/job/entries/eval/JobEntryEval.java | /* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.*/
package org.pentaho.di.job.entries.eval;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;
import java.util.List;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryType;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.w3c.dom.Node;
/**
* Job entry type to evaluate the result of a previous job entry.
* It uses a piece of javascript to do this.
*
* @author Matt
* @since 5-11-2003
*/
public class JobEntryEval extends JobEntryBase implements Cloneable, JobEntryInterface {
private String script;
public JobEntryEval(String n, String scr) {
super(n, ""); //$NON-NLS-1$
script = scr;
setID(-1L);
setJobEntryType(JobEntryType.EVAL);
}
public JobEntryEval() {
this("", ""); //$NON-NLS-1$ //$NON-NLS-2$
}
public JobEntryEval(JobEntryBase jeb) {
super(jeb);
}
public Object clone() {
JobEntryEval je = (JobEntryEval) super.clone();
return je;
}
public String getXML() {
StringBuffer retval = new StringBuffer();
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("script", script)); //$NON-NLS-1$ //$NON-NLS-2$
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException {
try {
super.loadXML(entrynode, databases, slaveServers);
script = XMLHandler.getTagValue(entrynode, "script"); //$NON-NLS-1$
} catch (Exception e) {
throw new KettleXMLException(Messages.getString("JobEntryEval.UnableToLoadFromXml"), e); //$NON-NLS-1$
}
}
public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException {
try {
super.loadRep(rep, id_jobentry, databases, slaveServers);
script = rep.getJobEntryAttributeString(id_jobentry, "script"); //$NON-NLS-1$
} catch (KettleDatabaseException dbe) {
throw new KettleException(
Messages.getString("JobEntryEval.UnableToLoadFromRepo", String.valueOf(id_jobentry)), dbe); //$NON-NLS-1$
}
}
// Save the attributes of this job entry
//
public void saveRep(Repository rep, long id_job) throws KettleException {
try {
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "script", script); //$NON-NLS-1$
} catch (KettleDatabaseException dbe) {
throw new KettleException(Messages.getString("JobEntryEval.UnableToSaveToRepo", String.valueOf(id_job)), //$NON-NLS-1$
dbe);
}
}
public void setScript(String s) {
script = s;
}
public String getScript() {
return script;
}
/**
* Evaluate the result of the execution of previous job entry.
* @param result The result to evaulate.
* @return The boolean result of the evaluation script.
*/
public boolean evaluate(Result result) {
LogWriter log = LogWriter.getInstance();
Context cx;
Scriptable scope;
String debug = "start"; //$NON-NLS-1$
cx = Context.enter();
debug = "try"; //$NON-NLS-1$
try {
scope = cx.initStandardObjects(null);
debug = "Long"; //$NON-NLS-1$
Long errors = new Long(result.getNrErrors());
Long lines_input = new Long(result.getNrLinesInput());
Long lines_output = new Long(result.getNrLinesOutput());
Long lines_updated = new Long(result.getNrLinesUpdated());
Long lines_rejected = new Long(result.getNrLinesRejected());
Long lines_read = new Long(result.getNrLinesRead());
Long lines_written = new Long(result.getNrLinesWritten());
Long exit_status = new Long(result.getExitStatus());
Long files_retrieved = new Long(result.getNrFilesRetrieved());
Long nr = new Long(result.getEntryNr());
debug = "scope.put"; //$NON-NLS-1$
scope.put("errors", scope, errors); //$NON-NLS-1$
scope.put("lines_input", scope, lines_input); //$NON-NLS-1$
scope.put("lines_output", scope, lines_output); //$NON-NLS-1$
scope.put("lines_updated", scope, lines_updated); //$NON-NLS-1$
scope.put("lines_rejected", scope, lines_rejected); //$NON-NLS-1$
scope.put("lines_read", scope, lines_read); //$NON-NLS-1$
scope.put("lines_written", scope, lines_written); //$NON-NLS-1$
scope.put("files_retrieved", scope, files_retrieved); //$NON-NLS-1$
scope.put("exit_status", scope, exit_status); //$NON-NLS-1$
scope.put("nr", scope, nr); //$NON-NLS-1$
scope.put("is_windows", scope, Boolean.valueOf(Const.isWindows())); //$NON-NLS-1$
Object array[] = null;
if (result.getRows() != null) {
array = result.getRows().toArray();
}
scope.put("rows", scope, array); //$NON-NLS-1$
try {
debug = "cx.evaluateString()"; //$NON-NLS-1$
Object res = cx.evaluateString(scope, this.script, "<cmd>", 1, null); //$NON-NLS-1$
debug = "toBoolean"; //$NON-NLS-1$
boolean retval = Context.toBoolean(res);
// System.out.println(result.toString()+" + ["+this.script+"] --> "+retval);
result.setNrErrors(0);
return retval;
} catch (Exception e) {
result.setNrErrors(1);
log.logError(toString(), Messages.getString("JobEntryEval.CouldNotCompile", e.toString())); //$NON-NLS-1$
return false;
}
} catch (Exception e) {
result.setNrErrors(1);
log.logError(toString(), Messages.getString("JobEntryEval.ErrorEvaluating", debug, e.toString())); //$NON-NLS-1$
return false;
} finally {
Context.exit();
}
}
/**
* Execute this job entry and return the result.
* In this case it means, just set the result boolean in the Result class.
* @param prev_result The result of the previous execution
* @return The Result of the execution.
*/
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
prev_result.setResult(evaluate(prev_result));
return prev_result;
}
public boolean resetErrorsBeforeExecution() {
// we should be able to evaluate the errors in
// the previous jobentry.
return false;
}
public boolean evaluates() {
return true;
}
public boolean isUnconditional() {
return false;
}
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta)
{
andValidator().validate(this, "script", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
}
} | Fix for PDI-508 : Make it easier to evaluate variables etc in the "Javascript" JOB ENTRY
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@5880 5fb7f6ec-07c1-534a-b4ca-9155e429e800
| src/org/pentaho/di/job/entries/eval/JobEntryEval.java | Fix for PDI-508 : Make it easier to evaluate variables etc in the "Javascript" JOB ENTRY | <ide><path>rc/org/pentaho/di/job/entries/eval/JobEntryEval.java
<ide> /**
<ide> * Evaluate the result of the execution of previous job entry.
<ide> * @param result The result to evaulate.
<add> * @param prev_result the previous result
<add> * @param parentJob the parent job
<ide> * @return The boolean result of the evaluation script.
<ide> */
<del> public boolean evaluate(Result result) {
<add> public boolean evaluate(Result result, Job parentJob, Result prev_result) {
<ide> LogWriter log = LogWriter.getInstance();
<ide> Context cx;
<ide> Scriptable scope;
<ide> }
<ide>
<ide> scope.put("rows", scope, array); //$NON-NLS-1$
<add> scope.put("parent_job", scope, parentJob); //$NON-NLS-1$
<add> scope.put("previous_result", scope, prev_result); //$NON-NLS-1$
<ide>
<ide> try {
<ide> debug = "cx.evaluateString()"; //$NON-NLS-1$
<ide> * @return The Result of the execution.
<ide> */
<ide> public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
<del> prev_result.setResult(evaluate(prev_result));
<add> prev_result.setResult(evaluate(prev_result, parentJob, prev_result));
<ide>
<ide> return prev_result;
<ide> } |
|
Java | apache-2.0 | 923768afe2680eb82d90ece8c153f889f195ef05 | 0 | alex-charos/footie-predictions,alex-charos/footie-predictions,alex-charos/footie-predictions,alex-charos/footie-predictions | package com.oranje.web.rest;
import com.codahale.metrics.annotation.Timed;
import com.oranje.domain.Prediction;
import com.oranje.repository.PredictionRepository;
import com.oranje.web.rest.util.HeaderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing Prediction.
*/
@RestController
@RequestMapping("/api")
public class PredictionResource {
private final Logger log = LoggerFactory.getLogger(PredictionResource.class);
@Inject
private PredictionRepository predictionRepository;
/**
* POST /predictions -> Create a new prediction.
*/
@RequestMapping(value = "/predictions",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Prediction> createPrediction(@RequestBody Prediction prediction) throws URISyntaxException {
log.debug("REST request to save Prediction : {}", prediction);
if (prediction.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("prediction", "idexists", "A new prediction cannot already have an ID")).body(null);
}
Prediction result = predictionRepository.save(prediction);
return ResponseEntity.created(new URI("/api/predictions/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert("prediction", result.getId().toString()))
.body(result);
}
/**
* PUT /predictions -> Updates an existing prediction.
*/
@RequestMapping(value = "/predictions",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Prediction> updatePrediction(@RequestBody Prediction prediction, Principal principal) throws URISyntaxException {
log.debug("REST request to update Prediction : {}", prediction);
prediction.setUsername(principal.getName());
Prediction p = predictionRepository.findOneByUsername(prediction.getUsername());
if (p!=null) {
prediction.setId(p.getId());
}
if (prediction.getId() == null) {
return createPrediction(prediction);
}
Prediction result = predictionRepository.save(prediction);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert("prediction", prediction.getId().toString()))
.body(result);
}
/**
* GET /predictions -> get all the predictions.
*/
@RequestMapping(value = "/predictions",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<Prediction> getAllPredictions() {
log.debug("REST request to get all Predictions");
return predictionRepository.findAll();
}
/**
* GET /predictions/:username -> get the "username" prediction.
*/
@RequestMapping(value = "/predictions/{username}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public Prediction getPrediction(@PathVariable String username) {
log.debug("REST request to get Prediction : {}", username);
Prediction p = predictionRepository.findOneByUsername(username);
if (p==null) {
p = new Prediction();
}
return p;
}
/**
* DELETE /predictions/:id -> delete the "id" prediction.
*/
@RequestMapping(value = "/predictions/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> deletePrediction(@PathVariable String id) {
log.debug("REST request to delete Prediction : {}", id);
predictionRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("prediction", id.toString())).build();
}
}
| src/main/java/com/oranje/web/rest/PredictionResource.java | package com.oranje.web.rest;
import com.codahale.metrics.annotation.Timed;
import com.oranje.domain.Prediction;
import com.oranje.repository.PredictionRepository;
import com.oranje.web.rest.util.HeaderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing Prediction.
*/
@RestController
@RequestMapping("/api")
public class PredictionResource {
private final Logger log = LoggerFactory.getLogger(PredictionResource.class);
@Inject
private PredictionRepository predictionRepository;
/**
* POST /predictions -> Create a new prediction.
*/
@RequestMapping(value = "/predictions",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Prediction> createPrediction(@RequestBody Prediction prediction) throws URISyntaxException {
log.debug("REST request to save Prediction : {}", prediction);
if (prediction.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("prediction", "idexists", "A new prediction cannot already have an ID")).body(null);
}
Prediction result = predictionRepository.save(prediction);
return ResponseEntity.created(new URI("/api/predictions/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert("prediction", result.getId().toString()))
.body(result);
}
/**
* PUT /predictions -> Updates an existing prediction.
*/
@RequestMapping(value = "/predictions",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Prediction> updatePrediction(@RequestBody Prediction prediction, Principal principal) throws URISyntaxException {
log.debug("REST request to update Prediction : {}", prediction);
prediction.setUsername(principal.getName());
if (prediction.getId() == null) {
return createPrediction(prediction);
}
Prediction result = predictionRepository.save(prediction);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert("prediction", prediction.getId().toString()))
.body(result);
}
/**
* GET /predictions -> get all the predictions.
*/
@RequestMapping(value = "/predictions",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<Prediction> getAllPredictions() {
log.debug("REST request to get all Predictions");
return predictionRepository.findAll();
}
/**
* GET /predictions/:username -> get the "username" prediction.
*/
@RequestMapping(value = "/predictions/{username}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public Prediction getPrediction(@PathVariable String username) {
log.debug("REST request to get Prediction : {}", username);
Prediction p = predictionRepository.findOneByUsername(username);
if (p==null) {
p = new Prediction();
}
return p;
}
/**
* DELETE /predictions/:id -> delete the "id" prediction.
*/
@RequestMapping(value = "/predictions/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> deletePrediction(@PathVariable String id) {
log.debug("REST request to delete Prediction : {}", id);
predictionRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("prediction", id.toString())).build();
}
}
| retrieve prediction by user before saving
| src/main/java/com/oranje/web/rest/PredictionResource.java | retrieve prediction by user before saving | <ide><path>rc/main/java/com/oranje/web/rest/PredictionResource.java
<ide> public ResponseEntity<Prediction> updatePrediction(@RequestBody Prediction prediction, Principal principal) throws URISyntaxException {
<ide> log.debug("REST request to update Prediction : {}", prediction);
<ide> prediction.setUsername(principal.getName());
<add> Prediction p = predictionRepository.findOneByUsername(prediction.getUsername());
<add> if (p!=null) {
<add> prediction.setId(p.getId());
<add> }
<ide> if (prediction.getId() == null) {
<ide> return createPrediction(prediction);
<ide> } |
|
Java | bsd-3-clause | 6b3ce15b5173f85f0330e514c28adc0f9c2d6a42 | 0 | psygate/CivModCore,psygate/CivModCore | package vg.civcraft.mc.civmodcore.world.locations.chunkmeta;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.function.Supplier;
import java.util.logging.Level;
import org.bukkit.World;
import vg.civcraft.mc.civmodcore.CivModCorePlugin;
import vg.civcraft.mc.civmodcore.world.locations.chunkmeta.api.ChunkMetaViewTracker;
public class ChunkCoord extends XZWCoord {
/**
* When was this chunk last loaded in Minecraft as UNIX timestamp
*/
private long lastLoadingTime;
/**
* When was this chunk last unloaded in Minecraft as UNIX timestamp
*/
private long lastUnloadingTime;
/**
* Each ChunkMeta belongs to one plugin, they are identified by the plugin id
*/
private Map<Short, ChunkMeta<?>> chunkMetas;
/**
* Set to true once all data has been loaded for this chunk and stays true for
* the entire life time of this object
*/
private boolean isFullyLoaded;
private World world;
ChunkCoord(int x, int z, short worldID, World world) {
super(x, z, worldID);
this.world = world;
this.chunkMetas = new TreeMap<>();
this.isFullyLoaded = false;
this.lastLoadingTime = -1;
this.lastUnloadingTime = -1;
}
/**
* @return World this instance is in
*/
public World getWorld() {
return world;
}
void addChunkMeta(ChunkMeta<?> chunkMeta) {
chunkMeta.setWorld(this.world);
chunkMetas.put(chunkMeta.getPluginID(), chunkMeta);
}
/**
* Writes all data held by this instance to the database
*
*/
void fullyPersist() {
for (ChunkMeta<?> chunkMeta : chunkMetas.values()) {
persistChunkMeta(chunkMeta);
}
}
/**
* Writes all data held by this instance for one specific plugin to the database
* @param id Internal id of the plugin to save data for
*/
void persistPlugin(short id) {
ChunkMeta<?> chunkMeta = chunkMetas.get(id);
if (chunkMeta != null) {
persistChunkMeta(chunkMeta);
}
}
private static void persistChunkMeta(ChunkMeta<?> chunkMeta) {
switch (chunkMeta.getCacheState()) {
case NORMAL:
break;
case MODIFIED:
chunkMeta.update();
break;
case NEW:
chunkMeta.insert();
break;
case DELETED:
chunkMeta.delete();
}
chunkMeta.setCacheState(CacheState.NORMAL);
}
/**
* Forget all data which is not supposed to be held in memory permanently
*/
void deleteNonPersistentData() {
Iterator<Entry<Short,ChunkMeta<?>>> iter = chunkMetas.entrySet().iterator();
while(iter.hasNext()) {
ChunkMeta<?> meta = iter.next().getValue();
if (!meta.loadAlways()) {
iter.remove();
}
}
}
/**
* @return When was the minecraft chunk (the block data) this object is tied
* last loaded (UNIX timestamp)
*/
long getLastMCLoadingTime() {
return lastLoadingTime;
}
/**
* @return When was the minecraft chunk (the block data) this object is tied
* last unloaded (UNIX timestamp)
*/
long getLastMCUnloadingTime() {
return lastUnloadingTime;
}
ChunkMeta<?> getMeta(short pluginID, boolean alwaysLoaded) {
if (!alwaysLoaded && !isFullyLoaded) {
// check before taking monitor. This is fine, because the loaded flag will never
// switch from true to false,
// only the other way around
synchronized (this) {
while (!isFullyLoaded) {
try {
wait();
} catch (InterruptedException e) {
// whatever
e.printStackTrace();
}
}
}
}
return chunkMetas.get(pluginID);
}
boolean hasPermanentlyLoadedData() {
for (ChunkMeta<?> meta : chunkMetas.values()) {
if (meta.loadAlways()) {
return true;
}
}
return false;
}
/**
* Loads data for all plugins for this chunk
*/
void loadAll() {
synchronized (this) {
if (isFullyLoaded) {
return;
}
for (Entry<Short, Supplier<ChunkMeta<?>>> generator : ChunkMetaFactory.getInstance()
.getEmptyChunkFunctions()) {
ChunkMeta<?> chunk = generator.getValue().get();
chunk.setChunkCoord(this);
short pluginID = generator.getKey();
chunk.setPluginID(pluginID);
try {
chunk.populate();
} catch (Throwable e) {
// need to catch everything here, otherwise we block the main thread forever
// once it tries to read this
CivModCorePlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to load chunk data", e);
}
ChunkMetaViewTracker.getInstance().get(pluginID).postLoad(chunk);
addChunkMeta(chunk);
}
isFullyLoaded = true;
this.notifyAll();
}
}
/**
* Called when the minecraft chunk (the block data) this object is tied to gets
* loaded
*/
void minecraftChunkLoaded() {
boolean hasBeenLoadedBefore = this.lastLoadingTime != -1;
this.lastLoadingTime = System.currentTimeMillis();
if (hasBeenLoadedBefore) {
for(ChunkMeta <?> meta : chunkMetas.values()) {
meta.handleChunkCacheReuse();
}
}
}
public boolean isChunkLoaded() {
if (this.lastUnloadingTime <= 0) {
//being loaded rn, ignore
return true;
}
if (this.lastUnloadingTime > 0) {
return this.lastUnloadingTime < this.lastLoadingTime;
} else {
return true;
}
}
/**
* Called when the minecraft chunk (the block data) this object is tied to gets
* unloaded
*/
void minecraftChunkUnloaded() {
this.lastUnloadingTime = System.currentTimeMillis();
for(ChunkMeta <?> meta : chunkMetas.values()) {
meta.handleChunkUnload();
}
}
}
| paper/src/main/java/vg/civcraft/mc/civmodcore/world/locations/chunkmeta/ChunkCoord.java | package vg.civcraft.mc.civmodcore.world.locations.chunkmeta;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.function.Supplier;
import java.util.logging.Level;
import org.bukkit.World;
import vg.civcraft.mc.civmodcore.CivModCorePlugin;
import vg.civcraft.mc.civmodcore.world.locations.chunkmeta.api.ChunkMetaViewTracker;
public class ChunkCoord extends XZWCoord {
/**
* When was this chunk last loaded in Minecraft as UNIX timestamp
*/
private long lastLoadingTime;
/**
* When was this chunk last unloaded in Minecraft as UNIX timestamp
*/
private long lastUnloadingTime;
/**
* Each ChunkMeta belongs to one plugin, they are identified by the plugin id
*/
private Map<Short, ChunkMeta<?>> chunkMetas;
/**
* Set to true once all data has been loaded for this chunk and stays true for
* the entire life time of this object
*/
private boolean isFullyLoaded;
private World world;
ChunkCoord(int x, int z, short worldID, World world) {
super(x, z, worldID);
this.world = world;
this.chunkMetas = new TreeMap<>();
this.isFullyLoaded = false;
this.lastLoadingTime = -1;
this.lastUnloadingTime = -1;
}
/**
* @return World this instance is in
*/
public World getWorld() {
return world;
}
void addChunkMeta(ChunkMeta<?> chunkMeta) {
chunkMeta.setWorld(this.world);
chunkMetas.put(chunkMeta.getPluginID(), chunkMeta);
}
/**
* Writes all data held by this instance to the database
*
*/
void fullyPersist() {
for (ChunkMeta<?> chunkMeta : chunkMetas.values()) {
persistChunkMeta(chunkMeta);
}
}
/**
* Writes all data held by this instance for one specific plugin to the database
* @param id Internal id of the plugin to save data for
*/
void persistPlugin(short id) {
ChunkMeta<?> chunkMeta = chunkMetas.get(id);
if (chunkMeta != null) {
persistChunkMeta(chunkMeta);
}
}
private static void persistChunkMeta(ChunkMeta<?> chunkMeta) {
switch (chunkMeta.getCacheState()) {
case NORMAL:
break;
case MODIFIED:
chunkMeta.update();
break;
case NEW:
chunkMeta.insert();
break;
case DELETED:
chunkMeta.delete();
}
chunkMeta.setCacheState(CacheState.NORMAL);
}
/**
* Forget all data which is not supposed to be held in memory permanently
*/
void deleteNonPersistentData() {
Iterator<Entry<Short,ChunkMeta<?>>> iter = chunkMetas.entrySet().iterator();
while(iter.hasNext()) {
ChunkMeta<?> meta = iter.next().getValue();
if (!meta.loadAlways()) {
iter.remove();
}
}
}
/**
* @return When was the minecraft chunk (the block data) this object is tied
* last loaded (UNIX timestamp)
*/
long getLastMCLoadingTime() {
return lastLoadingTime;
}
/**
* @return When was the minecraft chunk (the block data) this object is tied
* last unloaded (UNIX timestamp)
*/
long getLastMCUnloadingTime() {
return lastUnloadingTime;
}
ChunkMeta<?> getMeta(short pluginID, boolean alwaysLoaded) {
if (!alwaysLoaded && !isFullyLoaded) {
// check before taking monitor. This is fine, because the loaded flag will never
// switch from true to false,
// only the other way around
synchronized (this) {
while (!isFullyLoaded) {
try {
wait();
} catch (InterruptedException e) {
// whatever
e.printStackTrace();
}
}
}
}
return chunkMetas.get(pluginID);
}
boolean hasPermanentlyLoadedData() {
for (ChunkMeta<?> meta : chunkMetas.values()) {
if (meta.loadAlways()) {
return true;
}
}
return false;
}
/**
* Loads data for all plugins for this chunk
*/
void loadAll() {
synchronized (this) {
if (isFullyLoaded) {
return;
}
for (Entry<Short, Supplier<ChunkMeta<?>>> generator : ChunkMetaFactory.getInstance()
.getEmptyChunkFunctions()) {
ChunkMeta<?> chunk = generator.getValue().get();
chunk.setChunkCoord(this);
short pluginID = generator.getKey();
chunk.setPluginID(pluginID);
try {
chunk.populate();
} catch (Throwable e) {
// need to catch everything here, otherwise we block the main thread forever
// once it tries to read this
CivModCorePlugin.getInstance().getLogger().log(Level.SEVERE, "Failed to load chunk data", e);
}
ChunkMetaViewTracker.getInstance().get(pluginID).postLoad(chunk);
addChunkMeta(chunk);
}
isFullyLoaded = true;
this.notifyAll();
}
}
/**
* Called when the minecraft chunk (the block data) this object is tied to gets
* loaded
*/
void minecraftChunkLoaded() {
boolean hasBeenLoadedBefore = this.lastLoadingTime != -1;
this.lastLoadingTime = System.currentTimeMillis();
if (hasBeenLoadedBefore) {
for(ChunkMeta <?> meta : chunkMetas.values()) {
meta.handleChunkCacheReuse();
}
}
}
public boolean isChunkLoaded() {
if (this.lastUnloadingTime <= 0) {
//being loaded rn, ignore
return false;
}
if (this.lastUnloadingTime > 0) {
return this.lastUnloadingTime < this.lastLoadingTime;
} else {
return true;
}
}
/**
* Called when the minecraft chunk (the block data) this object is tied to gets
* unloaded
*/
void minecraftChunkUnloaded() {
this.lastUnloadingTime = System.currentTimeMillis();
for(ChunkMeta <?> meta : chunkMetas.values()) {
meta.handleChunkUnload();
}
}
}
| Fix: reinforcements are not saving into the database each minute
| paper/src/main/java/vg/civcraft/mc/civmodcore/world/locations/chunkmeta/ChunkCoord.java | Fix: reinforcements are not saving into the database each minute | <ide><path>aper/src/main/java/vg/civcraft/mc/civmodcore/world/locations/chunkmeta/ChunkCoord.java
<ide> public boolean isChunkLoaded() {
<ide> if (this.lastUnloadingTime <= 0) {
<ide> //being loaded rn, ignore
<del> return false;
<add> return true;
<ide> }
<ide> if (this.lastUnloadingTime > 0) {
<ide> return this.lastUnloadingTime < this.lastLoadingTime; |
|
Java | apache-2.0 | ed8b086047942dd6a40af7995c9b8a8028573495 | 0 | sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt | /*
* JavaSMT is an API wrapper for a collection of SMT solvers.
* This file is part of JavaSMT.
*
* Copyright (C) 2007-2016 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sosy_lab.java_smt.utils;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableMultimap.copyOf;
import static com.google.common.collect.Maps.difference;
import com.google.auto.value.AutoValue;
import com.google.common.base.Verify;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Streams;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.CheckReturnValue;
import org.sosy_lab.common.UniqueIdGenerator;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormulaManager;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.NumeralFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.TraversalProcess;
/**
* UfElimination replaces UFs by fresh variables and adds constraints to enforce the functional
* consistency.
*/
public class UfElimination {
public static class Result {
private final BooleanFormula formula;
private final BooleanFormula constraints;
private final ImmutableMap<Formula, Formula> substitutions;
private final ImmutableMultimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufs;
public static Result empty(FormulaManager pFormulaManager) {
BooleanFormula trueFormula = pFormulaManager.getBooleanFormulaManager().makeTrue();
return new Result(trueFormula, trueFormula, ImmutableMap.of(), ImmutableMultimap.of());
}
Result(
BooleanFormula pFormula,
BooleanFormula pConstraints,
ImmutableMap<Formula, Formula> pSubstitutions,
ImmutableMultimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> pUfs) {
formula = checkNotNull(pFormula);
constraints = checkNotNull(pConstraints);
substitutions = checkNotNull(pSubstitutions);
ufs = checkNotNull(pUfs);
}
/** @return the new {@link Formula} without UFs */
public BooleanFormula getFormula() {
return formula;
}
/** @return the constraints enforcing the functional consistency. */
public BooleanFormula getConstraints() {
return constraints;
}
/** @return the substitution used to replace UFs */
public Map<Formula, Formula> getSubstitution() {
return substitutions;
}
/** @return all eliminated application of Ufs */
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> getUfs() {
return ufs;
}
}
private static final UniqueIdGenerator UNIQUE_ID_GENERATOR = new UniqueIdGenerator();
private static final String prefix = "__UF_fresh_";
private final BooleanFormulaManager bfmgr;
private final FormulaManager fmgr;
UfElimination(FormulaManager pFmgr) {
bfmgr = pFmgr.getBooleanFormulaManager();
fmgr = pFmgr;
}
/**
* Applies the Ackermann transformation to the given {@link Formula}. Quantified formulas are not
* supported.
*
* @param f the {@link Formula} to remove all Ufs from
* @return the new {@link Formula} and the substitution done during transformation
*/
public BooleanFormula eliminateUfs(BooleanFormula f) {
Result result = eliminateUfs(f, Result.empty(fmgr));
return fmgr.getBooleanFormulaManager().and(result.getFormula(), result.getConstraints());
}
/**
* Applies the Ackermann transformation to the given {@link Formula} with respect to the {@link
* Result} of another formula. Quantified formulas are not supported.
*
* @param pF the {@link Formula} to remove all Ufs from
* @param pOtherResult result of eliminating Ufs in another {@link BooleanFormula}
* @return the {@link Result} of the Ackermannization
*/
public Result eliminateUfs(BooleanFormula pF, Result pOtherResult) {
checkArgument(!isQuantified(pF));
BooleanFormula f;
if (!pOtherResult.getSubstitution().isEmpty()) {
f = fmgr.substitute(pF, pOtherResult.getSubstitution());
} else {
f = pF;
}
int depth = getNestingDepthOfUfs(f);
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufs = findUFs(f);
merge(ufs, pOtherResult);
ImmutableMap.Builder<Formula, Formula> substitutionsBuilder = ImmutableMap.builder();
List<BooleanFormula> extraConstraints = new ArrayList<>();
for (FunctionDeclaration<?> function : ufs.keySet()) {
List<UninterpretedFunctionApplication> applications = new ArrayList<>(ufs.get(function));
for (int idx1 = 0; idx1 < applications.size(); idx1++) {
UninterpretedFunctionApplication application = applications.get(idx1);
Formula uf = application.getFormula();
List<Formula> args = application.getArguments();
Formula substitution = application.getSubstitution();
substitutionsBuilder.put(uf, substitution);
for (int idx2 = idx1 + 1; idx2 < applications.size(); idx2++) {
UninterpretedFunctionApplication application2 = applications.get(idx2);
List<Formula> otherArgs = application2.getArguments();
/*
* Add constraints to enforce functional consistency.
*/
Verify.verify(args.size() == otherArgs.size());
BooleanFormula argumentsEquality =
Streams.zip(args.stream(), otherArgs.stream(), this::makeEqual)
.collect(bfmgr.toConjunction());
BooleanFormula functionEquality = makeEqual(substitution, application2.getSubstitution());
extraConstraints.add(bfmgr.implication(argumentsEquality, functionEquality));
}
}
}
// Get rid of UFs.
ImmutableMap<Formula, Formula> substitutions = substitutionsBuilder.build();
BooleanFormula formulaWithoutUFs = fmgr.substitute(f, substitutions);
// substitute all UFs in the additional constraints,
// required if UFs are arguments of UFs, e.g. uf(uf(1, 2), 2)
for (int i = 0; i < depth; i++) {
extraConstraints.replaceAll(c -> fmgr.substitute(c, substitutions));
}
Map<Formula, Formula> otherSubstitution =
difference(pOtherResult.getSubstitution(), substitutions).entriesOnlyOnLeft();
substitutionsBuilder.putAll(otherSubstitution);
ImmutableMap<Formula, Formula> allSubstitutions = substitutionsBuilder.build();
BooleanFormula constraints = bfmgr.and(extraConstraints);
return new Result(formulaWithoutUFs, constraints, allSubstitutions, copyOf(ufs));
}
private void merge(
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> pUfs,
Result pPreviousResult) {
for (Entry<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufInOtherFormula :
pPreviousResult.getUfs().entries()) {
if (pUfs.containsKey(ufInOtherFormula.getKey())) {
pUfs.put(ufInOtherFormula.getKey(), ufInOtherFormula.getValue());
}
}
}
@SuppressWarnings("unchecked")
@CheckReturnValue
private BooleanFormula makeEqual(Formula pLhs, Formula pRhs) {
BooleanFormula t;
if (pLhs instanceof BooleanFormula && pRhs instanceof BooleanFormula) {
t = bfmgr.equivalence((BooleanFormula) pLhs, (BooleanFormula) pRhs);
} else if (pLhs instanceof IntegerFormula && pRhs instanceof IntegerFormula) {
t = fmgr.getIntegerFormulaManager().equal((IntegerFormula) pLhs, (IntegerFormula) pRhs);
} else if (pLhs instanceof NumeralFormula && pRhs instanceof NumeralFormula) {
t = fmgr.getRationalFormulaManager().equal((NumeralFormula) pLhs, (NumeralFormula) pRhs);
} else if (pLhs instanceof BitvectorFormula) {
t = fmgr.getBitvectorFormulaManager().equal((BitvectorFormula) pLhs, (BitvectorFormula) pRhs);
} else if (pLhs instanceof FloatingPointFormula && pRhs instanceof FloatingPointFormula) {
FloatingPointFormulaManager fpfmgr = fmgr.getFloatingPointFormulaManager();
t = fpfmgr.equalWithFPSemantics((FloatingPointFormula) pLhs, (FloatingPointFormula) pRhs);
} else if (pLhs instanceof ArrayFormula<?, ?> && pRhs instanceof ArrayFormula<?, ?>) {
ArrayFormula<?, ?> lhs = (ArrayFormula<?, ?>) pLhs;
@SuppressWarnings("rawtypes")
ArrayFormula rhs = (ArrayFormula) pRhs;
t = fmgr.getArrayFormulaManager().equivalence(lhs, rhs);
} else {
throw new IllegalArgumentException("Not supported interface");
}
return t;
}
private boolean isQuantified(Formula f) {
AtomicBoolean result = new AtomicBoolean();
fmgr.visitRecursively(
f,
new DefaultFormulaVisitor<TraversalProcess>() {
@Override
protected TraversalProcess visitDefault(Formula pF) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitQuantifier(
BooleanFormula pF,
Quantifier pQ,
List<Formula> pBoundVariables,
BooleanFormula pBody) {
result.set(true);
return TraversalProcess.ABORT;
}
});
return result.get();
}
private int getNestingDepthOfUfs(Formula f) {
return fmgr.visit(
f,
new DefaultFormulaVisitor<Integer>() {
@Override
protected Integer visitDefault(Formula pF) {
return 0;
}
@Override
public Integer visitFunction(
Formula pF, List<Formula> pArgs, FunctionDeclaration<?> pFunctionDeclaration) {
int depthOfArgs = pArgs.stream().mapToInt(f -> fmgr.visit(f, this)).max().orElse(0);
// count only UFs
if (pFunctionDeclaration.getKind() == FunctionDeclarationKind.UF) {
return depthOfArgs + 1;
} else {
return depthOfArgs;
}
}
@Override
public Integer visitQuantifier(
BooleanFormula pF,
QuantifiedFormulaManager.Quantifier pQ,
List<Formula> pBoundVariables,
BooleanFormula pBody) {
return fmgr.visit(pBody, this);
}
});
}
private Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> findUFs(Formula f) {
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufs = HashMultimap.create();
fmgr.visitRecursively(
f,
new DefaultFormulaVisitor<TraversalProcess>() {
@Override
protected TraversalProcess visitDefault(Formula f) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitFunction(
Formula f, List<Formula> args, FunctionDeclaration<?> decl) {
if (decl.getKind() == FunctionDeclarationKind.UF) {
Formula substitution = freshUfReplaceVariable(decl.getType());
ufs.put(decl, UninterpretedFunctionApplication.create(f, args, substitution));
}
return TraversalProcess.CONTINUE;
}
});
return ufs;
}
private Formula freshUfReplaceVariable(FormulaType<?> pType) {
return fmgr.makeVariable(pType, prefix + UNIQUE_ID_GENERATOR.getFreshId());
}
@AutoValue
abstract static class UninterpretedFunctionApplication {
static UninterpretedFunctionApplication create(
Formula pF, List<Formula> pArguments, Formula pSubstitution) {
return new AutoValue_UfElimination_UninterpretedFunctionApplication(
pF, pArguments, pSubstitution);
}
abstract Formula getFormula();
abstract List<Formula> getArguments();
abstract Formula getSubstitution();
}
}
| src/org/sosy_lab/java_smt/utils/UfElimination.java | /*
* JavaSMT is an API wrapper for a collection of SMT solvers.
* This file is part of JavaSMT.
*
* Copyright (C) 2007-2016 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sosy_lab.java_smt.utils;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableMultimap.copyOf;
import static com.google.common.collect.Maps.difference;
import com.google.auto.value.AutoValue;
import com.google.common.base.Verify;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Streams;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.CheckReturnValue;
import org.sosy_lab.common.UniqueIdGenerator;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.BooleanFormulaManager;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormulaManager;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaManager;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.NumeralFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor;
import org.sosy_lab.java_smt.api.visitors.TraversalProcess;
/**
* UfElimination replaces UFs by fresh variables and adds constraints to enforce the functional
* consistency.
*/
public class UfElimination {
public static class Result {
private final BooleanFormula formula;
private final BooleanFormula constraints;
private final ImmutableMap<Formula, Formula> substitutions;
private final ImmutableMultimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufs;
public static Result empty(FormulaManager pFormulaManager) {
BooleanFormula trueFormula = pFormulaManager.getBooleanFormulaManager().makeTrue();
return new Result(trueFormula, trueFormula, ImmutableMap.of(), ImmutableMultimap.of());
}
Result(
BooleanFormula pFormula,
BooleanFormula pConstraints,
ImmutableMap<Formula, Formula> pSubstitutions,
ImmutableMultimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> pUfs) {
formula = checkNotNull(pFormula);
constraints = checkNotNull(pConstraints);
substitutions = checkNotNull(pSubstitutions);
ufs = checkNotNull(pUfs);
}
/** @return the new {@link Formula} without UFs */
public BooleanFormula getFormula() {
return formula;
}
/** @return the constraints enforcing the functional consistency. */
public BooleanFormula getConstraints() {
return constraints;
}
/** @return the substitution used to replace UFs */
public Map<Formula, Formula> getSubstitution() {
return substitutions;
}
/** @return all eliminated application of Ufs */
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> getUfs() {
return ufs;
}
}
private static final UniqueIdGenerator UNIQUE_ID_GENERATOR = new UniqueIdGenerator();
private static final String prefix = "__UF_fresh_";
private final BooleanFormulaManager bfmgr;
private final FormulaManager fmgr;
UfElimination(FormulaManager pFmgr) {
bfmgr = pFmgr.getBooleanFormulaManager();
fmgr = pFmgr;
}
/**
* Applies the Ackermann transformation to the given {@link Formula}. Quantified formulas are not
* supported.
*
* @param f the {@link Formula} to remove all Ufs from
* @return the new {@link Formula} and the substitution done during transformation
*/
public BooleanFormula eliminateUfs(BooleanFormula f) {
Result result = eliminateUfs(f, Result.empty(fmgr));
return fmgr.getBooleanFormulaManager().and(result.getFormula(), result.getConstraints());
}
/**
* Applies the Ackermann transformation to the given {@link Formula} with respect to the {@link
* Result} of another formula. Quantified formulas are not supported.
*
* @param pF the {@link Formula} to remove all Ufs from
* @param pOtherResult result of eliminating Ufs in another {@link BooleanFormula}
* @return the {@link Result} of the Ackermannization
*/
public Result eliminateUfs(BooleanFormula pF, Result pOtherResult) {
checkArgument(!isQuantified(pF));
BooleanFormula f;
if (!pOtherResult.getSubstitution().isEmpty()) {
f = fmgr.substitute(pF, pOtherResult.getSubstitution());
} else {
f = pF;
}
int depth = getNestingDepthOfUfs(f);
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufs = findUFs(f);
ufs = merge(ufs, pOtherResult);
ImmutableMap.Builder<Formula, Formula> substitutionsBuilder = ImmutableMap.builder();
List<BooleanFormula> extraConstraints = new ArrayList<>();
for (FunctionDeclaration<?> function : ufs.keySet()) {
List<UninterpretedFunctionApplication> applications = new ArrayList<>(ufs.get(function));
for (int idx1 = 0; idx1 < applications.size(); idx1++) {
UninterpretedFunctionApplication application = applications.get(idx1);
Formula uf = application.getFormula();
List<Formula> args = application.getArguments();
Formula substitution = application.getSubstitution();
substitutionsBuilder.put(uf, substitution);
for (int idx2 = idx1 + 1; idx2 < applications.size(); idx2++) {
UninterpretedFunctionApplication application2 = applications.get(idx2);
List<Formula> otherArgs = application2.getArguments();
/*
* Add constraints to enforce functional consistency.
*/
Verify.verify(args.size() == otherArgs.size());
BooleanFormula argumentsEquality =
Streams.zip(args.stream(), otherArgs.stream(), this::makeEqual)
.collect(bfmgr.toConjunction());
BooleanFormula functionEquality = makeEqual(substitution, application2.getSubstitution());
extraConstraints.add(bfmgr.implication(argumentsEquality, functionEquality));
}
}
}
// Get rid of UFs.
ImmutableMap<Formula, Formula> substitutions = substitutionsBuilder.build();
BooleanFormula formulaWithoutUFs = fmgr.substitute(f, substitutions);
// substitute all UFs in the additional constraints,
// required if UFs are arguments of UFs, e.g. uf(uf(1, 2), 2)
for (int i = 0; i < depth; i++) {
extraConstraints.replaceAll(c -> fmgr.substitute(c, substitutions));
}
Map<Formula, Formula> otherSubstitution =
difference(pOtherResult.getSubstitution(), substitutions).entriesOnlyOnLeft();
substitutionsBuilder.putAll(otherSubstitution);
ImmutableMap<Formula, Formula> allSubstitutions = substitutionsBuilder.build();
BooleanFormula constraints = bfmgr.and(extraConstraints);
return new Result(formulaWithoutUFs, constraints, allSubstitutions, copyOf(ufs));
}
private Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> merge(
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> pUfs,
Result pPreviousResult) {
for (Entry<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufInOtherFormula :
pPreviousResult.getUfs().entries()) {
if (pUfs.containsKey(ufInOtherFormula.getKey())) {
pUfs.put(ufInOtherFormula.getKey(), ufInOtherFormula.getValue());
}
}
return pUfs;
}
@SuppressWarnings("unchecked")
@CheckReturnValue
private BooleanFormula makeEqual(Formula pLhs, Formula pRhs) {
BooleanFormula t;
if (pLhs instanceof BooleanFormula && pRhs instanceof BooleanFormula) {
t = bfmgr.equivalence((BooleanFormula) pLhs, (BooleanFormula) pRhs);
} else if (pLhs instanceof IntegerFormula && pRhs instanceof IntegerFormula) {
t = fmgr.getIntegerFormulaManager().equal((IntegerFormula) pLhs, (IntegerFormula) pRhs);
} else if (pLhs instanceof NumeralFormula && pRhs instanceof NumeralFormula) {
t = fmgr.getRationalFormulaManager().equal((NumeralFormula) pLhs, (NumeralFormula) pRhs);
} else if (pLhs instanceof BitvectorFormula) {
t = fmgr.getBitvectorFormulaManager().equal((BitvectorFormula) pLhs, (BitvectorFormula) pRhs);
} else if (pLhs instanceof FloatingPointFormula && pRhs instanceof FloatingPointFormula) {
FloatingPointFormulaManager fpfmgr = fmgr.getFloatingPointFormulaManager();
t = fpfmgr.equalWithFPSemantics((FloatingPointFormula) pLhs, (FloatingPointFormula) pRhs);
} else if (pLhs instanceof ArrayFormula<?, ?> && pRhs instanceof ArrayFormula<?, ?>) {
ArrayFormula<?, ?> lhs = (ArrayFormula<?, ?>) pLhs;
@SuppressWarnings("rawtypes")
ArrayFormula rhs = (ArrayFormula) pRhs;
t = fmgr.getArrayFormulaManager().equivalence(lhs, rhs);
} else {
throw new IllegalArgumentException("Not supported interface");
}
return t;
}
private boolean isQuantified(Formula f) {
AtomicBoolean result = new AtomicBoolean();
fmgr.visitRecursively(
f,
new DefaultFormulaVisitor<TraversalProcess>() {
@Override
protected TraversalProcess visitDefault(Formula pF) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitQuantifier(
BooleanFormula pF,
Quantifier pQ,
List<Formula> pBoundVariables,
BooleanFormula pBody) {
result.set(true);
return TraversalProcess.ABORT;
}
});
return result.get();
}
private int getNestingDepthOfUfs(Formula f) {
return fmgr.visit(
f,
new DefaultFormulaVisitor<Integer>() {
@Override
protected Integer visitDefault(Formula pF) {
return 0;
}
@Override
public Integer visitFunction(
Formula pF, List<Formula> pArgs, FunctionDeclaration<?> pFunctionDeclaration) {
int depthOfArgs = pArgs.stream().mapToInt(f -> fmgr.visit(f, this)).max().orElse(0);
// count only UFs
if (pFunctionDeclaration.getKind() == FunctionDeclarationKind.UF) {
return depthOfArgs + 1;
} else {
return depthOfArgs;
}
}
@Override
public Integer visitQuantifier(
BooleanFormula pF,
QuantifiedFormulaManager.Quantifier pQ,
List<Formula> pBoundVariables,
BooleanFormula pBody) {
return fmgr.visit(pBody, this);
}
});
}
private Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> findUFs(Formula f) {
Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufs = HashMultimap.create();
fmgr.visitRecursively(
f,
new DefaultFormulaVisitor<TraversalProcess>() {
@Override
protected TraversalProcess visitDefault(Formula f) {
return TraversalProcess.CONTINUE;
}
@Override
public TraversalProcess visitFunction(
Formula f, List<Formula> args, FunctionDeclaration<?> decl) {
if (decl.getKind() == FunctionDeclarationKind.UF) {
Formula substitution = freshUfReplaceVariable(decl.getType());
ufs.put(decl, UninterpretedFunctionApplication.create(f, args, substitution));
}
return TraversalProcess.CONTINUE;
}
});
return ufs;
}
private Formula freshUfReplaceVariable(FormulaType<?> pType) {
return fmgr.makeVariable(pType, prefix + UNIQUE_ID_GENERATOR.getFreshId());
}
@AutoValue
abstract static class UninterpretedFunctionApplication {
static UninterpretedFunctionApplication create(
Formula pF, List<Formula> pArguments, Formula pSubstitution) {
return new AutoValue_UfElimination_UninterpretedFunctionApplication(
pF, pArguments, pSubstitution);
}
abstract Formula getFormula();
abstract List<Formula> getArguments();
abstract Formula getSubstitution();
}
}
| remove useless self-assignment.
| src/org/sosy_lab/java_smt/utils/UfElimination.java | remove useless self-assignment. | <ide><path>rc/org/sosy_lab/java_smt/utils/UfElimination.java
<ide>
<ide> int depth = getNestingDepthOfUfs(f);
<ide> Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufs = findUFs(f);
<del> ufs = merge(ufs, pOtherResult);
<add> merge(ufs, pOtherResult);
<ide>
<ide> ImmutableMap.Builder<Formula, Formula> substitutionsBuilder = ImmutableMap.builder();
<ide> List<BooleanFormula> extraConstraints = new ArrayList<>();
<ide> return new Result(formulaWithoutUFs, constraints, allSubstitutions, copyOf(ufs));
<ide> }
<ide>
<del> private Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> merge(
<add> private void merge(
<ide> Multimap<FunctionDeclaration<?>, UninterpretedFunctionApplication> pUfs,
<ide> Result pPreviousResult) {
<ide> for (Entry<FunctionDeclaration<?>, UninterpretedFunctionApplication> ufInOtherFormula :
<ide> pUfs.put(ufInOtherFormula.getKey(), ufInOtherFormula.getValue());
<ide> }
<ide> }
<del> return pUfs;
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked") |
|
JavaScript | mit | dbf9d58c37053caa7c78bc142194bc42492f6be1 | 0 | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | /* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable react/jsx-filename-extension */
import React, {useEffect} from 'react'
import UUID from '@sanity/uuid'
import {route, useRouterState} from 'part:@sanity/base/router'
import {parsePanesSegment, encodePanesSegment} from '../utils/parsePanesSegment'
import IntentResolver from '../components/IntentResolver'
import {EMPTY_PARAMS} from '../constants'
import DeskTool from './DeskTool'
function toState(pathSegment) {
return parsePanesSegment(decodeURIComponent(pathSegment))
}
function toPath(panes) {
return encodePanesSegment(panes)
}
function legacyEditParamsToState(params) {
try {
return JSON.parse(decodeURIComponent(params))
} catch (err) {
// eslint-disable-next-line no-console
console.warn('Failed to parse JSON parameters')
return {}
}
}
function legacyEditParamsToPath(params) {
return JSON.stringify(params)
}
const state = {activePanes: []}
function setActivePanes(panes) {
state.activePanes = panes
}
function DeskToolPaneStateSyncer(props) {
const {intent, params, payload} = useRouterState()
useEffect(() => {
// Set active panes to blank on mount and unmount
setActivePanes([])
return () => setActivePanes([])
}, [])
return intent ? (
<IntentResolver intent={intent} params={params} payload={payload} />
) : (
<DeskTool {...props} onPaneChange={setActivePanes} />
)
}
// eslint-disable-next-line complexity
function getIntentState(intentName, params, currentState, payload) {
const paneSegments = (currentState && currentState.panes) || []
const activePanes = state.activePanes || []
const editDocumentId = params.id || UUID()
const isTemplate = intentName === 'create' && params.template
// Loop through open panes and see if any of them can handle the intent
for (let i = activePanes.length - 1; i >= 0; i--) {
const pane = activePanes[i]
if (pane.canHandleIntent && pane.canHandleIntent(intentName, params, {pane, index: i})) {
const paneParams = isTemplate ? {template: params.template} : EMPTY_PARAMS
return {
panes: paneSegments
.slice(0, i)
.concat([[{id: editDocumentId, params: paneParams, payload}]])
}
}
}
return {intent: intentName, params, payload}
}
const strokeStyle = {
stroke: 'currentColor',
strokeWidth: 1.2,
vectorEffect: 'non-scaling-stroke'
}
// @todo: Move to @sanity/base
// eslint-disable-next-line react/no-multi-comp
function MasterDetailIcon() {
return (
<svg width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="4.5" y="5.5" width="16" height="14" style={strokeStyle} />
<path d="M10.5 5.5V19.5" style={strokeStyle} />
<path d="M6 8.5H9" style={strokeStyle} />
<path d="M13 8.5H18" style={strokeStyle} />
<path d="M6 11.5H9" style={strokeStyle} />
<path d="M6 14.5H9" style={strokeStyle} />
</svg>
)
}
export default {
router: route('/', [
// "Asynchronous intent resolving" route
route.intents('/intent'),
// Legacy fallback route, will be redirected to new format
route('/edit/:type/:editDocumentId', [
route({
path: '/:params',
transform: {params: {toState: legacyEditParamsToState, toPath: legacyEditParamsToPath}}
})
]),
// The regular path - when the intent can be resolved to a specific pane
route({
path: '/:panes',
// Legacy URLs, used to handle redirects
children: [route('/:action', route('/:legacyEditDocumentId'))],
transform: {
panes: {toState, toPath}
}
})
]),
canHandleIntent(intentName, params) {
return Boolean(
(intentName === 'edit' && params.id) ||
(intentName === 'create' && params.type) ||
(intentName === 'create' && params.template)
)
},
getIntentState,
title: 'Desk',
name: 'desk',
icon: MasterDetailIcon,
component: DeskToolPaneStateSyncer
}
| packages/@sanity/desk-tool/src/tool/index.js | /* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable react/jsx-filename-extension */
import React, {useEffect} from 'react'
import UUID from '@sanity/uuid'
import Icon from 'part:@sanity/base/view-column-icon'
import {route, useRouterState} from 'part:@sanity/base/router'
import {parsePanesSegment, encodePanesSegment} from '../utils/parsePanesSegment'
import IntentResolver from '../components/IntentResolver'
import {EMPTY_PARAMS} from '../constants'
import DeskTool from './DeskTool'
function toState(pathSegment) {
return parsePanesSegment(decodeURIComponent(pathSegment))
}
function toPath(panes) {
return encodePanesSegment(panes)
}
function legacyEditParamsToState(params) {
try {
return JSON.parse(decodeURIComponent(params))
} catch (err) {
// eslint-disable-next-line no-console
console.warn('Failed to parse JSON parameters')
return {}
}
}
function legacyEditParamsToPath(params) {
return JSON.stringify(params)
}
const state = {activePanes: []}
function setActivePanes(panes) {
state.activePanes = panes
}
function DeskToolPaneStateSyncer(props) {
const {intent, params, payload} = useRouterState()
useEffect(() => {
// Set active panes to blank on mount and unmount
setActivePanes([])
return () => setActivePanes([])
}, [])
return intent ? (
<IntentResolver intent={intent} params={params} payload={payload} />
) : (
<DeskTool {...props} onPaneChange={setActivePanes} />
)
}
// eslint-disable-next-line complexity
function getIntentState(intentName, params, currentState, payload) {
const paneSegments = (currentState && currentState.panes) || []
const activePanes = state.activePanes || []
const editDocumentId = params.id || UUID()
const isTemplate = intentName === 'create' && params.template
// Loop through open panes and see if any of them can handle the intent
for (let i = activePanes.length - 1; i >= 0; i--) {
const pane = activePanes[i]
if (pane.canHandleIntent && pane.canHandleIntent(intentName, params, {pane, index: i})) {
const paneParams = isTemplate ? {template: params.template} : EMPTY_PARAMS
return {
panes: paneSegments
.slice(0, i)
.concat([[{id: editDocumentId, params: paneParams, payload}]])
}
}
}
return {intent: intentName, params, payload}
}
export default {
router: route('/', [
// "Asynchronous intent resolving" route
route.intents('/intent'),
// Legacy fallback route, will be redirected to new format
route('/edit/:type/:editDocumentId', [
route({
path: '/:params',
transform: {params: {toState: legacyEditParamsToState, toPath: legacyEditParamsToPath}}
})
]),
// The regular path - when the intent can be resolved to a specific pane
route({
path: '/:panes',
// Legacy URLs, used to handle redirects
children: [route('/:action', route('/:legacyEditDocumentId'))],
transform: {
panes: {toState, toPath}
}
})
]),
canHandleIntent(intentName, params) {
return Boolean(
(intentName === 'edit' && params.id) ||
(intentName === 'create' && params.type) ||
(intentName === 'create' && params.template)
)
},
getIntentState,
title: 'Desk',
name: 'desk',
icon: Icon,
component: DeskToolPaneStateSyncer
}
| [desk-tool] Update Desk tool icon
| packages/@sanity/desk-tool/src/tool/index.js | [desk-tool] Update Desk tool icon | <ide><path>ackages/@sanity/desk-tool/src/tool/index.js
<ide>
<ide> import React, {useEffect} from 'react'
<ide> import UUID from '@sanity/uuid'
<del>import Icon from 'part:@sanity/base/view-column-icon'
<ide> import {route, useRouterState} from 'part:@sanity/base/router'
<ide> import {parsePanesSegment, encodePanesSegment} from '../utils/parsePanesSegment'
<ide> import IntentResolver from '../components/IntentResolver'
<ide> return {intent: intentName, params, payload}
<ide> }
<ide>
<add>const strokeStyle = {
<add> stroke: 'currentColor',
<add> strokeWidth: 1.2,
<add> vectorEffect: 'non-scaling-stroke'
<add>}
<add>
<add>// @todo: Move to @sanity/base
<add>// eslint-disable-next-line react/no-multi-comp
<add>function MasterDetailIcon() {
<add> return (
<add> <svg width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<add> <rect x="4.5" y="5.5" width="16" height="14" style={strokeStyle} />
<add> <path d="M10.5 5.5V19.5" style={strokeStyle} />
<add> <path d="M6 8.5H9" style={strokeStyle} />
<add> <path d="M13 8.5H18" style={strokeStyle} />
<add> <path d="M6 11.5H9" style={strokeStyle} />
<add> <path d="M6 14.5H9" style={strokeStyle} />
<add> </svg>
<add> )
<add>}
<add>
<ide> export default {
<ide> router: route('/', [
<ide> // "Asynchronous intent resolving" route
<ide> getIntentState,
<ide> title: 'Desk',
<ide> name: 'desk',
<del> icon: Icon,
<add> icon: MasterDetailIcon,
<ide> component: DeskToolPaneStateSyncer
<ide> } |
|
Java | apache-2.0 | abc15a361be3b702070c6b18ac499688bbd6f6a7 | 0 | OpenSkywalking/skywalking,apache/skywalking,apache/skywalking,ascrutae/sky-walking,apache/skywalking,ascrutae/sky-walking,ascrutae/sky-walking,apache/skywalking,apache/skywalking,apache/skywalking,OpenSkywalking/skywalking,apache/skywalking,ascrutae/sky-walking | /*
* 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.skywalking.oap.server.storage.plugin.elasticsearch.query;
import java.io.IOException;
import java.util.*;
import org.apache.skywalking.oap.server.core.query.entity.*;
import org.apache.skywalking.oap.server.core.register.*;
import org.apache.skywalking.oap.server.core.source.DetectPoint;
import org.apache.skywalking.oap.server.core.storage.query.IMetadataQueryDAO;
import org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient;
import org.apache.skywalking.oap.server.library.util.BooleanUtils;
import org.apache.skywalking.oap.server.library.util.StringUtils;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base.*;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
/**
* @author peng-yongsheng
*/
public class MetadataQueryEsDAO extends EsDAO implements IMetadataQueryDAO {
public MetadataQueryEsDAO(ElasticSearchClient client) {
super(client);
}
@Override public int numOfService(long startTimestamp, long endTimestamp) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
boolQueryBuilder.must().add(QueryBuilders.termQuery(ServiceInventory.IS_ADDRESS, BooleanUtils.FALSE));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(0);
SearchResponse response = getClient().search(ServiceInventory.MODEL_NAME, sourceBuilder);
return (int)response.getHits().getTotalHits();
}
@Override public int numOfEndpoint(long startTimestamp, long endTimestamp) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
boolQueryBuilder.must().add(QueryBuilders.termQuery(EndpointInventory.DETECT_POINT, DetectPoint.SERVER.ordinal()));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(0);
SearchResponse response = getClient().search(EndpointInventory.MODEL_NAME, sourceBuilder);
return (int)response.getHits().getTotalHits();
}
@Override public int numOfConjectural(long startTimestamp, long endTimestamp, int srcLayer) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
boolQueryBuilder.must().add(QueryBuilders.termQuery(NetworkAddressInventory.SRC_LAYER, srcLayer));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(0);
SearchResponse response = getClient().search(NetworkAddressInventory.MODEL_NAME, sourceBuilder);
return (int)response.getHits().getTotalHits();
}
@Override
public List<Service> getAllServices(long startTimestamp, long endTimestamp) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
boolQueryBuilder.must().add(QueryBuilders.termQuery(ServiceInventory.IS_ADDRESS, BooleanUtils.FALSE));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(100);
SearchResponse response = getClient().search(ServiceInventory.MODEL_NAME, sourceBuilder);
return buildServices(response);
}
@Override public List<Service> searchServices(long startTimestamp, long endTimestamp,
String keyword) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
String matchCName = MatchCNameBuilder.INSTANCE.build(ServiceInventory.NAME);
boolQueryBuilder.must().add(QueryBuilders.matchQuery(matchCName, keyword));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(100);
SearchResponse response = getClient().search(ServiceInventory.MODEL_NAME, sourceBuilder);
return buildServices(response);
}
@Override
public Service searchService(String serviceCode) throws IOException {
GetResponse response = getClient().get(ServiceInventory.MODEL_NAME, ServiceInventory.buildId(serviceCode));
if (response.isExists()) {
Service service = new Service();
service.setId(String.valueOf(response.getSource().get(ServiceInventory.SEQUENCE)));
service.setName((String)response.getSource().get(ServiceInventory.NAME));
return service;
} else {
return null;
}
}
@Override public List<Endpoint> searchEndpoint(String keyword, String serviceId,
int limit) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(QueryBuilders.termQuery(EndpointInventory.SERVICE_ID, serviceId));
String matchCName = MatchCNameBuilder.INSTANCE.build(EndpointInventory.NAME);
if (StringUtils.isNotEmpty(keyword)) {
boolQueryBuilder.must().add(QueryBuilders.matchQuery(matchCName, keyword));
}
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(limit);
SearchResponse response = getClient().search(EndpointInventory.MODEL_NAME, sourceBuilder);
List<Endpoint> endpoints = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
Endpoint endpoint = new Endpoint();
endpoint.setId(String.valueOf(sourceAsMap.get(EndpointInventory.SEQUENCE)));
endpoint.setName((String)sourceAsMap.get(EndpointInventory.NAME));
endpoints.add(endpoint);
}
return endpoints;
}
@Override public List<ServiceInstance> getServiceInstances(long startTimestamp, long endTimestamp,
String serviceId) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
boolQueryBuilder.must().add(QueryBuilders.termQuery(ServiceInstanceInventory.SERVICE_ID, serviceId));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(100);
SearchResponse response = getClient().search(ServiceInstanceInventory.MODEL_NAME, sourceBuilder);
List<ServiceInstance> serviceInstances = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
ServiceInstance serviceInstance = new ServiceInstance();
serviceInstance.setId(String.valueOf(sourceAsMap.get(ServiceInstanceInventory.SEQUENCE)));
serviceInstance.setName((String)sourceAsMap.get(ServiceInstanceInventory.NAME));
int languageId = ((Number)sourceAsMap.get(ServiceInstanceInventory.LANGUAGE)).intValue();
serviceInstance.setLanguage(LanguageTrans.INSTANCE.value(languageId));
serviceInstances.add(serviceInstance);
}
return serviceInstances;
}
private List<Service> buildServices(SearchResponse response) {
List<Service> services = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
Service service = new Service();
service.setId(String.valueOf(sourceAsMap.get(ServiceInventory.SEQUENCE)));
service.setName((String)sourceAsMap.get(ServiceInventory.NAME));
services.add(service);
}
return services;
}
private BoolQueryBuilder timeRangeQueryBuild(long startTimestamp, long endTimestamp) {
BoolQueryBuilder boolQuery1 = QueryBuilders.boolQuery();
boolQuery1.must().add(QueryBuilders.rangeQuery(RegisterSource.HEARTBEAT_TIME).gte(endTimestamp));
boolQuery1.must().add(QueryBuilders.rangeQuery(RegisterSource.REGISTER_TIME).lte(endTimestamp));
BoolQueryBuilder boolQuery2 = QueryBuilders.boolQuery();
boolQuery2.must().add(QueryBuilders.rangeQuery(RegisterSource.REGISTER_TIME).lte(endTimestamp));
boolQuery2.must().add(QueryBuilders.rangeQuery(RegisterSource.HEARTBEAT_TIME).gte(startTimestamp));
BoolQueryBuilder timeBoolQuery = QueryBuilders.boolQuery();
timeBoolQuery.should().add(boolQuery1);
timeBoolQuery.should().add(boolQuery2);
return timeBoolQuery;
}
}
| oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/query/MetadataQueryEsDAO.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.skywalking.oap.server.storage.plugin.elasticsearch.query;
import java.io.IOException;
import java.util.*;
import org.apache.skywalking.oap.server.core.query.entity.*;
import org.apache.skywalking.oap.server.core.register.*;
import org.apache.skywalking.oap.server.core.source.DetectPoint;
import org.apache.skywalking.oap.server.core.storage.query.IMetadataQueryDAO;
import org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient;
import org.apache.skywalking.oap.server.library.util.BooleanUtils;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base.*;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
/**
* @author peng-yongsheng
*/
public class MetadataQueryEsDAO extends EsDAO implements IMetadataQueryDAO {
public MetadataQueryEsDAO(ElasticSearchClient client) {
super(client);
}
@Override public int numOfService(long startTimestamp, long endTimestamp) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
boolQueryBuilder.must().add(QueryBuilders.termQuery(ServiceInventory.IS_ADDRESS, BooleanUtils.FALSE));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(0);
SearchResponse response = getClient().search(ServiceInventory.MODEL_NAME, sourceBuilder);
return (int)response.getHits().getTotalHits();
}
@Override public int numOfEndpoint(long startTimestamp, long endTimestamp) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
boolQueryBuilder.must().add(QueryBuilders.termQuery(EndpointInventory.DETECT_POINT, DetectPoint.SERVER.ordinal()));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(0);
SearchResponse response = getClient().search(EndpointInventory.MODEL_NAME, sourceBuilder);
return (int)response.getHits().getTotalHits();
}
@Override public int numOfConjectural(long startTimestamp, long endTimestamp, int srcLayer) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
boolQueryBuilder.must().add(QueryBuilders.termQuery(NetworkAddressInventory.SRC_LAYER, srcLayer));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(0);
SearchResponse response = getClient().search(NetworkAddressInventory.MODEL_NAME, sourceBuilder);
return (int)response.getHits().getTotalHits();
}
@Override
public List<Service> getAllServices(long startTimestamp, long endTimestamp) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
boolQueryBuilder.must().add(QueryBuilders.termQuery(ServiceInventory.IS_ADDRESS, BooleanUtils.FALSE));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(100);
SearchResponse response = getClient().search(ServiceInventory.MODEL_NAME, sourceBuilder);
return buildServices(response);
}
@Override public List<Service> searchServices(long startTimestamp, long endTimestamp,
String keyword) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
String matchCName = MatchCNameBuilder.INSTANCE.build(ServiceInventory.NAME);
boolQueryBuilder.must().add(QueryBuilders.matchQuery(matchCName, keyword));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(100);
SearchResponse response = getClient().search(ServiceInventory.MODEL_NAME, sourceBuilder);
return buildServices(response);
}
@Override
public Service searchService(String serviceCode) throws IOException {
GetResponse response = getClient().get(ServiceInventory.MODEL_NAME, ServiceInventory.buildId(serviceCode));
if (response.isExists()) {
Service service = new Service();
service.setId(String.valueOf(response.getSource().get(ServiceInventory.SEQUENCE)));
service.setName((String)response.getSource().get(ServiceInventory.NAME));
return service;
} else {
return null;
}
}
@Override public List<Endpoint> searchEndpoint(String keyword, String serviceId,
int limit) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(QueryBuilders.termQuery(EndpointInventory.SERVICE_ID, serviceId));
String matchCName = MatchCNameBuilder.INSTANCE.build(EndpointInventory.NAME);
boolQueryBuilder.must().add(QueryBuilders.matchQuery(matchCName, keyword));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(limit);
SearchResponse response = getClient().search(EndpointInventory.MODEL_NAME, sourceBuilder);
List<Endpoint> endpoints = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
Endpoint endpoint = new Endpoint();
endpoint.setId(String.valueOf(sourceAsMap.get(EndpointInventory.SEQUENCE)));
endpoint.setName((String)sourceAsMap.get(EndpointInventory.NAME));
endpoints.add(endpoint);
}
return endpoints;
}
@Override public List<ServiceInstance> getServiceInstances(long startTimestamp, long endTimestamp,
String serviceId) throws IOException {
SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must().add(timeRangeQueryBuild(startTimestamp, endTimestamp));
boolQueryBuilder.must().add(QueryBuilders.termQuery(ServiceInstanceInventory.SERVICE_ID, serviceId));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.size(100);
SearchResponse response = getClient().search(ServiceInstanceInventory.MODEL_NAME, sourceBuilder);
List<ServiceInstance> serviceInstances = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
ServiceInstance serviceInstance = new ServiceInstance();
serviceInstance.setId(String.valueOf(sourceAsMap.get(ServiceInstanceInventory.SEQUENCE)));
serviceInstance.setName((String)sourceAsMap.get(ServiceInstanceInventory.NAME));
int languageId = ((Number)sourceAsMap.get(ServiceInstanceInventory.LANGUAGE)).intValue();
serviceInstance.setLanguage(LanguageTrans.INSTANCE.value(languageId));
serviceInstances.add(serviceInstance);
}
return serviceInstances;
}
private List<Service> buildServices(SearchResponse response) {
List<Service> services = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
Service service = new Service();
service.setId(String.valueOf(sourceAsMap.get(ServiceInventory.SEQUENCE)));
service.setName((String)sourceAsMap.get(ServiceInventory.NAME));
services.add(service);
}
return services;
}
private BoolQueryBuilder timeRangeQueryBuild(long startTimestamp, long endTimestamp) {
BoolQueryBuilder boolQuery1 = QueryBuilders.boolQuery();
boolQuery1.must().add(QueryBuilders.rangeQuery(RegisterSource.HEARTBEAT_TIME).gte(endTimestamp));
boolQuery1.must().add(QueryBuilders.rangeQuery(RegisterSource.REGISTER_TIME).lte(endTimestamp));
BoolQueryBuilder boolQuery2 = QueryBuilders.boolQuery();
boolQuery2.must().add(QueryBuilders.rangeQuery(RegisterSource.REGISTER_TIME).lte(endTimestamp));
boolQuery2.must().add(QueryBuilders.rangeQuery(RegisterSource.HEARTBEAT_TIME).gte(startTimestamp));
BoolQueryBuilder timeBoolQuery = QueryBuilders.boolQuery();
timeBoolQuery.should().add(boolQuery1);
timeBoolQuery.should().add(boolQuery2);
return timeBoolQuery;
}
}
| Make sure can get endpoint list with empty keyword. (#1719)
| oap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/query/MetadataQueryEsDAO.java | Make sure can get endpoint list with empty keyword. (#1719) | <ide><path>ap-server/server-storage-plugin/storage-elasticsearch-plugin/src/main/java/org/apache/skywalking/oap/server/storage/plugin/elasticsearch/query/MetadataQueryEsDAO.java
<ide> import org.apache.skywalking.oap.server.core.storage.query.IMetadataQueryDAO;
<ide> import org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient;
<ide> import org.apache.skywalking.oap.server.library.util.BooleanUtils;
<add>import org.apache.skywalking.oap.server.library.util.StringUtils;
<ide> import org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base.*;
<ide> import org.elasticsearch.action.get.GetResponse;
<ide> import org.elasticsearch.action.search.SearchResponse;
<ide> boolQueryBuilder.must().add(QueryBuilders.termQuery(EndpointInventory.SERVICE_ID, serviceId));
<ide>
<ide> String matchCName = MatchCNameBuilder.INSTANCE.build(EndpointInventory.NAME);
<del> boolQueryBuilder.must().add(QueryBuilders.matchQuery(matchCName, keyword));
<add> if (StringUtils.isNotEmpty(keyword)) {
<add> boolQueryBuilder.must().add(QueryBuilders.matchQuery(matchCName, keyword));
<add> }
<ide>
<ide> sourceBuilder.query(boolQueryBuilder);
<ide> sourceBuilder.size(limit); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.