answer
stringlengths 17
10.2M
|
|---|
package net.java.sip.communicator.service.protocol;
import java.util.*;
import net.java.sip.communicator.service.media.*;
/**
* SecureEvent class extends EventObject
* This is the event type sent to current call sessions running
* when the user changes the secure state of communication in the GUI,
* to inform about the go secure / go clear change in communication.
* The event is actual triggered by a modification of the usingSRTP
* static secure communication status in the CallSessionImpl class.
*
* @author Emanuel Onica (eonica@info.uaic.ro)
*/
public class SecureEvent
extends EventObject
{
/**
* Constant value defining that the user triggered secure communication.
*/
public static final int SECURE_COMMUNICATION = 1;
/**
* Constant value defining that the user triggered unsecure communication.
*/
public static final int UNSECURE_COMMUNICATION = 2;
/**
* The actual event value - secure or unsecure, set at one of the above constants
*/
private final int eventID;
/**
* The source that triggered the event - local or remote peer
*/
private final OperationSetSecureTelephony.SecureStatusChangeSource source;
/**
* The event constructor
*
* @param callSession the event source - the call session for which this event applies
* @param eventID the change value - going secure or stopping secure communication
*/
public SecureEvent(CallSession callSession,
int eventID,
OperationSetSecureTelephony.SecureStatusChangeSource source)
{
super(callSession);
this.eventID = eventID;
this.source = source;
}
/**
* Retrieves the value of change - secure or unsecure
*
* @return the actual event value
*/
public int getEventID()
{
return eventID;
}
/**
* Retrieves the source that triggered the event
* (change by local peer or remote peer or reverting a previous change)
*/
public OperationSetSecureTelephony.SecureStatusChangeSource getSource()
{
return source;
}
}
|
package net.java.sip.communicator.util.swing;
import java.awt.*;
import javax.swing.JFileChooser;
import net.java.sip.communicator.util.*;
/**
* This class is the entry point for creating a file dialog regarding to the OS.
*
* If the current operating system is Apple Mac OS X, we create an AWT
* FileDialog (user interface is more practical under Mac OS than a
* JFileChooser), else, a Swing JFileChooser.
*
* @author Valentin Martinet
*/
public class GenericFileDialog
{
/**
* Creates a file dialog (AWT's FileDialog or Swing's JFileChooser) regarding to
* user's operating system.
*
* @param parent the parent Frame/JFrame of this dialog
* @param title dialog's title
* @return SipCommFileChooser an implementation of SipCommFileChooser
*/
public static SipCommFileChooser create(
Frame parent, String title, int fileOperation)
{
int operation = -1;
if(OSUtils.IS_MAC)
{
if(fileOperation == SipCommFileChooser.LOAD_FILE_OPERATION)
operation = FileDialog.LOAD;
else if(fileOperation == SipCommFileChooser.SAVE_FILE_OPERATION)
operation = FileDialog.SAVE;
else
try
{
throw new Exception("UnknownFileOperation");
}
catch (Exception e)
{
e.printStackTrace();
}
if (parent == null)
parent = new Frame();
return new SipCommFileDialogImpl(parent, title, operation);
}
else
{
if(fileOperation == SipCommFileChooser.LOAD_FILE_OPERATION)
operation = JFileChooser.OPEN_DIALOG;
else if(fileOperation == SipCommFileChooser.SAVE_FILE_OPERATION)
operation = JFileChooser.SAVE_DIALOG;
else
try
{
throw new Exception("UnknownFileOperation");
}
catch (Exception e)
{
e.printStackTrace();
}
return new SipCommFileChooserImpl(title, operation);
}
}
/**
* Creates a file dialog (AWT FileDialog or Swing JFileChooser) regarding to
* user's operating system.
*
* @param parent the parent Frame/JFrame of this dialog
* @param title dialog's title
* @param path start path of this dialog
* @return SipCommFileChooser an implementation of SipCommFileChooser
*/
public static SipCommFileChooser create(
Frame parent, String title, int fileOperation, String path)
{
SipCommFileChooser scfc =
GenericFileDialog.create(parent, title, fileOperation);
if(path != null)
scfc.setStartPath(path);
return scfc;
}
}
|
package org.anddev.andengine.engine.handler.timer;
import org.anddev.andengine.engine.handler.IUpdateHandler;
/**
* @author Nicolas Gramlich
* @since 16:23:58 - 12.03.2010
*/
public class TimerHandler implements IUpdateHandler {
// Constants
// Fields
private final float mTimerSeconds;
private float mSecondsPassed;
private boolean mCallbackTriggered = false;
private final ITimerCallback mTimerCallback;
private boolean mAutoReset;
// Constructors
public TimerHandler(final float pTimerSeconds, final ITimerCallback pTimerCallback) {
this(pTimerSeconds, false, pTimerCallback);
}
public TimerHandler(final float pTimerSeconds, final boolean pAutoReset, final ITimerCallback pTimerCallback) {
this.mTimerSeconds = pTimerSeconds;
this.mAutoReset = pAutoReset;
this.mTimerCallback = pTimerCallback;
}
// Getter & Setter
public boolean isAutoReset() {
return this.mAutoReset;
}
public void setAutoReset(final boolean pAutoReset) {
this.mAutoReset = pAutoReset;
}
// Methods for/from SuperClass/Interfaces
@Override
public void onUpdate(final float pSecondsElapsed) {
if(this.mAutoReset) {
this.mSecondsPassed += pSecondsElapsed;
while(this.mSecondsPassed >= this.mTimerSeconds) {
this.mSecondsPassed -= this.mTimerSeconds;
this.mTimerCallback.onTimePassed(this);
}
} else {
if(!this.mCallbackTriggered) {
this.mSecondsPassed += pSecondsElapsed;
if(this.mSecondsPassed >= this.mTimerSeconds) {
this.mCallbackTriggered = true;
this.mTimerCallback.onTimePassed(this);
}
}
}
}
@Override
public void reset() {
this.mCallbackTriggered = false;
this.mSecondsPassed = 0;
}
// Methods
// Inner and Anonymous Classes
}
|
package org.andengine.opengl.texture.compressed.pvr;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.andengine.opengl.texture.ITextureStateListener;
import org.andengine.opengl.texture.PixelFormat;
import org.andengine.opengl.texture.Texture;
import org.andengine.opengl.texture.TextureManager;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.compressed.pvr.pixelbufferstrategy.GreedyPVRTexturePixelBufferStrategy;
import org.andengine.opengl.texture.compressed.pvr.pixelbufferstrategy.IPVRTexturePixelBufferStrategy;
import org.andengine.opengl.texture.compressed.pvr.pixelbufferstrategy.IPVRTexturePixelBufferStrategy.IPVRTexturePixelBufferStrategyBufferManager;
import org.andengine.opengl.util.GLState;
import org.andengine.util.StreamUtils;
import org.andengine.util.adt.DataConstants;
import org.andengine.util.adt.array.ArrayUtils;
import org.andengine.util.adt.io.out.ByteBufferOutputStream;
import org.andengine.util.debug.Debug;
import org.andengine.util.math.MathUtils;
import android.opengl.GLES20;
public abstract class PVRTexture extends Texture {
// Constants
public static final int FLAG_MIPMAP = (1 << 8); // has mip map levels
public static final int FLAG_TWIDDLE = (1 << 9); // is twiddled
public static final int FLAG_BUMPMAP = (1 << 10); // has normals encoded for a bump map
public static final int FLAG_TILING = (1 << 11); // is bordered for tiled pvr
public static final int FLAG_CUBEMAP = (1 << 12); // is a cubemap/skybox
public static final int FLAG_FALSEMIPCOL = (1 << 13); // are there false colored MIP levels
public static final int FLAG_VOLUME = (1 << 14); // is this a volume texture
public static final int FLAG_ALPHA = (1 << 15); // v2.1 is there transparency info in the texture
public static final int FLAG_VERTICALFLIP = (1 << 16); // v2.1 is the texture vertically flipped
// Fields
private final PVRTextureHeader mPVRTextureHeader;
private final IPVRTexturePixelBufferStrategy mPVRTexturePixelBufferStrategy;
// Constructors
public PVRTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat) throws IllegalArgumentException, IOException {
this(pTextureManager, pPVRTextureFormat, new GreedyPVRTexturePixelBufferStrategy(), TextureOptions.DEFAULT, null);
}
public PVRTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final IPVRTexturePixelBufferStrategy pPVRTexturePixelBufferStrategy) throws IllegalArgumentException, IOException {
this(pTextureManager, pPVRTextureFormat, pPVRTexturePixelBufferStrategy, TextureOptions.DEFAULT, null);
}
public PVRTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException {
this(pTextureManager, pPVRTextureFormat, new GreedyPVRTexturePixelBufferStrategy(), TextureOptions.DEFAULT, pTextureStateListener);
}
public PVRTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final IPVRTexturePixelBufferStrategy pPVRTexturePixelBufferStrategy, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException {
this(pTextureManager, pPVRTextureFormat, pPVRTexturePixelBufferStrategy, TextureOptions.DEFAULT, pTextureStateListener);
}
public PVRTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException {
this(pTextureManager, pPVRTextureFormat, new GreedyPVRTexturePixelBufferStrategy(), pTextureOptions, null);
}
public PVRTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final IPVRTexturePixelBufferStrategy pPVRTexturePixelBufferStrategy, final TextureOptions pTextureOptions) throws IllegalArgumentException, IOException {
this(pTextureManager, pPVRTextureFormat, pPVRTexturePixelBufferStrategy, pTextureOptions, null);
}
public PVRTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException {
this(pTextureManager, pPVRTextureFormat, new GreedyPVRTexturePixelBufferStrategy(), pTextureOptions, pTextureStateListener);
}
public PVRTexture(final TextureManager pTextureManager, final PVRTextureFormat pPVRTextureFormat, final IPVRTexturePixelBufferStrategy pPVRTexturePixelBufferStrategy, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IllegalArgumentException, IOException {
super(pTextureManager, pPVRTextureFormat.getPixelFormat(), pTextureOptions, pTextureStateListener);
this.mPVRTexturePixelBufferStrategy = pPVRTexturePixelBufferStrategy;
InputStream inputStream = null;
try {
inputStream = this.getInputStream();
this.mPVRTextureHeader = new PVRTextureHeader(StreamUtils.streamToBytes(inputStream, PVRTextureHeader.SIZE));
} finally {
StreamUtils.close(inputStream);
}
if(this.mPVRTextureHeader.getPVRTextureFormat().getPixelFormat() != pPVRTextureFormat.getPixelFormat()) {
throw new IllegalArgumentException("Other PVRTextureFormat: '" + this.mPVRTextureHeader.getPVRTextureFormat().getPixelFormat() + "' found than expected: '" + pPVRTextureFormat.getPixelFormat() + "'.");
}
if(this.mPVRTextureHeader.getPVRTextureFormat().isCompressed()) { // TODO && ! GLHELPER_EXTENSION_PVRTC] ) {
throw new IllegalArgumentException("Invalid PVRTextureFormat: '" + this.mPVRTextureHeader.getPVRTextureFormat() + "'.");
}
this.mUpdateOnHardwareNeeded = true;
}
// Getter & Setter
@Override
public int getWidth() {
return this.mPVRTextureHeader.getWidth();
}
@Override
public int getHeight() {
return this.mPVRTextureHeader.getHeight();
}
public PVRTextureHeader getPVRTextureHeader() {
return this.mPVRTextureHeader;
}
// Methods for/from SuperClass/Interfaces
protected abstract InputStream onGetInputStream() throws IOException;
public InputStream getInputStream() throws IOException {
return this.onGetInputStream();
}
@Override
protected void writeTextureToHardware(final GLState pGLState) throws IOException {
final IPVRTexturePixelBufferStrategyBufferManager pvrTextureLoadStrategyManager = this.mPVRTexturePixelBufferStrategy.newPVRTexturePixelBufferStrategyManager(this);
int width = this.getWidth();
int height = this.getHeight();
final int dataLength = this.mPVRTextureHeader.getDataLength();
final int bytesPerPixel = this.mPVRTextureHeader.getBitsPerPixel() / DataConstants.BITS_PER_BYTE;
/* Adjust unpack alignment. */
GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1);
int currentLevel = 0;
int currentPixelDataOffset = 0;
while (currentPixelDataOffset < dataLength) {
if (currentLevel > 0 && (width != height || MathUtils.nextPowerOfTwo(width) != width)) {
Debug.w("Mipmap level '" + currentLevel + "' is not squared. Width: '" + width + "', height: '" + height + "'. Texture won't render correctly.");
}
final int currentPixelDataSize = height * width * bytesPerPixel;
/* Load the current level. */
this.mPVRTexturePixelBufferStrategy.loadPVRTextureData(pvrTextureLoadStrategyManager, width, height, bytesPerPixel, this.mPixelFormat, currentLevel, currentPixelDataOffset, currentPixelDataSize);
currentPixelDataOffset += currentPixelDataSize;
/* Prepare next mipmap level. */
width = Math.max(width / 2, 1);
height = Math.max(height / 2, 1);
currentLevel++;
}
/* Restore default unpack alignment. */
GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, GLState.GL_UNPACK_ALIGNMENT_DEFAULT);
}
// Methods
public ByteBuffer getPVRTextureBuffer() throws IOException {
final InputStream inputStream = this.getInputStream();
try {
final ByteBufferOutputStream os = new ByteBufferOutputStream(DataConstants.BYTES_PER_KILOBYTE, DataConstants.BYTES_PER_MEGABYTE / 2);
StreamUtils.copy(inputStream, os);
return os.toByteBuffer();
} finally {
StreamUtils.close(inputStream);
}
}
// Inner and Anonymous Classes
public static class PVRTextureHeader {
// Constants
static final byte[] MAGIC_IDENTIFIER = {
(byte)'P',
(byte)'V',
(byte)'R',
(byte)'!'
};
public static final int SIZE = 13 * DataConstants.BYTES_PER_INT;
private static final int FORMAT_FLAG_MASK = 0x0FF;
// Fields
private final ByteBuffer mDataByteBuffer;
private final PVRTextureFormat mPVRTextureFormat;
// Constructors
public PVRTextureHeader(final byte[] pData) {
this.mDataByteBuffer = ByteBuffer.wrap(pData);
this.mDataByteBuffer.rewind();
this.mDataByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
/* Check magic bytes. */
if(!ArrayUtils.equals(pData, 11 * DataConstants.BYTES_PER_INT, PVRTextureHeader.MAGIC_IDENTIFIER, 0, PVRTextureHeader.MAGIC_IDENTIFIER.length)) {
throw new IllegalArgumentException("Invalid " + this.getClass().getSimpleName() + "!");
}
this.mPVRTextureFormat = PVRTextureFormat.fromID(this.getFlags() & PVRTextureHeader.FORMAT_FLAG_MASK);
}
// Getter & Setter
public PVRTextureFormat getPVRTextureFormat() {
return this.mPVRTextureFormat;
}
public int headerLength() {
return this.mDataByteBuffer.getInt(0 * DataConstants.BYTES_PER_INT); // TODO Constants
}
public int getHeight() {
return this.mDataByteBuffer.getInt(1 * DataConstants.BYTES_PER_INT);
}
public int getWidth() {
return this.mDataByteBuffer.getInt(2 * DataConstants.BYTES_PER_INT);
}
public int getNumMipmaps() {
return this.mDataByteBuffer.getInt(3 * DataConstants.BYTES_PER_INT);
}
public int getFlags() {
return this.mDataByteBuffer.getInt(4 * DataConstants.BYTES_PER_INT);
}
public int getDataLength() {
return this.mDataByteBuffer.getInt(5 * DataConstants.BYTES_PER_INT);
}
public int getBitsPerPixel() {
return this.mDataByteBuffer.getInt(6 * DataConstants.BYTES_PER_INT);
}
public int getBitmaskRed() {
return this.mDataByteBuffer.getInt(7 * DataConstants.BYTES_PER_INT);
}
public int getBitmaskGreen() {
return this.mDataByteBuffer.getInt(8 * DataConstants.BYTES_PER_INT);
}
public int getBitmaskBlue() {
return this.mDataByteBuffer.getInt(9 * DataConstants.BYTES_PER_INT);
}
public int getBitmaskAlpha() {
return this.mDataByteBuffer.getInt(10 * DataConstants.BYTES_PER_INT);
}
public boolean hasAlpha() {
return this.getBitmaskAlpha() != 0;
}
public int getPVRTag() {
return this.mDataByteBuffer.getInt(11 * DataConstants.BYTES_PER_INT);
}
public int numSurfs() {
return this.mDataByteBuffer.getInt(12 * DataConstants.BYTES_PER_INT);
}
// Methods for/from SuperClass/Interfaces
// Methods
// Inner and Anonymous Classes
}
public static enum PVRTextureFormat {
// Elements
RGBA_4444(0x10, false, PixelFormat.RGBA_4444),
RGBA_5551(0x11, false, PixelFormat.RGBA_5551),
RGBA_8888(0x12, false, PixelFormat.RGBA_8888),
RGB_565(0x13, false, PixelFormat.RGB_565),
// RGB_555( 0x14, ...),
// RGB_888( 0x15, ...),
I_8(0x16, false, PixelFormat.I_8),
AI_88(0x17, false, PixelFormat.AI_88),
// PVRTC_2(0x18, GL10.GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, true, TextureFormat.???),
// PVRTC_4(0x19, GL10.GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, true, TextureFormat.???),
// BGRA_8888(0x1A, GL10.GL_RGBA, TextureFormat.???),
A_8(0x1B, false, PixelFormat.A_8);
// Constants
// Fields
private final int mID;
private final boolean mCompressed;
private final PixelFormat mPixelFormat;
// Constructors
private PVRTextureFormat(final int pID, final boolean pCompressed, final PixelFormat pPixelFormat) {
this.mID = pID;
this.mCompressed = pCompressed;
this.mPixelFormat = pPixelFormat;
}
public static PVRTextureFormat fromID(final int pID) {
final PVRTextureFormat[] pvrTextureFormats = PVRTextureFormat.values();
final int pvrTextureFormatCount = pvrTextureFormats.length;
for(int i = 0; i < pvrTextureFormatCount; i++) {
final PVRTextureFormat pvrTextureFormat = pvrTextureFormats[i];
if(pvrTextureFormat.mID == pID) {
return pvrTextureFormat;
}
}
throw new IllegalArgumentException("Unexpected " + PVRTextureFormat.class.getSimpleName() + "-ID: '" + pID + "'.");
}
public static PVRTextureFormat fromPixelFormat(final PixelFormat pPixelFormat) throws IllegalArgumentException {
switch(pPixelFormat) {
case RGBA_8888:
return PVRTextureFormat.RGBA_8888;
case RGBA_4444:
return PVRTextureFormat.RGBA_4444;
case RGB_565:
return PVRTextureFormat.RGB_565;
default:
throw new IllegalArgumentException("Unsupported " + PixelFormat.class.getName() + ": '" + pPixelFormat + "'.");
}
}
// Getter & Setter
public int getID() {
return this.mID;
}
public boolean isCompressed() {
return this.mCompressed;
}
public PixelFormat getPixelFormat() {
return this.mPixelFormat;
}
// Methods from SuperClass/Interfaces
// Methods
// Inner and Anonymous Classes
}
}
|
package org.concord.datagraph.engine;
import java.awt.BasicStroke;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.EventObject;
import java.util.Vector;
import org.concord.data.stream.DataStoreFunctionUtil;
import org.concord.framework.data.stream.DataStore;
import org.concord.framework.data.stream.WritableDataStore;
import org.concord.graph.engine.CoordinateSystem;
import org.concord.graph.engine.Cursorable;
import org.concord.graph.engine.MouseControllable;
import org.concord.graph.engine.MouseMotionReceiver;
import org.concord.graph.event.CursorListener;
import org.concord.graph.util.engine.DrawingObject;
/**
* ControllableDataGraphable
* Class name and description
*
* Date created: Oct 27, 2004
*
* @author imoncada<p>
*
*/
public class ControllableDataGraphable extends DataGraphable
implements MouseControllable, MouseMotionReceiver, Cursorable, DrawingObject
{
public final static int DRAGMODE_NONE = 0;
public final static int DRAGMODE_MOVEPOINTS = 1;
public final static int DRAGMODE_ADDPOINTS = 2;
public final static int DRAGMODE_ADDMULTIPLEPOINTS = 3;
public final static int DRAGMODE_REMOVEPOINTS = 4;
protected int dragMode = DRAGMODE_NONE;
public final static int LINETYPE_FREE = 0;
public final static int LINETYPE_FUNCTION = 1;
protected int lineType = LINETYPE_FUNCTION;//LINETYPE_FREE;
Rectangle2D boundingBox;
private boolean mouseClicked = false;
private int indexPointClicked = -1;
protected Point2D lastPointW;
protected Point2D lastLocation;
protected boolean drawAlwaysConnected = true;
//private float startDragX = Float.NaN;
//private float startDragY = Float.NaN;
private DataStoreFunctionUtil functionUtil;
protected int drawingMode = DrawingObject.DRAWING_DRAG_MODE_NONE;
protected boolean bNewShape;
protected Cursor cursor;
protected Vector cursorListeners;
protected boolean isMouseInside = false;
protected DrawingObject[] allSelectedDrawingObjects;
public ControllableDataGraphable()
{
super();
functionUtil = new DataStoreFunctionUtil();
lastPointW = new Point2D.Double();
cursorListeners = new Vector();
bNewShape = true;
allSelectedDrawingObjects = new DrawingObject[0];
}
/**
* @see org.concord.datagraph.engine.DataGraphable#setDataStore(org.concord.framework.data.stream.DataStore)
*/
public void setDataStore(DataStore dataStore)
{
//This Data Graphable only makes sense with a Writable Data Store!
if (dataStore != null && !(dataStore instanceof WritableDataStore)) {
throw new IllegalArgumentException("The Data Store "+dataStore+" is not Writable!");
}
super.setDataStore(dataStore);
functionUtil.setDataStore((WritableDataStore)dataStore);
}
/**
* @see org.concord.datagraph.engine.DataGraphable#setChannelX(int)
*/
public void setChannelX(int channelX)
{
super.setChannelX(channelX);
functionUtil.setXChannel(channelX);
}
/**
* @see org.concord.graph.engine.MouseControllable#mousePressed(java.awt.Point)
*/
public boolean mousePressed(Point p)
{
mouseClicked = true;
if (dragMode == DRAGMODE_NONE) return false;
if (indexPointClicked == -1 &&
(dragMode == DRAGMODE_MOVEPOINTS || dragMode == DRAGMODE_REMOVEPOINTS)) return false;
if (graphArea == null) return false;
CoordinateSystem cs = graphArea.getCoordinateSystem();
lastPointW = cs.transformToWorld(p);
if (dragMode == DRAGMODE_ADDPOINTS || dragMode == DRAGMODE_ADDMULTIPLEPOINTS){
//Add a new point
if (lineType == LINETYPE_FREE){
if (!drawAlwaysConnected){
addPoint(Float.NaN, Float.NaN);
}
addPoint(lastPointW.getX(), lastPointW.getY());
}
else if (lineType == LINETYPE_FUNCTION){
addPointOrder((float)lastPointW.getX(), (float)lastPointW.getY());
//startDragX = (float)pointClickedW.getX();
//startDragY = (float)pointClickedW.getY();
}
}
else if (dragMode == DRAGMODE_REMOVEPOINTS){
//Remove the current point
removeSampleAt(indexPointClicked);
}
for (int i = 0; i < allSelectedDrawingObjects.length; i++) {
if (!allSelectedDrawingObjects[i].equals(this)){
allSelectedDrawingObjects[i].setCurrentLocationAsOriginal();
}
}
return true;
}
/* (non-Javadoc)
* @see org.concord.graph.engine.MouseControllable#mouseDragged(java.awt.Point)
*/
public boolean mouseDragged(Point p)
{
//System.out.println("dragged "+p);
double startDragX = Float.NaN;
if (lastPointW != null){
startDragX = lastPointW.getX();
}
if (dragMode == DRAGMODE_NONE) return false;
if (indexPointClicked == -1 &&
(dragMode == DRAGMODE_MOVEPOINTS || dragMode == DRAGMODE_REMOVEPOINTS)) return false;
if (graphArea == null) return false;
CoordinateSystem cs = graphArea.getCoordinateSystem();
lastPointW = cs.transformToWorld(p);
if (dragMode == DRAGMODE_MOVEPOINTS){
//Drag the current point
setValueAt(indexPointClicked, 0, new Float(lastPointW.getX()));
setValueAt(indexPointClicked, 1, new Float(lastPointW.getY()));
}
else if (dragMode == DRAGMODE_ADDMULTIPLEPOINTS){
//Add a new point
if (lineType == LINETYPE_FREE){
addPoint(lastPointW.getX(), lastPointW.getY());
}
else if (lineType == LINETYPE_FUNCTION){
addPointOrderFromTo((float)lastPointW.getX(), (float)lastPointW.getY(), (float)startDragX);
//startDragX = (float)pW.getX();
//startDragY = (float)pW.getY();
}
}
else{
return false;
}
return true;
}
/* (non-Javadoc)
* @see org.concord.graph.engine.MouseControllable#mouseReleased(java.awt.Point)
*/
public boolean mouseReleased(Point p)
{
if (bNewShape){
Cursor standard = new Cursor(Cursor.DEFAULT_CURSOR);
setCursor(standard);
isMouseInside = false;
}
bNewShape = false;
indexPointClicked = -1;
mouseClicked = false;
lastLocation = lastPointW;
lastPointW = null;
//startDragX = Float.NaN;
return false;
}
/* (non-Javadoc)
* @see org.concord.graph.engine.MouseControllable#isMouseControlled()
*/
public boolean isMouseControlled()
{
return mouseClicked;
}
/* (non-Javadoc)
* @see org.concord.graph.engine.MouseSensitive#isPointInProximity(java.awt.Point)
*/
public boolean isPointInProximity(Point p)
{
indexPointClicked = -1;
if (graphArea == null) return false;
if (dragMode == DRAGMODE_NONE) return false;
if (dragMode == DRAGMODE_MOVEPOINTS || dragMode == DRAGMODE_REMOVEPOINTS){
return isPointAValue(p);
}
if (dragMode == DRAGMODE_ADDPOINTS || dragMode == DRAGMODE_ADDMULTIPLEPOINTS){
return true;
}
return false;
}
/**
* @param p
* @return
*/
protected boolean isPointAValue(Point p)
{
indexPointClicked = getIndexValueAtDisplay(p, 5);
if (indexPointClicked == -1){
return false;
}
else{
return true;
}
}
/**
* @return Returns the dragMode.
*/
public int getDragMode()
{
return dragMode;
}
public Rectangle2D getBoundingRectangle(){
return boundingBox;
}
/**
* @param dragMode The dragMode to set.
*/
public void setDragMode(int dragMode)
{
if (this.dragMode != dragMode){
this.dragMode = dragMode;
notifyChange();
}
}
/* Function stuff */
/**
* @param f
* @param g
*/
private void addPointOrder(float x, float y)
{
float value;
int i = functionUtil.findSamplePositionValue(x);
value = functionUtil.getXValueAt(i);
addPointOrder(x, y, i, value);
}
/**
* @param x
* @param i
* @param value
*/
private void addPointOrder(float x, float y, int i, float value)
{
//float v = functionUtil.getXValueAt(i);
//if (v != value){
// System.err.println("values different: "+value+" "+v);
if (i < getTotalNumSamples()){
if (value != x){
insertSampleAt(i);
}
for (int j=0; j < getTotalNumChannels(); j++){
if (j == channelX){
setValueAt(i, j, new Float(x));
//System.out.println("addPointOrder set "+getFloatVectorStr(channel));
}
else if (j == channelY){
setValueAt(i, j, new Float(y));
}
else{
setValueAt(i, j, null);
}
}
//notifyDataChanged();
}
else{
addPoint(x,y);
}
}
public void addPointOrderFromTo(float x, float y, float otherX)
{
if (otherX <= x){
addPointOrderFrom(x, y, otherX);
}
else{
addPointOrderTo(x, y, otherX);
}
}
public void addPointOrderFrom(float x, float y, float startX)
{
float value;
int i;
int startI;
int t;
int ti;
if (x < startX){
return;
}
if (x == startX){
addPointOrder(x, y);
return;
}
i = functionUtil.findSamplePositionValue(x);
t = getTotalNumSamples();
startI = functionUtil.findSamplePositionValue(startX);
value = functionUtil.getXValueAt(i);
//System.out.println("addPointOrderFrom("+x+" "+i+" "+startX+" "+startI+") in "+getFloatVectorStr((Vector)channelsValues.elementAt(0)));
//Removing all values from startI to i
ti = Math.min(i, t);
for (int ii = startI+1; ii < ti; ii++){
//for (int j=0; j < channelsValues.size(); j++){
// Vector channel = (Vector)channelsValues.elementAt(j);
// channel.remove(startI+1);
//The only problem with doing this is that removeSampleAt fires a removed event
removeSampleAt(startI+1);
i
}
//i = i - (ti - (startI +1));
//System.out.println("after removing, i:"+i+" "+getFloatVectorStr((Vector)channelsValues.elementAt(0)));
addPointOrder(x, y, i, value);
}
public void addPointOrderTo(float x, float y, float endX)
{
float value;
int i;
int endI;
int t;
int ti;
if (x > endX){
return;
}
if (x == endX){
addPointOrder(x, y);
return;
}
i = functionUtil.findSamplePositionValue(x);
t = getTotalNumSamples();
endI = functionUtil.findSamplePositionValue(endX);
value = functionUtil.getXValueAt(i);
//System.out.println("addPointOrderFrom("+x+" "+i+" "+endX+" "+endI+") in "+getFloatVectorStr((Vector)channelsValues.elementAt(0)));
//Removing all values from i to endI
ti = Math.min(endI, t);
for (int ii = i; ii < ti; ii++){
removeSampleAt(i);
}
//System.out.println("after removing, i:"+i+" "+getFloatVectorStr((Vector)channelsValues.elementAt(0)));
addPointOrder(x, y, i, value);
}
/**
* @return Returns the lineType.
*/
public int getLineType()
{
return lineType;
}
/**
* @param lineType The lineType to set.
*/
public void setLineType(int lineType)
{
this.lineType = lineType;
}
/**
* @see org.concord.graph.util.engine.DrawingObject#erase(java.awt.geom.Rectangle2D)
*/
public boolean erase(Rectangle2D rectDisplay)
{
throw new UnsupportedOperationException("erase is not supported by ControllableDataGraphable yet");
}
/**
* @see org.concord.graph.util.engine.DrawingObject#setDrawingDragMode(int)
*/
public boolean setDrawingDragMode(int mode)
{
drawingMode = mode;
if (mode == DrawingObject.DRAWING_DRAG_MODE_NONE){
setDragMode(DRAGMODE_NONE);
return true;
}
else if (mode == DrawingObject.DRAWING_DRAG_MODE_DRAW){
setDragMode(DRAGMODE_ADDMULTIPLEPOINTS);
return true;
}
else if (mode == DrawingObject.DRAWING_DRAG_MODE_MOVE){
setDragMode(DRAGMODE_NONE);
return true;
}
//return false;
throw new UnsupportedOperationException("setDrawingDragMode("+mode+")is not supported by ControllableDataGraphable yet");
}
/**
* @see org.concord.graph.util.engine.DrawingObject#getDrawingDragMode()
*/
public int getDrawingDragMode()
{
return drawingMode;
}
/**
* @return Returns the drawAlwaysConnected.
*/
public boolean isDrawAlwaysConnected()
{
return drawAlwaysConnected;
}
/**
* @param drawAlwaysConnected The drawAlwaysConnected to set.
*/
public void setDrawAlwaysConnected(boolean drawAlwaysConnected)
{
this.drawAlwaysConnected = drawAlwaysConnected;
}
/**
* @see org.concord.graph.util.engine.DrawingObject#isResizeEnabled()
*/
public boolean isResizeEnabled()
{
return false;
}
public boolean isMouseReceiving() {
return isMouseInside;
}
public boolean mouseEntered(Point p) {
isMouseInside = true;
return false;
}
public boolean mouseExited(Point p) {
isMouseInside = false;
return false;
}
public boolean mouseMoved(Point p) {
if (bNewShape)
return false;
if (isMouseInside){
Cursor move = new Cursor(Cursor.HAND_CURSOR);
setCursor(move);
} else {
Cursor standard = new Cursor(Cursor.DEFAULT_CURSOR);
setCursor(standard);
}
return false;
}
public boolean isInsideBox(Rectangle2D box) {
Stroke perimeter = new BasicStroke(1);
Shape outline = perimeter.createStrokedShape(path);
if (box.getHeight() < 1 || box.getWidth() < 1){
// make a slightly larger rectangle
double iniX = box.getMinX()-1;
double iniY = box.getMinY()-1;
double w = (box.getMaxX() - iniX) + 2;
double h = (box.getMaxY() - iniY) + 2;
return outline.intersects(iniX, iniY, w, h);
}
return outline.intersects(box);
}
/**
* @see org.concord.graph.engine.Cursorable#setCursor(java.awt.Cursor)
*/
public void setCursor(Cursor cursor) {
this.cursor = cursor;
notifyCursorChange();
}
protected void notifyCursorChange() {
EventObject e = new EventObject(this);
for (int i = 0; i < cursorListeners.size(); i++) {
CursorListener l = (CursorListener) cursorListeners.elementAt(i);
l.cursorChanged(e);
}
}
/**
* @see org.concord.graph.engine.Cursorable#getCursor()
*/
public Cursor getCursor() {
return cursor;
}
/**
* @see org.concord.graph.engine.Cursorable#addCursorListener(org.concord.graph.event.CursorListener)
*/
public void addCursorListener(CursorListener l) {
if (!cursorListeners.contains(l)) {
cursorListeners.add(l);
}
}
/**
* @see org.concord.graph.engine.Cursorable#removeCursorListener(org.concord.graph.event.CursorListener)
*/
public void removeCursorListener(CursorListener l) {
cursorListeners.remove(l);
}
public void moveInRelation(Point2D start, Point2D end) {
// TODO Auto-generated method stub
}
public void setAllSelectedDrawingObjects(DrawingObject[] objects) {
allSelectedDrawingObjects = objects;
}
public void setCurrentLocationAsOriginal() {
// System.out.println("this = "+this+", setting: lastPointW = "+lastLocation);
// lastPointW =
}
}
|
/**
* @author <a href="mailto:novotny@gridsphere.org">Jason Novotny</a>
* @version $Id: ActionLinkBean.java 4694 2006-03-29 20:28:46Z novotny $
*/
package org.gridsphere.provider.portletui.beans;
import java.util.ArrayList;
import java.util.List;
/**
* An <code>ActionLinkBean</code> is a visual bean that represents a hyperlink containing a portlet action
*/
public class ActionLinkBean extends ActionBean implements TagBean {
protected String style = "none";
protected List<TagBean> beans = new ArrayList<TagBean>();
/**
* Constructs a default action link bean
*/
public ActionLinkBean() {
}
/**
* Constructs an action link bean from a portlet request and supplied bean identifier
*
* @param beanId the bean id used to reference this ActionLinkBean
*/
public ActionLinkBean(String beanId) {
this.beanId = beanId;
}
/**
* Returns the style of the text: Available styles are
* <ul>
* <li>nostyle - plain text</li>
* <li>error - error text</li>
* <li>info - default info text</li>
* <li>status - status text</li>
* <li>alert - alert text</li>
* <li>success - success text</li>
*
* @return the text style
*/
public String getStyle() {
return style;
}
/**
* Sets the style of the text: Available styles are
* <ul>
* <li>error</li>
* <li>info</li>
* <li>status</li>
* <li>alert</li>
* <li>success</li>
*
* @param style the text style
*/
public void setStyle(String style) {
this.style = style;
}
/**
* Gets the beans to be rendered before the text in the ActionLink.
*
* @return TagBean
*/
public List<TagBean> getTagBeans() {
return beans;
}
/**
* Sets beans to be rendered before the text in the ActionLink.
*
* @param beans Bean to be rendered
*/
public void setTagBeans(List<TagBean> beans) {
this.beans = beans;
}
public String toStartString() {
return "";
}
public String toEndString() {
// now do the string rendering
action = this.portletURI.toString();
if (anchor != null) action += "#" + anchor;
//String hlink = "<a href=\"" + action + "\"" + " onClick=\"this.href='" + action + "&JavaScript=enabled'\"/>" + value + "</a>";
if (style.equalsIgnoreCase("error") || (style.equalsIgnoreCase("err"))) {
this.cssClass = MessageStyle.MSG_ERROR;
} else if (style.equalsIgnoreCase("status")) {
this.cssClass = MessageStyle.MSG_STATUS;
} else if (style.equalsIgnoreCase("info")) {
this.cssClass = MessageStyle.MSG_INFO;
} else if (style.equalsIgnoreCase("alert")) {
this.cssClass = MessageStyle.MSG_ALERT;
} else if (style.equalsIgnoreCase("success")) {
this.cssClass = MessageStyle.MSG_SUCCESS;
} else if (style.equalsIgnoreCase(MessageStyle.MSG_BOLD)) {
this.addCssStyle("font-weight: bold;");
} else if (style.equalsIgnoreCase(MessageStyle.MSG_ITALIC)) {
this.addCssStyle("font-weight: italic;");
} else if (style.equalsIgnoreCase(MessageStyle.MSG_UNDERLINE)) {
this.addCssStyle("font-weight: underline;");
}
StringBuffer sb = new StringBuffer();
sb.append("<a");
if (name != null) sb.append(" name=\"").append(name).append("\"");
if (id != null) sb.append(" id=\"").append(id).append("\" ");
if (useAjax) action = "
sb.append(" href=\"").append(action).append("\"");
sb.append(getFormattedCss());
if (onClick != null) sb.append(" onclick=\"").append(onClick).append("\"");
if (onMouseOut != null) sb.append(" onMouseOut=\"").append(onMouseOut).append("\"");
if (onMouseOver != null) sb.append(" onMouseOver=\"").append(onMouseOver).append("\"");
sb.append(">");
for (TagBean bean : beans) {
sb.append(bean.toStartString());
sb.append(bean.toEndString());
}
sb.append(value).append("</a>");
return sb.toString();
}
}
|
package org.helioviewer.jhv.renderable.gui;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
import org.helioviewer.jhv.JHVDirectory;
import org.helioviewer.jhv.JHVGlobals;
import org.helioviewer.jhv.base.FileUtils;
import org.helioviewer.jhv.base.JSONUtils;
import org.helioviewer.jhv.base.time.JHVDate;
import org.helioviewer.jhv.camera.Camera;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.display.Viewport;
import org.helioviewer.jhv.layers.ImageLayer;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.renderable.components.RenderableMiniview;
import org.helioviewer.jhv.threads.JHVWorker;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.jogamp.opengl.GL2;
@SuppressWarnings("serial")
public class RenderableContainer extends AbstractTableModel implements Reorderable {
private ArrayList<Renderable> renderables = new ArrayList<>();
private ArrayList<Renderable> newRenderables = new ArrayList<>();
private final ArrayList<Renderable> removedRenderables = new ArrayList<>();
public void addBeforeRenderable(Renderable renderable) {
int lastImagelayerIndex = -1;
int size = renderables.size();
for (int i = 0; i < size; i++) {
if (renderables.get(i) instanceof ImageLayer) {
lastImagelayerIndex = i;
}
}
renderables.add(lastImagelayerIndex + 1, renderable);
newRenderables.add(renderable);
int row = lastImagelayerIndex + 1;
fireTableRowsInserted(row, row);
}
public void addRenderable(Renderable renderable) {
renderables.add(renderable);
newRenderables.add(renderable);
int row = renderables.size() - 1;
fireTableRowsInserted(row, row);
Displayer.display(); // e.g., PFSS renderable
}
public void removeRenderable(Renderable renderable) {
renderables.remove(renderable);
removedRenderables.add(renderable);
// refreshTable(); display() will take care
Displayer.display();
}
public void prerender(GL2 gl) {
int count = removeRenderables(gl);
initRenderables(gl);
if (count > 0)
refreshTable();
for (Renderable renderable : renderables) {
renderable.prerender(gl);
}
}
public void render(Camera camera, Viewport vp, GL2 gl) {
for (Renderable renderable : renderables) {
renderable.render(camera, vp, gl);
}
}
public void renderScale(Camera camera, Viewport vp, GL2 gl) {
for (Renderable renderable : renderables) {
renderable.renderScale(camera, vp, gl);
}
}
public void renderFloat(Camera camera, Viewport vp, GL2 gl) {
for (Renderable renderable : renderables) {
renderable.renderFloat(camera, vp, gl);
}
}
public void renderFullFloat(Camera camera, Viewport vp, GL2 gl) {
for (Renderable renderable : renderables) {
renderable.renderFullFloat(camera, vp, gl);
}
}
public void renderMiniview(Camera camera, Viewport miniview, GL2 gl) {
RenderableMiniview.renderBackground(camera, miniview, gl);
for (Renderable renderable : renderables) {
renderable.renderMiniview(camera, miniview, gl);
}
}
private void initRenderables(GL2 gl) {
for (Renderable renderable : newRenderables) {
renderable.init(gl);
}
newRenderables.clear();
}
private int removeRenderables(GL2 gl) {
int count = removedRenderables.size();
for (Renderable renderable : removedRenderables) {
renderable.remove(gl);
}
removedRenderables.clear();
return count;
}
private void insertRow(int row, Renderable rowData) {
if (row > renderables.size()) {
renderables.add(rowData);
} else {
renderables.add(row, rowData);
}
}
@Override
public void reorder(int fromIndex, int toIndex) {
if (toIndex > renderables.size()) {
return;
}
Renderable toMove = renderables.get(fromIndex);
Renderable moveTo = renderables.get(Math.max(0, toIndex - 1));
if (!(toMove instanceof ImageLayer) || !(moveTo instanceof ImageLayer)) {
return;
}
renderables.remove(fromIndex);
if (fromIndex < toIndex) {
insertRow(toIndex - 1, toMove);
} else {
insertRow(toIndex, toMove);
}
refreshTable();
if (Displayer.multiview) {
Layers.arrangeMultiView(true);
}
}
@Override
public int getRowCount() {
return renderables.size();
}
@Override
public int getColumnCount() {
return RenderableContainerPanel.NUMBER_COLUMNS;
}
@Override
public Object getValueAt(int row, int col) {
try {
return renderables.get(row);
} catch (Exception e) {
return null;
}
}
public void refreshTable() {
fireTableDataChanged();
}
public void updateCell(int row, int col) {
if (row >= 0) // negative row breaks model
fireTableCellUpdated(row, col);
}
public void fireTimeUpdated(Renderable renderable) {
updateCell(renderables.indexOf(renderable), RenderableContainerPanel.TIME_COL);
}
public void dispose(GL2 gl) {
for (Renderable renderable : renderables) {
renderable.dispose(gl);
}
newRenderables = renderables;
renderables = new ArrayList<>();
}
public void saveCurrentScene() {
JSONObject main = new JSONObject();
main.put("time", Layers.getLastUpdatedTimestamp());
JSONArray ja = new JSONArray();
for (Renderable renderable : renderables) {
JSONObject jo = new JSONObject();
JSONObject dataObject = new JSONObject();
jo.put("data", dataObject);
jo.put("className", renderable.getClass().getName());
renderable.serialize(dataObject);
ja.put(jo);
JSONArray va = new JSONArray();
renderable.serializeVisibility(va);
jo.put("visibility", va);
if (renderable instanceof ImageLayer && ((ImageLayer) renderable).isActiveImageLayer())
jo.put("master", true);
}
main.put("renderables", ja);
try (OutputStream os = FileUtils.newBufferedOutputStream(new File(JHVDirectory.HOME.getPath() + "test.json"))) {
final PrintStream printStream = new PrintStream(os);
printStream.print(main.toString());
printStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void loadScene() {
ArrayList<Renderable> newlist = new ArrayList<Renderable>();
Renderable masterRenderable = null;
try (InputStream in = FileUtils.newBufferedInputStream(new File(JHVDirectory.HOME.getPath() + "test.json"))) {
JSONObject data = JSONUtils.getJSONStream(in);
JSONArray rja = data.getJSONArray("renderables");
for (Object o : rja) {
if (o instanceof JSONObject) {
JSONObject jo = (JSONObject) o;
try {
JSONObject jdata = jo.optJSONObject("data");
if (jdata == null)
continue;
Class<?> c = Class.forName(jo.optString("className"));
Constructor<?> cons = c.getConstructor(JSONObject.class);
Object _renderable = cons.newInstance(jdata);
if (_renderable instanceof Renderable) {
Renderable renderable = (Renderable) _renderable;
newlist.add(renderable);
JSONArray va = jo.optJSONArray("visibility");
if (va == null)
va = new JSONArray(new double[] { 1, 0, 0, 0 });
renderable.deserializeVisibility(va);
if (jo.optBoolean("master", false))
masterRenderable = renderable;
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | JSONException |
ClassNotFoundException | NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
}
}
removedRenderables.addAll(renderables);
renderables = new ArrayList<>();
LoadState loadStateTask = new LoadState(newlist, masterRenderable, JHVDate.optional(data.optString("time")));
JHVGlobals.getExecutorService().execute(loadStateTask);
} catch (IOException e1) {
e1.printStackTrace();
}
}
class LoadState extends JHVWorker<Integer, Void> {
private ArrayList<Renderable> newlist;
private Renderable master;
private JHVDate time;
public LoadState(ArrayList<Renderable> _newlist, Renderable _master, JHVDate _time) {
newlist = _newlist;
master = _master;
time = _time;
}
@Override
protected Integer backgroundWork() {
for (Renderable renderable : newlist) {
while (!renderable.isLoadedForState()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return 1;
}
@Override
protected void done() {
if (!isCancelled()) {
for (Renderable renderable : newlist) {
addRenderable(renderable);
if (renderable == master && renderable instanceof ImageLayer)
((ImageLayer) renderable).setActiveImageLayer();
}
Layers.setTime(time);
}
}
}
}
|
package integration;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.Selectors;
import com.codeborne.selenide.ex.InvalidStateException;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import java.util.Arrays;
import java.util.List;
import static com.codeborne.selenide.Condition.empty;
import static com.codeborne.selenide.Condition.exactValue;
import static com.codeborne.selenide.Condition.selected;
import static com.codeborne.selenide.Condition.readonly;
import static com.codeborne.selenide.Configuration.timeout;
import static com.codeborne.selenide.Selenide.$;
import static org.assertj.core.api.Assertions.anyOf;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
class ReadonlyElementsTest extends IntegrationTest {
@BeforeEach
void openTestPage() {
openFile("page_with_readonly_elements.html");
timeout = 10 * averageSeleniumCommandDuration;
}
@AfterEach
void cleanUp() {
Configuration.fastSetValue = false;
}
@Test
void cannotSetValueToReadonlyField_slowSetValue() {
final List<String> exceptionMessages = Arrays.asList(
"Element is read-only and so may not be used for actions",
"Element must be user-editable in order to clear it",
"You may only edit editable elements",
"Invalid element state: invalid element state",
"Element is read-only: <input name=\"username\">"
);
Configuration.fastSetValue = false;
assertThat(verifySetValueThrowsException())
.is(anyOf(getExceptionMessagesCondition(exceptionMessages)));
}
private String verifySetValueThrowsException() {
try {
$(By.name("username")).val("another-username");
fail("should throw InvalidStateException where setting value to readonly/disabled element");
return null;
} catch (InvalidStateException expected) {
$(By.name("username")).shouldBe(empty);
$(By.name("username")).shouldHave(exactValue(""));
return expected.getMessage();
}
}
private Condition<String> getExceptionMessagesCondition(final List<String> exceptionMessages) {
return new Condition<>(exception ->
exceptionMessages.stream().anyMatch(exception::contains),
"exceptionMessages");
}
@Test
void cannotSetValueToDisabledField_slowSetValue() {
final List<String> exceptionMessages = Arrays.asList(
"Element must be user-editable in order to clear it",
"You may only edit editable elements",
"You may only interact with enabled elements",
"Element is not currently interactable and may not be manipulated",
"Invalid element state: invalid element state: Element is not currently interactable and may not be manipulated",
"Element is disabled");
Configuration.fastSetValue = false;
assertThat(verifySetValue2ThrowsException())
.is(anyOf(getExceptionMessagesCondition(exceptionMessages)));
}
private String verifySetValue2ThrowsException() {
try {
$(By.name("password")).setValue("another-pwd");
fail("should throw InvalidStateException where setting value to readonly/disabled element");
return null;
} catch (InvalidStateException expected) {
$(By.name("password")).shouldBe(empty);
$(By.name("password")).shouldHave(exactValue(""));
return expected.getMessage();
}
}
@Test
void cannotSetValueToReadonlyField_fastSetValue() {
final List<String> exceptionMessages = Arrays.asList(
"Cannot change value of readonly element",
"Element must be user-editable in order to clear it");
Configuration.fastSetValue = true;
assertThat(verifySetValueThrowsException())
.is(anyOf(getExceptionMessagesCondition(exceptionMessages)));
}
@Test
void cannotSetValueToDisabledField_fastSetValue() {
final List<String> exceptionMessages = Arrays.asList(
"Cannot change value of disabled element",
"Element is not currently interactable and may not be manipulated");
Configuration.fastSetValue = true;
assertThat(verifySetValue2ThrowsException())
.is(anyOf(getExceptionMessagesCondition(exceptionMessages)));
}
@Test
void cannotSetValueToReadonlyTextArea() {
assertThatThrownBy(() -> $("#text-area").val("textArea value"))
.isInstanceOf(InvalidStateException.class);
}
@Test
void cannotSetValueToDisabledTextArea() {
assertThatThrownBy(() -> $("#text-area-disabled").val("textArea value"))
.isInstanceOf(InvalidStateException.class);
}
@Test
void cannotChangeValueOfDisabledCheckbox() {
assertThatThrownBy(() -> $(By.name("disabledCheckbox")).setSelected(false))
.isInstanceOf(InvalidStateException.class);
}
@Test
void cannotSetValueToReadonlyCheckbox() {
assertThatThrownBy(() -> $(By.name("rememberMe")).setSelected(true))
.isInstanceOf(InvalidStateException.class);
}
@Test
void cannotSetValueToReadonlyRadiobutton() {
assertThatThrownBy(() -> $(By.name("me")).selectRadio("margarita"))
.isInstanceOf(InvalidStateException.class);
}
@Test
void waitsUntilInputGetsEditable_slowSetValue() {
$("#enable-inputs").click();
Configuration.fastSetValue = false;
$(By.name("username")).val("another-username");
$(By.name("username")).shouldHave(exactValue("another-username"));
}
@Test
void waitsUntilInputGetsEditable_fastSetValue() {
$("#enable-inputs").click();
Configuration.fastSetValue = true;
$(By.name("username")).val("another-username");
$(By.name("username")).shouldHave(exactValue("another-username"));
}
@Test
void waitsUntilTextAreaGetsEditable() {
$("#enable-inputs").click();
$("#text-area").val("TextArea value");
$("#text-area").shouldHave(exactValue("TextArea value"));
}
@Test
void waitsUntilCheckboxGetsEditable() {
$("#enable-inputs").click();
$(By.name("rememberMe")).setSelected(true);
$(By.name("rememberMe")).shouldBe(selected);
}
@Test
void waitsUntilRadiobuttonGetsEditable() {
$("#enable-inputs").click();
$(By.name("me")).selectRadio("margarita");
$(Selectors.byValue("margarita")).shouldBe(selected);
}
@Test
void readonlyAttributeIsShownInErrorMessage() {
assertThatThrownBy(() -> $(By.name("username")).shouldNotHave(readonly))
.hasMessageMatching("(?s).*<input.*readonly.*");
}
}
|
package solver.constraints.nary;
import common.ESat;
import common.util.tools.ArrayUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
import solver.Solver;
import solver.constraints.Constraint;
import solver.constraints.IntConstraintFactory;
import solver.exception.ContradictionException;
import solver.search.loop.monitors.SearchMonitorFactory;
import solver.search.strategy.IntStrategyFactory;
import solver.variables.IntVar;
import solver.variables.VariableFactory;
public class LexTest {
@Test(groups = "1s")
public void testLessLexq() {
for (int seed = 0; seed < 5; seed++) {
Solver solver = new Solver();
int n1 = 8;
int k = 2;
IntVar[] vs1 = new IntVar[n1 / 2];
IntVar[] vs2 = new IntVar[n1 / 2];
for (int i = 0; i < n1 / 2; i++) {
vs1[i] = VariableFactory.bounded("" + i, 0, k, solver);
vs2[i] = VariableFactory.bounded("" + i, 0, k, solver);
}
solver.post(IntConstraintFactory.lex_less_eq(vs1, vs2));
solver.set(IntStrategyFactory.random(ArrayUtils.append(vs1, vs2), seed));
solver.findAllSolutions();
int kpn = (int) Math.pow(k + 1, n1 / 2);
Assert.assertEquals(solver.getMeasures().getSolutionCount(), (kpn * (kpn + 1) / 2));
}
}
@Test(groups = "1s")
public void testLex() {
for (int seed = 0; seed < 5; seed++) {
Solver solver = new Solver();
int n1 = 8;
int k = 2;
IntVar[] vs1 = new IntVar[n1 / 2];
IntVar[] vs2 = new IntVar[n1 / 2];
for (int i = 0; i < n1 / 2; i++) {
vs1[i] = VariableFactory.bounded("" + i, 0, k, solver);
vs2[i] = VariableFactory.bounded("" + i, 0, k, solver);
}
solver.post(IntConstraintFactory.lex_less(vs1, vs2));
solver.set(IntStrategyFactory.random(ArrayUtils.append(vs1, vs2), seed));
solver.findAllSolutions();
Assert.assertEquals(solver.getMeasures().getSolutionCount(), 3240);
}
}
@Test(groups = "1s")
public void testLexiSatisfied() {
Solver solver = new Solver();
IntVar v1 = VariableFactory.bounded("v1", 1, 1, solver);
IntVar v2 = VariableFactory.bounded("v2", 2, 2, solver);
IntVar v3 = VariableFactory.bounded("v3", 3, 3, solver);
Constraint c1 = IntConstraintFactory.lex_less(new IntVar[]{v1, v2}, new IntVar[]{v1, v3});
Constraint c2 = IntConstraintFactory.lex_less(new IntVar[]{v1, v2}, new IntVar[]{v1, v2});
Constraint c3 = IntConstraintFactory.lex_less(new IntVar[]{v1, v2}, new IntVar[]{v1, v1});
Constraint c4 = IntConstraintFactory.lex_less_eq(new IntVar[]{v1, v2}, new IntVar[]{v1, v3});
Constraint c5 = IntConstraintFactory.lex_less_eq(new IntVar[]{v1, v2}, new IntVar[]{v1, v2});
Constraint c6 = IntConstraintFactory.lex_less_eq(new IntVar[]{v1, v2}, new IntVar[]{v1, v1});
solver.post(c1, c2, c3, c4, c5, c6);
Assert.assertEquals(ESat.TRUE, c1.isSatisfied());
Assert.assertEquals(ESat.FALSE, c2.isSatisfied());
Assert.assertEquals(ESat.FALSE, c3.isSatisfied());
Assert.assertEquals(ESat.TRUE, c4.isSatisfied());
Assert.assertEquals(ESat.TRUE, c5.isSatisfied());
Assert.assertEquals(ESat.FALSE, c6.isSatisfied());
}
@Test(groups = "1s")
public void testAshish() {
Solver solver = new Solver();
IntVar[] a = new IntVar[2];
IntVar[] b = new IntVar[2];
a[0] = VariableFactory.bounded("a1", 5, 7, solver);
a[1] = VariableFactory.bounded("a2", 1, 1, solver);
b[0] = VariableFactory.bounded("b1", 5, 8, solver);
b[1] = VariableFactory.bounded("b2", 0, 0, solver);
solver.post(IntConstraintFactory.lex_less(a, b));
try {
solver.propagate();
} catch (ContradictionException e) {
Assert.fail();
}
SearchMonitorFactory.log(solver, true, true);
solver.findAllSolutions();
Assert.assertEquals(6, solver.getMeasures().getSolutionCount());
}
@Test(groups = "1s")
public void testBug1() {
Solver solver = new Solver();
IntVar[] a = new IntVar[2];
IntVar[] b = new IntVar[2];
a[0] = VariableFactory.enumerated("a2", new int[]{5, 8}, solver);
a[1] = VariableFactory.enumerated("a3", new int[]{-2, 0}, solver);
b[0] = VariableFactory.enumerated("b2", new int[]{5, 8}, solver);
b[1] = VariableFactory.enumerated("b3", new int[]{-3, -2}, solver);
solver.post(IntConstraintFactory.lex_less(a, b));
try {
solver.propagate();
} catch (ContradictionException e) {
Assert.fail();
}
Assert.assertEquals(5, a[0].getUB());
SearchMonitorFactory.log(solver, true, true);
solver.findAllSolutions();
Assert.assertEquals(solver.getMeasures().getSolutionCount(), 4);
}
@Test(groups = "1s")
public void testBug2() {
Solver solver = new Solver();
IntVar[] a = new IntVar[2];
IntVar[] b = new IntVar[2];
a[0] = VariableFactory.enumerated("a1", new int[]{-2, 5}, solver);
a[1] = VariableFactory.enumerated("a2", new int[]{-1, 1}, solver);
b[0] = VariableFactory.enumerated("b1", new int[]{3, 5}, solver);
b[1] = VariableFactory.enumerated("b2", new int[]{-6, -1}, solver);
solver.post(IntConstraintFactory.lex_less(a, b));
try {
solver.propagate();
} catch (ContradictionException e) {
Assert.fail();
}
Assert.assertEquals(-2, a[0].getUB());
solver.findAllSolutions();
Assert.assertEquals(solver.getMeasures().getSolutionCount(), 8);
}
@Test(groups = "1s")
public void testBug3() {
Solver solver = new Solver();
IntVar[] a = new IntVar[2];
IntVar[] b = new IntVar[2];
a[0] = VariableFactory.enumerated("a1", new int[]{5}, solver);
a[1] = VariableFactory.enumerated("a2", new int[]{-1, 1}, solver);
b[0] = VariableFactory.enumerated("b1", new int[]{3, 5}, solver);
b[1] = VariableFactory.enumerated("b2", new int[]{-6, -1}, solver);
solver.post(IntConstraintFactory.lex_less(a, b));
try {
solver.propagate();
Assert.fail();
} catch (ContradictionException e) {
}
Assert.assertEquals(solver.getMeasures().getSolutionCount(), 0);
}
@Test(groups = "1s")
public void testBug4() {
Solver solver = new Solver();
IntVar[] a = new IntVar[5];
IntVar[] b = new IntVar[5];
a[0] = VariableFactory.enumerated("a1", new int[]{2}, solver);
a[1] = VariableFactory.enumerated("a2", new int[]{1, 3, 4}, solver);
a[2] = VariableFactory.enumerated("a3", new int[]{1, 2, 3, 4, 5}, solver);
a[3] = VariableFactory.enumerated("a4", new int[]{1, 2}, solver);
a[4] = VariableFactory.enumerated("a5", new int[]{3, 4, 5}, solver);
b[0] = VariableFactory.enumerated("b1", new int[]{0, 1, 2}, solver);
b[1] = VariableFactory.enumerated("b2", new int[]{1}, solver);
b[2] = VariableFactory.enumerated("b3", new int[]{0, 1, 2, 3, 4}, solver);
b[3] = VariableFactory.enumerated("b4", new int[]{0, 1}, solver);
b[4] = VariableFactory.enumerated("b5", new int[]{0, 1, 2}, solver);
solver.post(IntConstraintFactory.lex_less(a, b));
try {
solver.propagate();
} catch (ContradictionException e) {
}
solver.findAllSolutions();
Assert.assertEquals(solver.getMeasures().getSolutionCount(), 216);
}
@Test(groups = "1s")
public void testBug5() {
Solver solver = new Solver();
IntVar[] a = new IntVar[3];
IntVar[] b = new IntVar[3];
a[0] = VariableFactory.enumerated("a1", new int[]{-10, -3, 2}, solver);
a[1] = VariableFactory.enumerated("a2", new int[]{-5, -4, 2}, solver);
a[2] = VariableFactory.enumerated("a3", new int[]{2}, solver);
b[0] = VariableFactory.enumerated("b1", new int[]{-10, -1, 3}, solver);
b[1] = VariableFactory.enumerated("b2", new int[]{-5}, solver);
b[2] = VariableFactory.enumerated("b3", new int[]{-4, 2}, solver);
solver.post(IntConstraintFactory.lex_less(a, b));
try {
solver.propagate();
} catch (ContradictionException e) {
Assert.fail();
}
Assert.assertEquals(-1, b[0].getLB());
SearchMonitorFactory.log(solver, true, false);
solver.findAllSolutions();
Assert.assertEquals(solver.getMeasures().getSolutionCount(), 30);
}
}
|
package org.jetbrains.plugins.scala.lang.lexer;
import com.intellij.psi.tree.IElementType;
public interface ScalaTokenTypes {
///////////////////////// Wrong token //////////////////////////////////////////////////////////////////////////////////
IElementType tWRONG = new ScalaElementType("wrong token");
///////////////////////// White spaces in line /////////////////////////////////////////////////////////////////////////////////////
IElementType tWHITE_SPACE_IN_LINE = new ScalaElementType("white space in line");
///////////////////////// White spaces in line /////////////////////////////////////////////////////////////////////////////////////
IElementType tLINE_TERMINATOR = new ScalaElementType("newline");
IElementType tNON_SIGNIFICANT_NEWLINE = new ScalaElementType("non significant line terminate");
///////////////////////// Stub /////////////////////////////////////////////////////////////////////////////////////
IElementType tSTUB = new ScalaElementType("stub");
///////////////////////// Comments /////////////////////////////////////////////////////////////////////////////////////
IElementType tCOMMENT = new ScalaElementType("comment");
IElementType tBLOCK_COMMENT = new ScalaElementType("comment");
///////////////////////// Strings & chars //////////////////////////////////////////////////////////////////////////////
IElementType tSTRING = new ScalaElementType("string content");
IElementType tWRONG_STRING = new ScalaElementType("wrong string content");
IElementType tCHAR = new ScalaElementType("Character");
IElementType tSYMBOL = new ScalaElementType("Symbol");
///////////////////////// integer and float literals ///////////////////////////////////////////////////////////////////
IElementType tINTEGER = new ScalaElementType("integer");
IElementType tFLOAT = new ScalaElementType("float");
///////////////////////// Operators ////////////////////////////////////////////////////////////////////////////////////
IElementType tEQUAL = new ScalaElementType("==");
IElementType tNOTEQUAL = new ScalaElementType("!=");
IElementType tLESS = new ScalaElementType("<");
IElementType tLESSOREQUAL = new ScalaElementType("<=");
IElementType tGREATER = new ScalaElementType(">");
IElementType tGREATEROREQUAL = new ScalaElementType(">=");
IElementType tPLUS = new ScalaElementType("+");
IElementType tMINUS = new ScalaElementType("-");
IElementType tTILDA = new ScalaElementType("~");
IElementType tNOT = new ScalaElementType("!");
IElementType tSTAR = new ScalaElementType("*");
IElementType tDIV = new ScalaElementType("/");
///////////////////////// Braces ///////////////////////////////////////////////////////////////////////////////////////
IElementType tLSQBRACKET = new ScalaElementType("[");
IElementType tRSQBRACKET = new ScalaElementType("]");
IElementType tLBRACE = new ScalaElementType("{");
IElementType tRBRACE = new ScalaElementType("}");
IElementType tLPARENTHIS = new ScalaElementType("(");
IElementType tRPARENTHIS = new ScalaElementType(")");
///////////////////////// keywords /////////////////////////////////////////////////////////////////////////////////////
IElementType kABSTRACT = new ScalaElementType("abstract");
IElementType kCASE = new ScalaElementType("case");
IElementType kCATCH = new ScalaElementType("catch");
IElementType kCLASS = new ScalaElementType("class");
IElementType kDEF = new ScalaElementType("def");
IElementType kDO = new ScalaElementType("do");
IElementType kELSE = new ScalaElementType("else");
IElementType kEXTENDS = new ScalaElementType("extends");
IElementType kFALSE = new ScalaElementType("false");
IElementType kFINAL = new ScalaElementType("final");
IElementType kFINALLY = new ScalaElementType("finally");
IElementType kFOR = new ScalaElementType("for");
IElementType kIF = new ScalaElementType("if");
IElementType kIMPLICIT = new ScalaElementType("implicit");
IElementType kIMPORT = new ScalaElementType("import");
IElementType kMATCH = new ScalaElementType("match");
IElementType kNEW = new ScalaElementType("new");
IElementType kNULL = new ScalaElementType("null");
IElementType kOBJECT = new ScalaElementType("object");
IElementType kOVERRIDE = new ScalaElementType("override");
IElementType kPACKAGE = new ScalaElementType("package");
IElementType kPRIVATE = new ScalaElementType("private");
IElementType kPROTECTED = new ScalaElementType("protected");
IElementType kREQUIRES = new ScalaElementType("requires");
IElementType kRETURN = new ScalaElementType("return");
IElementType kSEALED = new ScalaElementType("sealed");
IElementType kSUPER = new ScalaElementType("super");
IElementType kTHIS = new ScalaElementType("this");
IElementType kTHROW = new ScalaElementType("throw");
IElementType kTRAIT = new ScalaElementType("trait");
IElementType kTRY = new ScalaElementType("try");
IElementType kTRUE = new ScalaElementType("true");
IElementType kTYPE = new ScalaElementType("type");
IElementType kVAL = new ScalaElementType("val");
IElementType kVAR = new ScalaElementType("var");
IElementType kWHILE = new ScalaElementType("while");
IElementType kWITH = new ScalaElementType("whith");
IElementType kYIELD = new ScalaElementType("yield");
///////////////////////// variables and constants //////////////////////////////////////////////////////////////////////
IElementType tIDENTIFIER = new ScalaElementType("identifier");
////////////////////////// xml tag /////////////////////////////////////////////////////////////////////////////////////
IElementType tOPENXMLTAG = new ScalaElementType("opened xml tag");
IElementType tCLOSEXMLTAG = new ScalaElementType("closed xml tag");
IElementType tBEGINSCALAEXPR = new ScalaElementType("begin of scala expression");
IElementType tENDSCALAEXPR = new ScalaElementType("end of scala expression");
IElementType tDOT = new ScalaElementType(".");
IElementType tCOMMA = new ScalaElementType(",");
IElementType tSEMICOLON = new ScalaElementType(";");
IElementType tUNDER = new ScalaElementType("_");
IElementType tCOLON = new ScalaElementType(":");
IElementType tASSIGN = new ScalaElementType("=");
IElementType tAND = new ScalaElementType("&");
IElementType tOR = new ScalaElementType("|");
IElementType tFUNTYPE = new ScalaElementType("=>");
IElementType tFUNTYPE_ASCII = new ScalaElementType(Character.toString('\u21D2'));
IElementType tCHOOSE = new ScalaElementType("<-");
IElementType tLOWER_BOUND = new ScalaElementType(">:");
IElementType tUPPER_BOUND = new ScalaElementType("<:");
IElementType tVIEW = new ScalaElementType("<%");
IElementType tINNER_CLASS = new ScalaElementType("
IElementType tAT = new ScalaElementType("@");
IElementType tQUESTION = new ScalaElementType("?");
}
|
package au.gov.amsa.streams;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;
/**
* Publishes lines from an Observable<String> source to a
* {@link ServerSocket}.
*/
public class StringServer {
private static Logger log = LoggerFactory.getLogger(StringServer.class);
private final ServerSocket ss;
private volatile boolean keepGoing = true;
private final Observable<String> source;
/**
* Factory method.
*
* @param source
* source to publish on server socket
* @param port
* to assign the server socket to
*/
public static StringServer create(Observable<String> source, int port) {
return new StringServer(source, port);
}
/**
* Constructor.
*
* @param ss
* {@link ServerSocket} to publish to
* @param source
* the source of lines to publish on ServerSocket
*/
private StringServer(Observable<String> source, int port) {
try {
this.ss = new ServerSocket(port);
} catch (IOException e) {
throw new RuntimeException(e);
}
this.source = source;
}
/**
* Starts the server. Each connection to the server will bring about another
* subscription to the source.
*/
public void start() {
try {
while (keepGoing) {
try {
// this is a blocking call so it hogs a thread
final Socket socket = ss.accept();
final String socketName = socket.getInetAddress()
.getHostAddress() + ":" + socket.getPort();
try {
final OutputStream out = socket.getOutputStream();
source
// subscribe in background so can accept another
// connection
.subscribeOn(Schedulers.io())
// write each line to the socket OutputStream
.subscribe(
createSubscriber(socket, socketName,
out));
} catch (IOException e) {
// could not get output stream (could have closed very
// quickly after connecting
// dont' care
}
} catch (SocketTimeoutException e) {
// don't care
}
}
} catch (IOException e) {
if (keepGoing) {
log.warn(e.getMessage(), e);
throw new RuntimeException(e);
} else
log.info("server stopped");
} finally {
closeServerSocket();
}
}
/**
* Stops the server by closing the ServerSocket.
*/
public void stop() {
log.info("stopping");
keepGoing = false;
closeServerSocket();
}
private void closeServerSocket() {
try {
ss.close();
} catch (IOException e) {
log.info("could not close server socket: " + e.getMessage());
}
}
private static Subscriber<String> createSubscriber(final Socket socket,
final String socketName, final OutputStream out) {
return new Subscriber<String>() {
@Override
public void onCompleted() {
log.info("stream completed");
closeSocket();
}
@Override
public void onError(Throwable e) {
log.error(e.getMessage()
+ " - unexpected due to upstream retry");
closeSocket();
}
@Override
public void onNext(String line) {
try {
out.write(line.getBytes(StandardCharsets.UTF_8));
out.flush();
} catch (IOException e) {
log.info(e.getMessage() + " " + socketName);
// this will unsubscribe to clean up the
// resources associated with this subscription
unsubscribe();
closeSocket();
}
}
private void closeSocket() {
try {
socket.close();
} catch (IOException e1) {
log.info("closing socket " + socketName + ":"
+ e1.getMessage());
}
}
};
}
}
|
package org.maltparser.parser.guide.instance;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.maltparser.core.config.ConfigurationDir;
import org.maltparser.core.exception.MaltChainedException;
import org.maltparser.core.feature.FeatureException;
import org.maltparser.core.feature.FeatureVector;
import org.maltparser.core.feature.function.FeatureFunction;
import org.maltparser.core.feature.function.Modifiable;
import org.maltparser.core.feature.value.SingleFeatureValue;
import org.maltparser.core.syntaxgraph.DependencyStructure;
import org.maltparser.parser.guide.ClassifierGuide;
import org.maltparser.parser.guide.GuideException;
import org.maltparser.parser.guide.Model;
import org.maltparser.parser.history.action.SingleDecision;
/**
* This class implements a decision tree model. The class is recursive and an
* instance of the class can be a root model or belong to an other decision tree
* model. Every node in the decision tree is represented by an instance of the
* class. Node can be in one of the three states branch model, leaf model or not
* decided. A branch model has several sub decision tree models and a leaf model
* owns an atomic model that is used to classify instances. When a decision tree
* model is in the not decided state it has both sub decision trees and an
* atomic model. It can be in the not decided state during training before it is
* tested by cross validation if the sub decision tree models provide better
* accuracy than the atomic model.
*
*
* @author Kjell Winblad
*/
public class DecisionTreeModel implements InstanceModel {
/*
* The leaf nodes needs a int index that is unique among all leaf nodes
* because they have an AtomicModel which need such an index.
*/
private static int leafModelIndexConter = 0;
private final static int OTHER_BRANCH_ID = 999;// Integer.MAX_VALUE;
// The number of division used when doing cross validation test
private int numberOfCrossValidationSplits = 10;
/*
* Cross validation accuracy is calculated for every node during training
* This should be calculated for every node and is set to -1.0 if it isn't
* calculated yet
*/
private final static double CROSS_VALIDATION_ACCURACY_NOT_SET_VALUE = -1.0;
private double crossValidationAccuracy = CROSS_VALIDATION_ACCURACY_NOT_SET_VALUE;
// The parent model
private Model parent = null;
// An ordered list of features to divide on
private LinkedList<FeatureFunction> divideFeatures = null;
/*
* The branches of the tree Is set to null if this is a leaf node
*/
private SortedMap<Integer, DecisionTreeModel> branches = null;
/*
* This model is used if this is a leaf node Is set to null if this is a
* branch node
*/
private AtomicModel leafModel = null;
// Number of training instances added
private int frequency = 0;
/*
* min number of instances for a node to existAll sub nodes with less
* instances will be concatenated to one sub node
*/
private int divideThreshold = 0;
// The feature vector for this problem
private FeatureVector featureVector;
private FeatureVector subFeatureVector = null;
// Used to indicate that the modelIndex field is not set
private static final int MODEL_INDEX_NOT_SET = Integer.MIN_VALUE;
/*
* Model index is the identifier used to distinguish this model from other
* models at the same level. This should not be used in the root model and
* has the value MODEL_INDEX_NOT_SET in it.
*/
private int modelIndex = MODEL_INDEX_NOT_SET;
// Indexes of the column used to divide on
private ArrayList<Integer> divideFeatureIndexVector;
/**
* Constructs a feature divide model.
*
* @param features
* the feature vector used by the decision tree model
* @param parent
* the parent guide model.
* @throws MaltChainedException
*/
public DecisionTreeModel(FeatureVector featureVector, Model parent)
throws MaltChainedException {
this.featureVector = featureVector;
this.divideFeatures = new LinkedList<FeatureFunction>();
setParent(parent);
setFrequency(0);
initDecisionTreeParam();
if (getGuide().getGuideMode() == ClassifierGuide.GuideMode.BATCH) {
// Prepare for training
branches = new TreeMap<Integer, DecisionTreeModel>();
leafModel = new AtomicModel(-1, featureVector, this);
} else if (getGuide().getGuideMode() == ClassifierGuide.GuideMode.CLASSIFY) {
load();
}
}
/*
* This constructor is used from within objects of the class to create sub decision tree models
*
*
*/
private DecisionTreeModel(int modelIndex, FeatureVector featureVector,
Model parent, LinkedList<FeatureFunction> divideFeatures,
int divideThreshold) throws MaltChainedException {
this.featureVector = featureVector;
setParent(parent);
setFrequency(0);
this.modelIndex = modelIndex;
this.divideFeatures = divideFeatures;
this.divideThreshold = divideThreshold;
if (getGuide().getGuideMode() == ClassifierGuide.GuideMode.BATCH) {
//Create the divide feature index vector
if (divideFeatures.size() > 0) {
divideFeatureIndexVector = new ArrayList<Integer>();
for (int i = 0; i < featureVector.size(); i++) {
if (featureVector.get(i).equals(divideFeatures.get(0))) {
divideFeatureIndexVector.add(i);
}
}
}
leafModelIndexConter++;
// Prepare for training
branches = new TreeMap<Integer, DecisionTreeModel>();
leafModel = new AtomicModel(-1, featureVector, this);
} else if (getGuide().getGuideMode() == ClassifierGuide.GuideMode.CLASSIFY) {
load();
}
}
/**
* Loads the feature divide model settings .fsm file.
*
* @throws MaltChainedException
*/
protected void load() throws MaltChainedException {
ConfigurationDir configDir = getGuide().getConfiguration()
.getConfigurationDir();
// load the dsm file
try {
final BufferedReader in = new BufferedReader(
configDir.getInputStreamReaderFromConfigFile(getModelName()
+ ".dsm"));
final Pattern tabPattern = Pattern.compile("\t");
boolean first = true;
while (true) {
String line = in.readLine();
if (line == null)
break;
String[] cols = tabPattern.split(line);
if (cols.length != 2) {
throw new GuideException("");
}
int code = -1;
int freq = 0;
try {
code = Integer.parseInt(cols[0]);
freq = Integer.parseInt(cols[1]);
} catch (NumberFormatException e) {
throw new GuideException(
"Could not convert a string value into an integer value when loading the feature divide model settings (.fsm). ",
e);
}
if (code == MODEL_INDEX_NOT_SET) {
if (!first)
throw new GuideException(
"Error in config file '"
+ getModelName()
+ ".dsm"
+ "'. If the index in the .dsm file is MODEL_INDEX_NOT_SET it should be the first.");
first = false;
// It is a leaf node
// Create atomic model for the leaf node
leafModel = new AtomicModel(-1, featureVector, this);
// setIsLeafNode();
} else {
if (first) {
// Create the branches holder
branches = new TreeMap<Integer, DecisionTreeModel>();
// setIsBranchNode();
first = false;
}
if (branches == null)
throw new GuideException(
"Error in config file '"
+ getModelName()
+ ".dsm"
+ "'. If MODEL_INDEX_NOT_SET is the first model index in the .dsm file it should be the only.");
if (code == OTHER_BRANCH_ID)
branches.put(code, new DecisionTreeModel(code,
featureVector, this,
new LinkedList<FeatureFunction>(),
divideThreshold));
else
branches.put(code, new DecisionTreeModel(code,
getSubFeatureVector(), this,
createNextLevelDivideFeatures(),
divideThreshold));
branches.get(code).setFrequency(freq);
setFrequency(getFrequency() + freq);
}
}
in.close();
} catch (IOException e) {
throw new GuideException(
"Could not read from the guide model settings file '"
+ getModelName() + ".dsm" + "', when "
+ "loading the guide model settings. ", e);
}
}
private void initDecisionTreeParam() throws MaltChainedException {
String treeSplitColumns = getGuide().getConfiguration().getOptionValue(
"guide", "tree_split_columns").toString();
String treeSplitStructures = getGuide().getConfiguration()
.getOptionValue("guide", "tree_split_structures").toString();
if (treeSplitColumns == null || treeSplitColumns.length() == 0) {
throw new GuideException(
"The option '--guide-tree_split_columns' cannot be found, when initializing the decision tree model. ");
}
if (treeSplitStructures == null || treeSplitStructures.length() == 0) {
throw new GuideException(
"The option '--guide-tree_split_structures' cannot be found, when initializing the decision tree model. ");
}
String[] treeSplitColumnsArray = treeSplitColumns.split("@");
String[] treeSplitStructuresArray = treeSplitStructures.split("@");
if (treeSplitColumnsArray.length != treeSplitStructuresArray.length)
throw new GuideException(
"The option '--guide-tree_split_structures' and '--guide-tree_split_columns' must be followed by a ; separated lists of the same length");
try {
for (int n = 0; n < treeSplitColumnsArray.length; n++) {
final String spec = "InputColumn("
+ treeSplitColumnsArray[n].trim() + ", "
+ treeSplitStructuresArray[n].trim() + ")";
divideFeatures.addLast(featureVector.getFeatureModel()
.identifyFeature(spec));
}
} catch (FeatureException e) {
throw new GuideException("The data split feature 'InputColumn("
+ getGuide().getConfiguration().getOptionValue("guide",
"data_split_column").toString()
+ ", "
+ getGuide().getConfiguration().getOptionValue("guide",
"data_split_structure").toString()
+ ") cannot be initialized. ", e);
}
for (FeatureFunction divideFeature : divideFeatures) {
if (!(divideFeature instanceof Modifiable)) {
throw new GuideException("The data split feature 'InputColumn("
+ getGuide().getConfiguration().getOptionValue("guide",
"data_split_column").toString()
+ ", "
+ getGuide().getConfiguration().getOptionValue("guide",
"data_split_structure").toString()
+ ") does not implement Modifiable interface. ");
}
}
divideFeatureIndexVector = new ArrayList<Integer>();
for (int i = 0; i < featureVector.size(); i++) {
if (featureVector.get(i).equals(divideFeatures.get(0))) {
divideFeatureIndexVector.add(i);
}
}
if (divideFeatureIndexVector.size() == 0) {
throw new GuideException(
"Could not match the given divide features to any of the available features.");
}
try {
String treeSplitTreshold = getGuide().getConfiguration()
.getOptionValue("guide", "tree_split_threshold").toString();
if (treeSplitTreshold != null && treeSplitTreshold.length() > 0) {
divideThreshold = Integer.parseInt(treeSplitTreshold);
} else {
divideThreshold = 0;
}
} catch (NumberFormatException e) {
throw new GuideException(
"The --guide-tree_split_threshold option is not an integer value. ",
e);
}
try {
String treeNumberOfCrossValidationDivisions = getGuide()
.getConfiguration().getOptionValue("guide",
"tree_number_of_cross_validation_divisions")
.toString();
if (treeNumberOfCrossValidationDivisions != null
&& treeNumberOfCrossValidationDivisions.length() > 0) {
numberOfCrossValidationSplits = Integer
.parseInt(treeNumberOfCrossValidationDivisions);
} else {
divideThreshold = 0;
}
} catch (NumberFormatException e) {
throw new GuideException(
"The --guide-tree_number_of_cross_validation_divisions option is not an integer value. ",
e);
}
}
@Override
public void addInstance(SingleDecision decision)
throws MaltChainedException {
if (getGuide().getGuideMode() == ClassifierGuide.GuideMode.CLASSIFY) {
throw new GuideException("Can only add instance during learning. ");
} else if (divideFeatures.size() > 0) {
FeatureFunction divideFeature = divideFeatures.getFirst();
if (!(divideFeature.getFeatureValue() instanceof SingleFeatureValue)) {
throw new GuideException(
"The divide feature does not have a single value. ");
}
divideFeature.update();
leafModel.addInstance(decision);
} else {
// Model has already been decided. It is a leaf node
if (branches != null)
setIsLeafNode();
leafModel.addInstance(decision);
}
}
@SuppressWarnings("unchecked")
private LinkedList<FeatureFunction> createNextLevelDivideFeatures() {
LinkedList<FeatureFunction> nextLevelDivideFeatures = (LinkedList<FeatureFunction>) divideFeatures
.clone();
nextLevelDivideFeatures.removeFirst();
return nextLevelDivideFeatures;
}
/*
* Removes the current divide feature from the feature vector so it is not
* present in the sub node
*/
private FeatureVector getSubFeatureVector() {
if (subFeatureVector != null)
return subFeatureVector;
FeatureFunction divideFeature = divideFeatures.getFirst();
ArrayList<Integer> divideFeatureIndexVector = new ArrayList<Integer>();
for (int i = 0; i < featureVector.size(); i++) {
if (featureVector.get(i).equals(divideFeature)) {
divideFeatureIndexVector.add(i);
}
}
FeatureVector divideFeatureVector = (FeatureVector) featureVector
.clone();
for (Integer i : divideFeatureIndexVector) {
divideFeatureVector.remove(divideFeatureVector.get(i));
}
subFeatureVector = divideFeatureVector;
return divideFeatureVector;
}
@Override
public FeatureVector extract() throws MaltChainedException {
return getCurrentAtomicModel().extract();
}
/*
* Returns the atomic model that is effected by this parsing step
*/
private AtomicModel getCurrentAtomicModel() throws MaltChainedException {
if (getGuide().getGuideMode() == ClassifierGuide.GuideMode.BATCH) {
throw new GuideException("Can only predict during parsing. ");
}
if (branches == null && leafModel != null)
return leafModel;
FeatureFunction divideFeature = divideFeatures.getFirst();
if (!(divideFeature.getFeatureValue() instanceof SingleFeatureValue)) {
throw new GuideException(
"The divide feature does not have a single value. ");
}
if (branches != null
&& branches.containsKey(((SingleFeatureValue) divideFeature
.getFeatureValue()).getCode())) {
return branches.get(
((SingleFeatureValue) divideFeature.getFeatureValue())
.getCode()).getCurrentAtomicModel();
} else if (branches.containsKey(OTHER_BRANCH_ID)
&& branches.get(OTHER_BRANCH_ID).getFrequency() > 0) {
return branches.get(OTHER_BRANCH_ID).getCurrentAtomicModel();
} else {
getGuide()
.getConfiguration()
.getConfigLogger()
.info(
"Could not predict the next parser decision because there is "
+ "no divide or master model that covers the divide value '"
+ ((SingleFeatureValue) divideFeature
.getFeatureValue()).getCode()
+ "', as default"
+ " class code '1' is used. ");
}
return null;
}
/**
* Increase the frequency by 1
*/
public void increaseFrequency() {
frequency++;
}
public void decreaseFrequency() {
frequency
}
@Override
public boolean predict(SingleDecision decision) throws MaltChainedException {
if (getGuide().getGuideMode() == ClassifierGuide.GuideMode.BATCH) {
throw new GuideException("Can only predict during parsing. ");
} else if (divideFeatures.size() > 0
&& !(divideFeatures.getFirst().getFeatureValue() instanceof SingleFeatureValue)) {
throw new GuideException(
"The divide feature does not have a single value. ");
}
if (branches != null
&& branches.containsKey(((SingleFeatureValue) divideFeatures
.getFirst().getFeatureValue()).getCode())) {
return branches.get(
((SingleFeatureValue) divideFeatures.getFirst()
.getFeatureValue()).getCode()).predict(decision);
} else if (branches != null && branches.containsKey(OTHER_BRANCH_ID)) {
return branches.get(OTHER_BRANCH_ID).predict(decision);
} else if (leafModel != null) {
return leafModel.predict(decision);
} else {
getGuide()
.getConfiguration()
.getConfigLogger()
.info(
"Could not predict the next parser decision because there is "
+ "no divide or master model that covers the divide value '"
+ ((SingleFeatureValue) divideFeatures
.getFirst().getFeatureValue())
.getCode() + "', as default"
+ " class code '1' is used. ");
decision.addDecision(1); // default prediction
// classCodeTable.getEmptyKBestList().addKBestItem(1);
}
return true;
}
@Override
public FeatureVector predictExtract(SingleDecision decision)
throws MaltChainedException {
return getCurrentAtomicModel().predictExtract(decision);
}
/*
* Decides if this is a branch or leaf node by doing cross validation and
* returns the cross validation score for this node
*/
private double decideNodeType() throws MaltChainedException {
// We don't want to do this twice test
if (crossValidationAccuracy != CROSS_VALIDATION_ACCURACY_NOT_SET_VALUE)
return crossValidationAccuracy;
if (modelIndex == MODEL_INDEX_NOT_SET)
if (getGuide().getConfiguration().getConfigLogger().isInfoEnabled()) {
getGuide().getConfiguration().getConfigLogger().info(
"Starting deph first pruning of the decision tree\n");
}
long start = System.currentTimeMillis();
double leafModelCrossValidationAccuracy = leafModel.getMethod()
.crossValidate(featureVector, numberOfCrossValidationSplits);
long stop = System.currentTimeMillis();
if (getGuide().getConfiguration().getConfigLogger().isInfoEnabled()) {
getGuide().getConfiguration().getConfigLogger().info(
"Cross Validation Time: " + (stop - start) + " ms"
+ " for model " + getModelName() + "\n");
}
if (getGuide().getConfiguration().getConfigLogger().isInfoEnabled()) {
getGuide().getConfiguration().getConfigLogger().info(
"Cross Validation Accuracy as leaf node = "
+ leafModelCrossValidationAccuracy + " for model "
+ getModelName() + "\n");
}
if (branches == null && leafModel != null) {// If it is already decided
// that this is a leaf node
crossValidationAccuracy = leafModelCrossValidationAccuracy;
return crossValidationAccuracy;
}
int totalFrequency = 0;
double totalAccuracyCount = 0.0;
// Calculate crossValidationAccuracy for branch nodes
for (DecisionTreeModel b : branches.values()) {
double bAccuracy = b.decideNodeType();
totalFrequency = totalFrequency + b.getFrequency();
totalAccuracyCount = totalAccuracyCount + bAccuracy
* b.getFrequency();
}
double branchModelCrossValidationAccuracy = totalAccuracyCount
/ totalFrequency;
if (getGuide().getConfiguration().getConfigLogger().isInfoEnabled()) {
getGuide().getConfiguration().getConfigLogger().info(
"Total Cross Validation Accuracy for branches = "
+ branchModelCrossValidationAccuracy
+ " for model " + getModelName() + "\n");
}
// Finally decide which model to use
if (branchModelCrossValidationAccuracy > leafModelCrossValidationAccuracy) {
setIsBranchNode();
crossValidationAccuracy = branchModelCrossValidationAccuracy;
return crossValidationAccuracy;
} else {
setIsLeafNode();
crossValidationAccuracy = leafModelCrossValidationAccuracy;
return crossValidationAccuracy;
}
}
@Override
public void train() throws MaltChainedException {
// Decide node type
// This operation is more expensive than the training itself
decideNodeType();
// Do the training depending on which type of node this is
if (branches == null && leafModel != null) {
// If it is a leaf node
leafModel.train();
save();
leafModel.terminate();
} else {
// It is a branch node
for (DecisionTreeModel b : branches.values())
b.train();
save();
for (DecisionTreeModel b : branches.values())
b.terminate();
}
terminate();
}
/**
* Saves the decision tree model settings .dsm file.
*
* @throws MaltChainedException
*/
private void save() throws MaltChainedException {
try {
final BufferedWriter out = new BufferedWriter(getGuide()
.getConfiguration().getConfigurationDir()
.getOutputStreamWriter(getModelName() + ".dsm"));
if (branches != null) {
for (DecisionTreeModel b : branches.values()) {
out.write(b.getModelIndex() + "\t" + b.getFrequency()
+ "\n");
}
} else {
out.write(MODEL_INDEX_NOT_SET + "\t" + getFrequency() + "\n");
}
out.close();
} catch (IOException e) {
throw new GuideException(
"Could not write to the guide model settings file '"
+ getModelName() + ".dsm"
+ "' or the name mapping file '" + getModelName()
+ ".nmf" + "', when "
+ "saving the guide model settings to files. ", e);
}
}
@Override
public void finalizeSentence(DependencyStructure dependencyGraph)
throws MaltChainedException {
if (branches != null) {
for (DecisionTreeModel b : branches.values()) {
b.finalizeSentence(dependencyGraph);
}
} else if (leafModel != null) {
leafModel.finalizeSentence(dependencyGraph);
} else {
throw new GuideException(
"The feature divide models cannot be found. ");
}
}
@Override
public ClassifierGuide getGuide() {
return parent.getGuide();
}
@Override
public String getModelName() throws MaltChainedException {
try {
return parent.getModelName()
+ (modelIndex == MODEL_INDEX_NOT_SET ? ""
: ("_" + modelIndex));
} catch (NullPointerException e) {
throw new GuideException(
"The parent guide model cannot be found. ", e);
}
}
/*
* This is called to define this node as to be in the leaf state. It sets branches to null.
*/
private void setIsLeafNode() throws MaltChainedException {
if (branches == null && leafModel != null)
return;
if (branches != null && leafModel != null) {
for (DecisionTreeModel t : branches.values())
t.terminate();
branches = null;
} else
throw new MaltChainedException(
"Can't set a node that have aleready been set to a leaf node.");
}
/*
* This is called to define this node as to be in the branch state. It sets leafModel to null.
*/
private void setIsBranchNode() throws MaltChainedException {
if (branches != null && leafModel != null) {
leafModel.terminate();
leafModel = null;
} else
throw new MaltChainedException(
"Can't set a node that have aleready been set to a branch node.");
}
@Override
public void noMoreInstances() throws MaltChainedException {
if (leafModel == null)
throw new GuideException(
"The model in tree node is null in a state where it is not allowed");
leafModel.noMoreInstances();
if (divideFeatures.size() == 0)
setIsLeafNode();
if (branches != null) {
FeatureFunction divideFeature = divideFeatures.getFirst();
divideFeature.updateCardinality();
leafModel.noMoreInstances();
Map<Integer, Integer> divideFeatureIdToCountMap = leafModel
.getMethod().createFeatureIdToCountMap(
divideFeatureIndexVector);
int totalInOther = 0;
Set<Integer> featureIdsToCreateSeparateBranchesForSet = new HashSet<Integer>();
List<Integer> removeFromDivideFeatureIdToCountMap = new LinkedList<Integer>();
for (Entry<Integer, Integer> entry : divideFeatureIdToCountMap
.entrySet())
if (entry.getValue() >= divideThreshold) {
featureIdsToCreateSeparateBranchesForSet
.add(entry.getKey());
} else {
removeFromDivideFeatureIdToCountMap.add(entry.getKey());
totalInOther = totalInOther + entry.getValue();
}
for (int removeIndex : removeFromDivideFeatureIdToCountMap)
divideFeatureIdToCountMap.remove(removeIndex);
boolean otherExists = false;
if (totalInOther > 0)
otherExists = true;
if ((totalInOther < divideThreshold && featureIdsToCreateSeparateBranchesForSet
.size() <= 1)
|| featureIdsToCreateSeparateBranchesForSet.size() == 0) {
// Node enough instances, make this a leaf node
setIsLeafNode();
} else {
// If total in other is less then divideThreshold then add the
// smallest of the other parts to other
if (otherExists && totalInOther < divideThreshold) {
int smallestSoFar = Integer.MAX_VALUE;
int smallestSoFarId = Integer.MAX_VALUE;
for (Entry<Integer, Integer> entry : divideFeatureIdToCountMap
.entrySet()) {
if (entry.getValue() < smallestSoFar) {
smallestSoFar = entry.getValue();
smallestSoFarId = entry.getKey();
}
}
featureIdsToCreateSeparateBranchesForSet
.remove(smallestSoFarId);
}
// Create new files for all feature ids with count value greater
// than divideThreshold and one for the
// other branch
leafModel.getMethod().divideByFeatureSet(
featureIdsToCreateSeparateBranchesForSet,
divideFeatureIndexVector, "" + OTHER_BRANCH_ID);
for (int id : featureIdsToCreateSeparateBranchesForSet) {
DecisionTreeModel newBranch = new DecisionTreeModel(id,
getSubFeatureVector(), this,
createNextLevelDivideFeatures(), divideThreshold);
branches.put(id, newBranch);
}
if (otherExists) {
DecisionTreeModel newBranch = new DecisionTreeModel(
OTHER_BRANCH_ID, featureVector, this,
new LinkedList<FeatureFunction>(), divideThreshold);
branches.put(OTHER_BRANCH_ID, newBranch);
}
for (DecisionTreeModel b : branches.values())
b.noMoreInstances();
}
}
}
@Override
public void terminate() throws MaltChainedException {
if (branches != null) {
for (DecisionTreeModel branch : branches.values()) {
branch.terminate();
}
branches = null;
}
if (leafModel != null) {
leafModel.terminate();
leafModel = null;
}
}
public void setParent(Model parent) {
this.parent = parent;
}
public Model getParent() {
return parent;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
public int getFrequency() {
return frequency;
}
public int getModelIndex() {
return modelIndex;
}
private LinkedList<FeatureFunction> createGainRatioSplitList() {
return divideFeatures;
}
}
|
package org.uct.cs.simplify.model;
import org.uct.cs.simplify.ply.header.PLYElement;
import org.uct.cs.simplify.ply.reader.PLYReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
public class ReliableBufferedVertexReader extends StreamingVertexReader implements AutoCloseable
{
protected final PLYReader reader;
protected final PLYElement vertexElement;
protected final VertexAttrMap vam;
protected final long start;
protected final int blockSize;
protected final ByteBuffer blockBuffer;
protected long index;
protected long count;
protected FileInputStream istream;
protected FileChannel inputChannel;
public ReliableBufferedVertexReader(PLYReader r) throws IOException
{
reader = r;
vertexElement = reader.getHeader().getElement("vertex");
count = vertexElement.getCount();
vam = new VertexAttrMap(this.vertexElement);
start = reader.getElementDimension("vertex").getOffset();
istream = new FileInputStream(reader.getFile());
inputChannel = istream.getChannel();
inputChannel.position(start);
blockSize = vertexElement.getItemSize();
blockBuffer = ByteBuffer.allocateDirect(blockSize);
blockBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
@Override
public boolean hasNext()
{
return index < count;
}
@Override
public Vertex next() throws IOException
{
Vertex v = new Vertex(0, 0, 0);
next(v);
return v;
}
@Override
public void next(Vertex v) throws IOException
{
inputChannel.read(blockBuffer);
blockBuffer.flip();
v.read(blockBuffer, vam);
index++;
blockBuffer.clear();
}
@Override
public long getCount()
{
return this.count;
}
@Override
public void close() throws IOException
{
this.istream.close();
}
@Override
public VertexAttrMap getVam()
{
return vam;
}
public void skipTo(long i) throws IOException
{
if (index == i) return;
this.index = i;
this.inputChannel.position(start + i * blockSize);
}
public long getIndex()
{
return index;
}
}
|
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import javax.swing.Action;
import javax.swing.ButtonModel;
import javax.swing.CellRendererPane;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicGraphicsUtils;
import org.jdesktop.swingx.graphics.GraphicsUtilities;
import org.jdesktop.swingx.graphics.PaintUtils;
import org.jdesktop.swingx.painter.AbstractPainter;
import org.jdesktop.swingx.painter.Painter;
import org.jdesktop.swingx.painter.PainterPaint;
/**
* <p>A {@link org.jdesktop.swingx.painter.Painter} enabled subclass of {@link javax.swing.JButton}.
* This class supports setting the foreground and background painters of the button separately.</p>
*
* <p>For example, if you wanted to blur <em>just the text</em> on the button, and let everything else be
* handled by the UI delegate for your look and feel, then you could:
* <pre><code>
* JXButton b = new JXButton("Execute");
* AbstractPainter fgPainter = (AbstractPainter)b.getForegroundPainter();
* StackBlurFilter filter = new StackBlurFilter();
* fgPainter.setFilters(filter);
* </code></pre>
*
* <p>If <em>either</em> the foreground painter or the background painter is set,
* then super.paintComponent() is not called. By setting both the foreground and background
* painters to null, you get <em>exactly</em> the same painting behavior as JButton.</p>
*
* @author rbair
* @author rah003
* @author Jan Stola
* @author Karl George Schaefer
*/
public class JXButton extends JButton implements BackgroundPaintable {
private class BackgroundButton extends JButton {
/**
* {@inheritDoc}
*/
@Override
public boolean isDefaultButton() {
return JXButton.this.isDefaultButton();
}
/**
* {@inheritDoc}
*/
@Override
public Icon getDisabledIcon() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Icon getDisabledSelectedIcon() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int getDisplayedMnemonicIndex() {
return -1;
}
/**
* {@inheritDoc}
*/
@Override
public int getHorizontalAlignment() {
return JXButton.this.getHorizontalAlignment();
}
/**
* {@inheritDoc}
*/
@Override
public int getHorizontalTextPosition() {
return JXButton.this.getHorizontalTextPosition();
}
/**
* {@inheritDoc}
*/
@Override
public Icon getIcon() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int getIconTextGap() {
return JXButton.this.getIconTextGap();
}
/**
* {@inheritDoc}
*/
@Override
public Insets getMargin() {
return JXButton.this.getMargin();
}
/**
* {@inheritDoc}
*/
@Override
public int getMnemonic() {
return -1;
}
/**
* {@inheritDoc}
*/
@Override
public ButtonModel getModel() {
return JXButton.this.getModel();
}
/**
* {@inheritDoc}
*/
@Override
public Icon getPressedIcon() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Icon getRolloverIcon() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Icon getRolloverSelectedIcon() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Icon getSelectedIcon() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public String getText() {
return "";
}
/**
* {@inheritDoc}
*/
@Override
public int getVerticalAlignment() {
return JXButton.this.getVerticalAlignment();
}
/**
* {@inheritDoc}
*/
@Override
public int getVerticalTextPosition() {
return JXButton.this.getVerticalTextPosition();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isBorderPainted() {
return JXButton.this.isBorderPainted();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isContentAreaFilled() {
return JXButton.this.isContentAreaFilled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isFocusPainted() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRolloverEnabled() {
return JXButton.this.isRolloverEnabled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isSelected() {
return JXButton.this.isSelected();
}
}
private class ForegroundButton extends JButton {
/**
* {@inheritDoc}
*/
@Override
public Color getForeground() {
if (fgPainter == null) {
return JXButton.this.getForeground();
}
return PaintUtils.setAlpha(JXButton.this.getForeground(), 0);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDefaultButton() {
return JXButton.this.isDefaultButton();
}
/**
* {@inheritDoc}
*/
@Override
public Icon getDisabledIcon() {
return JXButton.this.getDisabledIcon();
}
/**
* {@inheritDoc}
*/
@Override
public Icon getDisabledSelectedIcon() {
return JXButton.this.getDisabledSelectedIcon();
}
/**
* {@inheritDoc}
*/
@Override
public int getDisplayedMnemonicIndex() {
return JXButton.this.getDisplayedMnemonicIndex();
}
/**
* {@inheritDoc}
*/
@Override
public int getHorizontalAlignment() {
return JXButton.this.getHorizontalAlignment();
}
/**
* {@inheritDoc}
*/
@Override
public int getHorizontalTextPosition() {
return JXButton.this.getHorizontalTextPosition();
}
/**
* {@inheritDoc}
*/
@Override
public Icon getIcon() {
return JXButton.this.getIcon();
}
/**
* {@inheritDoc}
*/
@Override
public int getIconTextGap() {
return JXButton.this.getIconTextGap();
}
/**
* {@inheritDoc}
*/
@Override
public Insets getMargin() {
return JXButton.this.getMargin();
}
/**
* {@inheritDoc}
*/
@Override
public int getMnemonic() {
return JXButton.this.getMnemonic();
}
/**
* {@inheritDoc}
*/
@Override
public ButtonModel getModel() {
return JXButton.this.getModel();
}
/**
* {@inheritDoc}
*/
@Override
public Icon getPressedIcon() {
return JXButton.this.getPressedIcon();
}
/**
* {@inheritDoc}
*/
@Override
public Icon getRolloverIcon() {
return JXButton.this.getRolloverIcon();
}
/**
* {@inheritDoc}
*/
@Override
public Icon getRolloverSelectedIcon() {
return JXButton.this.getRolloverSelectedIcon();
}
/**
* {@inheritDoc}
*/
@Override
public Icon getSelectedIcon() {
return JXButton.this.getSelectedIcon();
}
/**
* {@inheritDoc}
*/
@Override
public String getText() {
return JXButton.this.getText();
}
/**
* {@inheritDoc}
*/
@Override
public int getVerticalAlignment() {
return JXButton.this.getVerticalAlignment();
}
/**
* {@inheritDoc}
*/
@Override
public int getVerticalTextPosition() {
return JXButton.this.getVerticalTextPosition();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isBorderPainted() {
return JXButton.this.isBorderPainted();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isContentAreaFilled() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasFocus() {
return JXButton.this.hasFocus();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isFocusPainted() {
return JXButton.this.isFocusPainted();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRolloverEnabled() {
return JXButton.this.isRolloverEnabled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isSelected() {
return JXButton.this.isSelected();
}
}
private ForegroundButton fgStamp;
private Painter fgPainter;
private PainterPaint fgPaint;
private BackgroundButton bgStamp;
private Painter bgPainter;
private boolean paintBorderInsets = true;
private Rectangle viewRect = new Rectangle();
private Rectangle textRect = new Rectangle();
private Rectangle iconRect = new Rectangle();
/**
* Creates a button with no set text or icon.
*/
public JXButton() {
init();
}
/**
* Creates a button with text.
*
* @param text
* the text of the button
*/
public JXButton(String text) {
super(text);
init();
}
/**
* Creates a button where properties are taken from the {@code Action} supplied.
*
* @param a
* the {@code Action} used to specify the new button
*/
public JXButton(Action a) {
super(a);
init();
}
/**
* Creates a button with an icon.
*
* @param icon
* the Icon image to display on the button
*/
public JXButton(Icon icon) {
super(icon);
init();
}
/**
* Creates a button with initial text and an icon.
*
* @param text
* the text of the button
* @param icon
* the Icon image to display on the button
*/
public JXButton(String text, Icon icon) {
super(text, icon);
init();
}
private void init() {
fgStamp = new ForegroundButton();
}
/**
* Sets the background color for this component by
*
* @param bg
* the desired background <code>Color</code>
* @see java.swing.JComponent#getBackground
* @see #setOpaque
*
* @beaninfo
* preferred: true
* bound: true
* attribute: visualUpdate true
* description: The background color of the component.
*/
@Override
public void setBackground(Color bg) {
super.setBackground(bg);
SwingXUtilities.installBackground(this, bg);
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public Painter getBackgroundPainter() {
return bgPainter;
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public void setBackgroundPainter(Painter p) {
Painter old = getBackgroundPainter();
this.bgPainter = p;
firePropertyChange("backgroundPainter", old, getBackgroundPainter());
repaint();
}
/**
* @return
*/
@SuppressWarnings("unchecked")
public Painter getForegroundPainter() {
return fgPainter;
}
@SuppressWarnings("unchecked")
public void setForegroundPainter(Painter p) {
Painter old = getForegroundPainter();
this.fgPainter = p;
if (fgPainter == null) {
fgPaint = null;
} else {
fgPaint = new PainterPaint(fgPainter, this);
if (bgStamp == null) {
bgStamp = new BackgroundButton();
}
}
firePropertyChange("foregroundPainter", old, getForegroundPainter());
repaint();
}
/**
* Returns true if the background painter should paint where the border is
* or false if it should only paint inside the border. This property is
* true by default. This property affects the width, height,
* and initial transform passed to the background painter.
*/
@Override
public boolean isPaintBorderInsets() {
return paintBorderInsets;
}
/**
* Sets the paintBorderInsets property.
* Set to true if the background painter should paint where the border is
* or false if it should only paint inside the border. This property is true by default.
* This property affects the width, height,
* and initial transform passed to the background painter.
*
* This is a bound property.
*/
@Override
public void setPaintBorderInsets(boolean paintBorderInsets) {
boolean old = this.isPaintBorderInsets();
this.paintBorderInsets = paintBorderInsets;
firePropertyChange("paintBorderInsets", old, isPaintBorderInsets());
}
/**
* {@inheritDoc}
*/
@Override
public Dimension getPreferredSize() {
if (getComponentCount() == 1 && getComponent(0) instanceof CellRendererPane) {
return BasicGraphicsUtils.getPreferredButtonSize(fgStamp, getIconTextGap());
}
return super.getPreferredSize();
}
/**
* {@inheritDoc}
*/
@Override
protected void paintComponent(Graphics g) {
if (fgPainter == null && bgPainter == null) {
super.paintComponent(g);
} else {
if (fgPainter == null) {
Graphics2D g2d = (Graphics2D) g.create();
try{
paintWithoutForegroundPainter(g2d);
} finally {
g2d.dispose();
}
} else if (fgPainter instanceof AbstractPainter && ((AbstractPainter<?>) fgPainter).getFilters().length > 0) {
paintWithForegroundPainterWithFilters(g);
} else {
Graphics2D g2d = (Graphics2D) g.create();
try {
paintWithForegroundPainterWithoutFilters(g2d);
} finally {
g2d.dispose();
}
}
}
}
private void paintWithoutForegroundPainter(Graphics2D g2d) {
if (bgPainter == null) {
SwingUtilities.paintComponent(g2d, bgStamp, this, 0, 0, getWidth(), getHeight());
} else {
SwingXUtilities.paintBackground(this, g2d);
}
SwingUtilities.paintComponent(g2d, fgStamp, this, 0, 0, getWidth(), getHeight());
}
private void paintWithForegroundPainterWithoutFilters(Graphics2D g2d) {
paintWithoutForegroundPainter(g2d);
if (getText() != null && !getText().isEmpty()) {
Insets i = getInsets();
viewRect.x = i.left;
viewRect.y = i.top;
viewRect.width = getWidth() - (i.right + viewRect.x);
viewRect.height = getHeight() - (i.bottom + viewRect.y);
textRect.x = textRect.y = textRect.width = textRect.height = 0;
iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;
// layout the text and icon
String text = SwingUtilities.layoutCompoundLabel(
this, g2d.getFontMetrics(), getText(), getIcon(),
getVerticalAlignment(), getHorizontalAlignment(),
getVerticalTextPosition(), getHorizontalTextPosition(),
viewRect, iconRect, textRect,
getText() == null ? 0 : getIconTextGap());
if (!isPaintBorderInsets()) {
g2d.translate(i.left, i.top);
}
g2d.setPaint(fgPaint);
BasicGraphicsUtils.drawStringUnderlineCharAt(g2d, text, getDisplayedMnemonicIndex(),
textRect.x, textRect.y + g2d.getFontMetrics().getAscent());
}
}
private void paintWithForegroundPainterWithFilters(Graphics g) {
BufferedImage im = GraphicsUtilities.createCompatibleImage(getWidth(), getHeight());
Graphics2D g2d = im.createGraphics();
paintWithForegroundPainterWithoutFilters(g2d);
for (BufferedImageOp filter : ((AbstractPainter<?>) fgPainter).getFilters()) {
im = filter.filter(im, null);
}
g.drawImage(im, 0, 0, this);
}
/**
* Notification from the <code>UIManager</code> that the L&F has changed.
* Replaces the current UI object with the latest version from the <code>UIManager</code>.
*
* @see javax.swing.JComponent#updateUI
*/
@Override
public void updateUI() {
super.updateUI();
if (bgStamp != null) {
bgStamp.updateUI();
}
if (fgStamp != null) {
fgStamp.updateUI();
}
}
}
|
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in th future.
package org.usfirst.frc330.Beachbot2013Java.subsystems;
import org.usfirst.frc330.Beachbot2013Java.RobotMap;
import org.usfirst.frc330.Beachbot2013Java.commands.*;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.CounterBase.EncodingType; import edu.wpi.first.wpilibj.Encoder.PIDSourceParameter;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class Chassis extends Subsystem {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
SpeedController leftDriveJaguar1 = RobotMap.chassisLeftDriveJaguar1;
SpeedController leftDriveJaguar2 = RobotMap.chassisLeftDriveJaguar2;
SpeedController rightDriveJaguar1 = RobotMap.chassisRightDriveJaguar1;
SpeedController rightDriveJaguar2 = RobotMap.chassisRightDriveJaguar2;
RobotDrive robotDrive = RobotMap.chassisRobotDrive;
Gyro gyro = RobotMap.chassisGyro;
Encoder leftDriveEncoder = RobotMap.chassisLeftDriveEncoder;
Encoder rightDriveEncoder = RobotMap.chassisRightDriveEncoder;
Compressor compressor = RobotMap.chassisCompressor;
DoubleSolenoid shiftSolenoid = RobotMap.chassisShiftSolenoid;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
setDefaultCommand(new TankDrive());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
public void tankDrive(Joystick leftJoystick, Joystick rightJoystick)
{
robotDrive.tankDrive(leftJoystick, rightJoystick, false);
}
public void tankDrive(double left, double right)
{
robotDrive.tankDrive(left, right, false);
}
public void shiftHigh()
{
shiftSolenoid.set(DoubleSolenoid.Value.kForward);
// System.out.println("Shifting into High");
}
public void shiftLow()
{
shiftSolenoid.set(DoubleSolenoid.Value.kReverse);
// System.out.println("Shifting into Low");
}
}
|
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
package org.opennms.netmgt.model;
/**
* Represents the status of a node, interface or services
* @author brozow
*/
public class PollStatus {
/**
* Status of the pollable object.
*/
//public static final PollStatus STATUS_UP = new PollStatus(PollStatus.SERVICE_AVAILABLE, "Up");
// public static final PollStatus STATUS_DOWN = new PollStatus(PollStatus.SERVICE_UNAVAILABLE, "Down");
// public static final PollStatus STATUS_UNRESPONSIVE = new PollStatus(PollStatus.SERVICE_UNRESPONSIVE, "Unresponsive");
// public static final PollStatus STATUS_UNKNOWN = new PollStatus(PollStatus.SERVICE_UNKNOWN, "Unknown");
long m_timestamp = System.currentTimeMillis();
int m_statusCode;
String m_reason;
long m_responseTime = -1L;
/**
* <P>
* The constant that defines a service that is up but is most likely
* suffering due to excessive load or latency issues and because of that has
* not responded within the configured timeout period.
* </P>
*/
public static final int SERVICE_UNRESPONSIVE = 3;
/**
* <P>
* The constant that defines a service that is not working normally and
* should be scheduled using the downtime models.
* </P>
*/
public static final int SERVICE_UNAVAILABLE = 2;
/**
* <P>
* The constant that defines a service as being in a normal state. If this
* is returned by the poll() method then the framework will re-schedule the
* service for its next poll using the standard uptime interval
* </P>
*/
public static final int SERVICE_AVAILABLE = 1;
/**
* The constant the defines a status is unknown. Used mostly internally
*/
public static final int SERVICE_UNKNOWN = 0;
private static final String[] s_statusNames = {
"Unknown",
"Up",
"Down",
"Unresponsive"
};
public static PollStatus decode(String statusName) {
for (int statusCode = 0; statusCode < s_statusNames.length; statusCode++) {
if (s_statusNames[statusCode].equals(statusName)) {
return new PollStatus(statusCode);
}
}
return new PollStatus(SERVICE_UNKNOWN);
}
public static PollStatus decode(String statusName, String reason) {
return decode(statusName, reason, -1L);
}
public static PollStatus decode(String statusName, String reason, long responseTime) {
PollStatus result = decode(statusName);
result.setReason(reason);
result.setResponseTime(responseTime);
return result;
}
public static PollStatus get(int status, String reason) {
return get(status, reason, -1L);
}
public static PollStatus get(int status, String reason, long responseTime) {
return new PollStatus(status, reason, responseTime);
}
private PollStatus(int statusCode) {
this(statusCode, null, -1L);
}
private PollStatus(int statusCode, String reason, long responseTime) {
m_statusCode = statusCode;
m_reason = reason;
m_responseTime = responseTime;
}
public static PollStatus up() {
return up(-1L);
}
public static PollStatus up(long responseTime) {
return available(responseTime);
}
public static PollStatus available() {
return available(-1L);
}
public static PollStatus available(long responseTime) {
return new PollStatus(SERVICE_AVAILABLE, null, responseTime);
}
public static PollStatus unknown() {
return new PollStatus(SERVICE_UNKNOWN, null, -1L);
}
public static PollStatus unresponsive() {
return unresponsive(null);
}
public static PollStatus unresponsive(String reason) {
return new PollStatus(SERVICE_UNRESPONSIVE, reason, -1L);
}
public static PollStatus down() {
return down(null);
}
public static PollStatus unavailable() {
return unavailable(null);
}
public static PollStatus down(String reason) {
return unavailable(reason);
}
public static PollStatus unavailable(String reason) {
return new PollStatus(SERVICE_UNAVAILABLE, reason, -1L);
}
public boolean equals(Object o) {
if (o instanceof PollStatus) {
return m_statusCode == ((PollStatus)o).m_statusCode;
}
return false;
}
public int hashCode() {
return m_statusCode;
}
public boolean isUp() {
return !isDown();
}
public boolean isAvailable() {
return this.m_statusCode == SERVICE_AVAILABLE;
}
public boolean isUnresponsive() {
return this.m_statusCode == SERVICE_UNRESPONSIVE;
}
public boolean isUnavailable() {
return this.m_statusCode == SERVICE_UNAVAILABLE;
}
public boolean isDown() {
return this.m_statusCode == SERVICE_UNAVAILABLE;
}
public String toString() {
return getStatusName();
}
public String getReason() {
return m_reason;
}
public void setReason(String reason) {
m_reason = reason;
}
public long getResponseTime() {
return m_responseTime;
}
public void setResponseTime(long responseTime) {
m_responseTime = responseTime;
}
public int getStatusCode() {
return m_statusCode;
}
public String getStatusName() {
return s_statusNames[m_statusCode];
}
}
|
package org.xbill.DNS;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* The Response from a query to Cache.lookupRecords() or Zone.findRecords()
* @see Cache
* @see Zone
*
* @author Brian Wellington
*/
public class SetResponse {
/**
* The Cache contains no information about the requested name/type
*/
static final byte UNKNOWN = 0;
/**
* The Zone does not contain the requested name, or the Cache has
* determined that the name does not exist.
*/
static final byte NXDOMAIN = 1;
/**
* The Zone contains the name, but no data of the requested type,
* or the Cache has determined that the name exists and has no data
* of the requested type.
*/
static final byte NXRRSET = 2;
/**
* A delegation enclosing the requested name was found.
*/
static final byte DELEGATION = 3;
/**
* The Cache/Zone found a CNAME when looking for the name.
* @see CNAMERecord
*/
static final byte CNAME = 4;
/**
* The Cache/Zone found a DNAME when looking for the name.
* @see CNAMERecord
*/
static final byte DNAME = 5;
/**
* The Cache/Zone has successfully answered the question for the
* requested name/type/class.
*/
static final byte SUCCESSFUL = 6;
private byte type;
private Object data;
private
SetResponse() {}
SetResponse(byte _type, Object _data) {
type = _type;
data = _data;
}
SetResponse(byte _type) {
this(_type, null);
}
/** Changes the value of a SetResponse */
void
set(byte _type, Object _data) {
type = _type;
data = _data;
}
void
addRRset(RRset rrset) {
if (data == null)
data = new Vector();
Vector v = (Vector) data;
v.addElement(rrset);
}
void
addNS(RRset nsset) {
data = nsset;
}
void
addCNAME(CNAMERecord cname) {
data = cname;
}
void
addDNAME(DNAMERecord dname) {
data = dname;
}
/** Is the answer to the query unknown? */
public boolean
isUnknown() {
return (type == UNKNOWN);
}
/** Is the answer to the query that the name does not exist? */
public boolean
isNXDOMAIN() {
return (type == NXDOMAIN);
}
/** Is the answer to the query that the name exists, but the type does not? */
public boolean
isNXRRSET() {
return (type == NXRRSET);
}
/** Is the result of the lookup that the name is below a delegation? */
public boolean
isDelegation() {
return (type == DELEGATION);
}
/** Is the result of the lookup a CNAME? */
public boolean
isCNAME() {
return (type == CNAME);
}
/** Is the result of the lookup a DNAME? */
public boolean
isDNAME() {
return (type == DNAME);
}
/** Was the query successful? */
public boolean
isSuccessful() {
return (type == SUCCESSFUL);
}
/** If the query was successful, return the answers */
public RRset []
answers() {
if (type != SUCCESSFUL)
return null;
Vector v = (Vector) data;
RRset [] rrsets = new RRset[v.size()];
for (int i = 0; i < rrsets.length; i++)
rrsets[i] = (RRset) v.elementAt(i);
return rrsets;
}
/**
* If the query encountered a CNAME, return it.
*/
public CNAMERecord
getCNAME() {
return (CNAMERecord) data;
}
/**
* If the query encountered a DNAME, return it.
*/
public DNAMERecord
getDNAME() {
return (DNAMERecord) data;
}
/**
* If the query hit a delegation point, return the NS set.
*/
public RRset
getNS() {
return (RRset) data;
}
/** Prints the value of the SetResponse */
public String
toString() {
switch (type) {
case UNKNOWN: return "unknown";
case NXDOMAIN: return "NXDOMAIN";
case NXRRSET: return "NXRRSET";
case DELEGATION: return "delegation: " + data;
case CNAME: return "CNAME: " + data;
case DNAME: return "DNAME: " + data;
case SUCCESSFUL: return "successful";
default: return null;
}
}
}
|
package uk.ac.cam.ch.wwmm.opsin;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
/**
* Provides valency checking features and a lookup on the possible valencies
* for an atom given its element and charge
*
* Also used to perform a final check on the output of OPSIN, to reject interpretations
* that result in hypervalent structures due to incorrect names or misinterpreted names
*
* @author ptc24
* @author dl387
*
*/
class ValencyChecker {
/** used to decide on the likely valency state*/
private static final Map<ChemEl, Integer> expectedDefaultValency = new EnumMap<ChemEl, Integer>(ChemEl.class);
/** used to decide whether an atom has spare valency in a ring, these are the same as specified in the Hantzch-Widman system */
private static final Map<ChemEl, Integer> valencyInHW = new EnumMap<ChemEl, Integer>(ChemEl.class);
/** used to decide on the likely valency state */
private static final Map<ChemEl, Map<Integer, Integer[]>> possibleStableValencies = new EnumMap<ChemEl, Map<Integer, Integer[]>>(ChemEl.class);
static {
expectedDefaultValency.put(ChemEl.B, 3);
expectedDefaultValency.put(ChemEl.Al, 3);
expectedDefaultValency.put(ChemEl.In, 3);
expectedDefaultValency.put(ChemEl.Ga, 3);
expectedDefaultValency.put(ChemEl.Tl, 3);
expectedDefaultValency.put(ChemEl.C, 4);
expectedDefaultValency.put(ChemEl.Si, 4);
expectedDefaultValency.put(ChemEl.Ge, 4);
expectedDefaultValency.put(ChemEl.Sn, 4);
expectedDefaultValency.put(ChemEl.Pb, 4);
expectedDefaultValency.put(ChemEl.N, 3);
expectedDefaultValency.put(ChemEl.P, 3);
expectedDefaultValency.put(ChemEl.As, 3);
expectedDefaultValency.put(ChemEl.Sb, 3);
expectedDefaultValency.put(ChemEl.Bi, 3);
expectedDefaultValency.put(ChemEl.O, 2);
expectedDefaultValency.put(ChemEl.S, 2);
expectedDefaultValency.put(ChemEl.Se, 2);
expectedDefaultValency.put(ChemEl.Te, 2);
expectedDefaultValency.put(ChemEl.Po, 2);
expectedDefaultValency.put(ChemEl.F, 1);
expectedDefaultValency.put(ChemEl.Cl, 1);
expectedDefaultValency.put(ChemEl.Br, 1);
expectedDefaultValency.put(ChemEl.I, 1);
expectedDefaultValency.put(ChemEl.At, 1);
//in order of priority in the HW system
valencyInHW.put(ChemEl.F, 1);
valencyInHW.put(ChemEl.Cl, 1);
valencyInHW.put(ChemEl.Br, 1);
valencyInHW.put(ChemEl.I, 1);
valencyInHW.put(ChemEl.O, 2);
valencyInHW.put(ChemEl.S, 2);
valencyInHW.put(ChemEl.Se, 2);
valencyInHW.put(ChemEl.Te, 2);
valencyInHW.put(ChemEl.N, 3);
valencyInHW.put(ChemEl.P, 3);
valencyInHW.put(ChemEl.As, 3);
valencyInHW.put(ChemEl.Sb, 3);
valencyInHW.put(ChemEl.Bi, 3);
valencyInHW.put(ChemEl.Si, 4);
valencyInHW.put(ChemEl.Ge, 4);
valencyInHW.put(ChemEl.Sn, 4);
valencyInHW.put(ChemEl.Pb, 4);
valencyInHW.put(ChemEl.B, 3);
valencyInHW.put(ChemEl.Al, 3);
valencyInHW.put(ChemEl.Ga, 3);
valencyInHW.put(ChemEl.In, 3);
valencyInHW.put(ChemEl.Tl, 3);
valencyInHW.put(ChemEl.Hg, 2);
possibleStableValencies.put(ChemEl.H, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.He, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Li, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Be, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.B, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.C, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.N, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.O, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.F, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Ne, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Na, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Mg, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Al, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Si, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.P, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.S, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Cl, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Ar, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.K, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Ca, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Ga, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Ge, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.As, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Se, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Br, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Kr, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Rb, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Sr, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.In, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Sn, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Sb, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Te, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.I, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Xe, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Cs, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Ba, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Tl, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Pb, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Bi, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Po, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.At, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Rn, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Fr, new HashMap<Integer, Integer[]>());
possibleStableValencies.put(ChemEl.Ra, new HashMap<Integer, Integer[]>());
possibleStableValencies.get(ChemEl.H).put(0, new Integer[]{1});
possibleStableValencies.get(ChemEl.He).put(0, new Integer[]{0});
possibleStableValencies.get(ChemEl.Li).put(0, new Integer[]{1});
possibleStableValencies.get(ChemEl.Be).put(0, new Integer[]{2});
possibleStableValencies.get(ChemEl.B).put(0, new Integer[]{3});
possibleStableValencies.get(ChemEl.C).put(0, new Integer[]{4});
possibleStableValencies.get(ChemEl.N).put(0, new Integer[]{3});
possibleStableValencies.get(ChemEl.O).put(0, new Integer[]{2});
possibleStableValencies.get(ChemEl.F).put(0, new Integer[]{1});
possibleStableValencies.get(ChemEl.Ne).put(0, new Integer[]{0});
possibleStableValencies.get(ChemEl.Na).put(0, new Integer[]{1});
possibleStableValencies.get(ChemEl.Mg).put(0, new Integer[]{2});
possibleStableValencies.get(ChemEl.Al).put(0, new Integer[]{3});
possibleStableValencies.get(ChemEl.Si).put(0, new Integer[]{4});
possibleStableValencies.get(ChemEl.P).put(0, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.S).put(0, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.Cl).put(0, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.Ar).put(0, new Integer[]{0});
possibleStableValencies.get(ChemEl.K).put(0, new Integer[]{1});
possibleStableValencies.get(ChemEl.Ca).put(0, new Integer[]{2});
possibleStableValencies.get(ChemEl.Ga).put(0, new Integer[]{3});
possibleStableValencies.get(ChemEl.Ge).put(0, new Integer[]{4});
possibleStableValencies.get(ChemEl.As).put(0, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Se).put(0, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.Br).put(0, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.Kr).put(0, new Integer[]{0,2});
possibleStableValencies.get(ChemEl.Rb).put(0, new Integer[]{1});
possibleStableValencies.get(ChemEl.Sr).put(0, new Integer[]{2});
possibleStableValencies.get(ChemEl.In).put(0, new Integer[]{3});
possibleStableValencies.get(ChemEl.Sn).put(0, new Integer[]{2,4});
possibleStableValencies.get(ChemEl.Sb).put(0, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Te).put(0, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.I).put(0, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.Xe).put(0, new Integer[]{0,2,4,6,8});
possibleStableValencies.get(ChemEl.Cs).put(0, new Integer[]{1});
possibleStableValencies.get(ChemEl.Ba).put(0, new Integer[]{2});
possibleStableValencies.get(ChemEl.Tl).put(0, new Integer[]{1,3});
possibleStableValencies.get(ChemEl.Pb).put(0, new Integer[]{2,4});
possibleStableValencies.get(ChemEl.Bi).put(0, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Po).put(0, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.At).put(0, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.Rn).put(0, new Integer[]{0,2,4,6,8});
possibleStableValencies.get(ChemEl.Fr).put(0, new Integer[]{1});
possibleStableValencies.get(ChemEl.Ra).put(0, new Integer[]{2});
possibleStableValencies.get(ChemEl.H).put(1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Li).put(1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Be).put(1, new Integer[]{1});
possibleStableValencies.get(ChemEl.Be).put(2, new Integer[]{0});
possibleStableValencies.get(ChemEl.B).put(2, new Integer[]{1});
possibleStableValencies.get(ChemEl.B).put(1, new Integer[]{2});
possibleStableValencies.get(ChemEl.B).put(-1, new Integer[]{4});
possibleStableValencies.get(ChemEl.B).put(-2, new Integer[]{3});
possibleStableValencies.get(ChemEl.C).put(2, new Integer[]{2});
possibleStableValencies.get(ChemEl.C).put(1, new Integer[]{3});
possibleStableValencies.get(ChemEl.C).put(-1, new Integer[]{3});
possibleStableValencies.get(ChemEl.C).put(-2, new Integer[]{2});
possibleStableValencies.get(ChemEl.N).put(2, new Integer[]{3});
possibleStableValencies.get(ChemEl.N).put(1, new Integer[]{4});
possibleStableValencies.get(ChemEl.N).put(-1, new Integer[]{2});
possibleStableValencies.get(ChemEl.N).put(-2, new Integer[]{1});
possibleStableValencies.get(ChemEl.O).put(1, new Integer[]{4});
possibleStableValencies.get(ChemEl.O).put(1, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.O).put(-1, new Integer[]{1});
possibleStableValencies.get(ChemEl.O).put(-2, new Integer[]{0});
possibleStableValencies.get(ChemEl.F).put(2, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.F).put(1, new Integer[]{2});
possibleStableValencies.get(ChemEl.F).put(-1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Na).put(1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Na).put(-1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Mg).put(2, new Integer[]{0});
possibleStableValencies.get(ChemEl.Al).put(3, new Integer[]{0});
possibleStableValencies.get(ChemEl.Al).put(2, new Integer[]{1});
possibleStableValencies.get(ChemEl.Al).put(1, new Integer[]{2});
possibleStableValencies.get(ChemEl.Al).put(-1, new Integer[]{4});
possibleStableValencies.get(ChemEl.Al).put(-2, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Si).put(2, new Integer[]{2});
possibleStableValencies.get(ChemEl.Si).put(1, new Integer[]{3});
possibleStableValencies.get(ChemEl.Si).put(-1, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Si).put(-2, new Integer[]{2});
possibleStableValencies.get(ChemEl.P).put(2, new Integer[]{3});
possibleStableValencies.get(ChemEl.P).put(1, new Integer[]{4});
possibleStableValencies.get(ChemEl.P).put(-1, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.P).put(-2, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.S).put(2, new Integer[]{4});
possibleStableValencies.get(ChemEl.S).put(1, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.S).put(-1, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.S).put(-2, new Integer[]{0});
possibleStableValencies.get(ChemEl.Cl).put(2, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Cl).put(1, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.Cl).put(-1, new Integer[]{0});
possibleStableValencies.get(ChemEl.K).put(1, new Integer[]{0});
possibleStableValencies.get(ChemEl.K).put(-1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Ca).put(2, new Integer[]{0});
possibleStableValencies.get(ChemEl.Ca).put(1, new Integer[]{1});
possibleStableValencies.get(ChemEl.Ga).put(3, new Integer[]{0});
possibleStableValencies.get(ChemEl.Ga).put(2, new Integer[]{1});
possibleStableValencies.get(ChemEl.Ga).put(1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Ga).put(-1, new Integer[]{4});
possibleStableValencies.get(ChemEl.Ga).put(-2, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Ge).put(4, new Integer[]{0});
possibleStableValencies.get(ChemEl.Ge).put(1, new Integer[]{3});
possibleStableValencies.get(ChemEl.Ge).put(-1, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Ge).put(-2, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.As).put(2, new Integer[]{3});
possibleStableValencies.get(ChemEl.As).put(1, new Integer[]{4});
possibleStableValencies.get(ChemEl.As).put(-1, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.As).put(-2, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.As).put(-3, new Integer[]{0});
possibleStableValencies.get(ChemEl.Se).put(2, new Integer[]{4});
possibleStableValencies.get(ChemEl.Se).put(1, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Se).put(-1, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.Se).put(-2, new Integer[]{0});
possibleStableValencies.get(ChemEl.Br).put(2, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Br).put(1, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.Br).put(-1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Rb).put(1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Rb).put(-1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Sr).put(2, new Integer[]{0});
possibleStableValencies.get(ChemEl.Sr).put(1, new Integer[]{1});
possibleStableValencies.get(ChemEl.In).put(3, new Integer[]{0});
possibleStableValencies.get(ChemEl.In).put(2, new Integer[]{1});
possibleStableValencies.get(ChemEl.In).put(1, new Integer[]{0});
possibleStableValencies.get(ChemEl.In).put(-1, new Integer[]{2,4});
possibleStableValencies.get(ChemEl.In).put(-2, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Sn).put(4, new Integer[]{0});
possibleStableValencies.get(ChemEl.Sn).put(2, new Integer[]{0});
possibleStableValencies.get(ChemEl.Sn).put(1, new Integer[]{3});
possibleStableValencies.get(ChemEl.Sn).put(-1, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Sn).put(-2, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.Sb).put(3, new Integer[]{0});
possibleStableValencies.get(ChemEl.Sb).put(2, new Integer[]{3});
possibleStableValencies.get(ChemEl.Sb).put(1, new Integer[]{2,4});
possibleStableValencies.get(ChemEl.Sb).put(-1, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.Sb).put(-2, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.Te).put(2, new Integer[]{2,4});
possibleStableValencies.get(ChemEl.Te).put(1, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Te).put(-1, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.Te).put(-2, new Integer[]{0});
possibleStableValencies.get(ChemEl.I).put(2, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.I).put(1, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.I).put(-1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Cs).put(1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Cs).put(-1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Ba).put(2, new Integer[]{0});
possibleStableValencies.get(ChemEl.Ba).put(1, new Integer[]{1});
possibleStableValencies.get(ChemEl.Pb).put(2, new Integer[]{0});
possibleStableValencies.get(ChemEl.Pb).put(1, new Integer[]{3});
possibleStableValencies.get(ChemEl.Pb).put(-1, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.Pb).put(-2, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.Bi).put(3, new Integer[]{0});
possibleStableValencies.get(ChemEl.Bi).put(2, new Integer[]{3});
possibleStableValencies.get(ChemEl.Bi).put(1, new Integer[]{2,4});
possibleStableValencies.get(ChemEl.Bi).put(-1, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.Bi).put(-2, new Integer[]{1,3,5,7});
possibleStableValencies.get(ChemEl.At).put(2, new Integer[]{3,5});
possibleStableValencies.get(ChemEl.At).put(1, new Integer[]{2,4,6});
possibleStableValencies.get(ChemEl.At).put(-1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Fr).put(1, new Integer[]{0});
possibleStableValencies.get(ChemEl.Ra).put(2, new Integer[]{0});
possibleStableValencies.get(ChemEl.Ra).put(1, new Integer[]{1});
}
/**
* Given a chemical element (e.g. Na) and charge (e.g. 1) returns the highest stable valency that OPSIN knows is possible
* If for the particular combination of chemical element and charge the highest stable valency is not known null is returned
* @param chemEl
* @param charge
* @return
*/
static Integer getMaximumValency(ChemEl chemEl, int charge) {
Map<Integer, Integer[]> possibleStableValenciesForEl = possibleStableValencies.get(chemEl);
if (possibleStableValenciesForEl != null){
Integer[] possibleStableValenciesForElAndCharge = possibleStableValenciesForEl.get(charge);
if (possibleStableValenciesForElAndCharge != null){
return possibleStableValenciesForElAndCharge[possibleStableValenciesForElAndCharge.length - 1];
}
}
return null;
}
/**
* Return the lambda convention derived valency if set otherwise returns the same as {@link #getMaximumValency(ChemEl, int)}
* Returns null if the maximum valency is not known
* @param a
* @return
*/
static Integer getMaximumValency(Atom a) {
Integer maxVal;
if (a.getLambdaConventionValency() != null) {
maxVal = a.getLambdaConventionValency() + a.getProtonsExplicitlyAddedOrRemoved();
}
else{
maxVal = getMaximumValency(a.getElement(), a.getCharge());
}
return maxVal;
}
/**
* Checks whether the total incoming valency to an atom exceeds its expected valency
* outValency e.g. on radicals is taken into account
* @param a
* @return
*/
static boolean checkValency(Atom a) {
int valency = a.getIncomingValency() + a.getOutValency();
Integer maxVal = getMaximumValency(a);
if(maxVal == null) {
return true;
}
return valency <= maxVal;
}
/** Check whether valency is available on the atom to form a bond of the given order.
* spareValency and outValency are not taken into account.
* @param a atom you are interested in
* @param bondOrder order of bond required
* @return
*/
static boolean checkValencyAvailableForBond(Atom a, int bondOrder) {
int valency = a.getIncomingValency() + bondOrder;
Integer maxVal = getMaximumValency(a);
if(maxVal == null) {
return true;
}
return valency <= maxVal;
}
/** Check whether changing to a heteroatom will result in valency being exceeded
* spareValency and outValency is taken into account
* @param a atom you are interested in
* @param heteroatom atom which will be replacing it
* @return
*/
static boolean checkValencyAvailableForReplacementByHeteroatom(Atom a, Atom heteroatom) {
int valency =a.getIncomingValency();
valency +=a.hasSpareValency() ? 1 : 0;
valency +=a.getOutValency();
Integer maxValOfHeteroAtom = getMaximumValency(heteroatom.getElement(), heteroatom.getCharge());
return maxValOfHeteroAtom == null || valency <= maxValOfHeteroAtom;
}
/**
* Returns the default valency of an element when uncharged or null if unknown
* @param chemlEl
* @return
*/
static Integer getDefaultValency(ChemEl chemlEl) {
return expectedDefaultValency.get(chemlEl);
}
/**
* Returns the valency of an element in the HW system (useful for deciding whether something should have double bonds in a ring) or null if unknown
* Note that the HW system makes no claim about valency when the atom is charged
* @param chemEl
* @return
*/
static Integer getHWValency(ChemEl chemEl) {
return valencyInHW.get(chemEl);
}
/**
* Returns the maximum valency of an element with a given charge or null if unknown
* @param chemEl
* @param charge
* @return
*/
static Integer[] getPossibleValencies(ChemEl chemEl, int charge) {
Map<Integer, Integer[]> possibleStableValenciesForEl = possibleStableValencies.get(chemEl);
if (possibleStableValenciesForEl == null){
return null;
}
return possibleStableValenciesForEl.get(charge);
}
}
|
package com.client.pygmy.entity;
import com.lib.pygmy.EntityType;
import com.lib.pygmy.GameLevel;
import com.lib.pygmy.GameMove;
import com.lib.pygmy.PygmyGameEntity;
import com.lib.pygmy.Tile;
import com.lib.pygmy.util.Point;
public class Pawn extends PygmyGameEntity {
public Pawn(GameLevel level, String playerId, EntityType type, Point p) {
super(level, playerId, type, p);
}
@Override
public void oneStepMoveAddedBehavior() {
}
@Override
public boolean isLegalMove(GameMove move) {
Tile src = getCurrentTile();
Tile dst = move.getDestination();
return (dst.getPosition().y - src.getPosition().y) == 0;
}
}
|
package org.traccar.protocol;
import org.junit.Test;
import org.traccar.ProtocolTest;
public class GlobalSatProtocolDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
GlobalSatProtocolDecoder decoder = new GlobalSatProtocolDecoder(new GlobalSatProtocol());
verifyNull(decoder, text(
"GSh,131826789036289,3,M,ea04*3d"));
decoder.setFormat0("SORPZAB27GHKLMN*U!");
verifyPosition(decoder, text(
"GSr,011412001878820,4,5,00,,1,250114,105316,E00610.2925,N4612.1824,0,0.02,0,1,0.0,64*51!"));
verifyPosition(decoder, text(
"GSr,357938020310710,,4,04,,1,170315,060657,E00000.0000,N0000.0000,148,0.00,0,0,0.0,11991mV*6c!"));
decoder.setFormat0("TSPRXAB27GHKLMnaicz*U!");
verifyPosition(decoder, text(
"GSr,1,135785412249986,01,I,EA02,3,230410,153318,E12129.2839,N2459.8570,0,1.17,212,8,1.0,12.3V*55"));
verifyPosition(decoder, text(
"GSr,GTR-128,012896009148443,0040,5,0080,3,190813,185812,W11203.3661,N3330.2104,344,0.24,78,9,0.8,60%,0,0,12,\"310,410,0bdd,050d,02,21\",\"310,410,0bdd,0639,24,7\"*79"));
verifyPosition(decoder, text(
"$355632004245866,1,1,040202,093633,E12129.2252,N2459.8891,00161,0.0100,147,07,2.4"));
verifyPosition(decoder, text(
"$355632000959420,9,3,160413,230536,E03738.4906,N5546.3148,00000,0.3870,147,07,2.4"));
verifyPosition(decoder, text(
"$353681041893264,9,3,240913,100833,E08513.0122,N5232.9395,181.3,22.02,251.30,9,1.00"));
decoder.setFormat0("SPRXYAB27GHKLMmnaefghiotuvwb*U!");
verifyPosition(decoder, text(
"GSr,GTR-128,013227006963064,0080,1,a080,3,190615,163816,W07407.7134,N0440.8601,2579,0.01,130,12,0.7,11540mV,0,77,14,\"732,123,0744,2fc1,41,23\",\"732,123,0744,2dfe,05,28\",\"732,123,0744,272a,15,21\",\"732,123,0744,2f02,27,23\"*3b!"));
verifyPosition(decoder, text(
"$80050377796567,0,13,281015,173437,E08513.28616,N5232.85432,222.3,0.526,,07*37"),
position("2015-10-28 17:34:37.000", true, 52.54757, 85.22144));
verifyPosition(decoder, text(
"$80050377796567,0,18,281015,191919,E08513.93290,N5232.42141,193.4,37.647,305.40,07*37"),
position("2015-10-28 19:19:19.000", true, 52.54036, 85.23222));
}
}
|
/*
* $Id: TestXmlMetadataExtractor.java,v 1.6 2012-03-12 04:30:17 pgust Exp $
*/
package org.lockss.extractor;
import java.io.*;
import java.util.*;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import junit.framework.*;
import org.lockss.test.*;
import org.lockss.util.*;
import org.lockss.daemon.*;
/** Tests for both SimpleXmlMetadataExtractor and SaxMetadataExtractor */
public abstract class TestXmlMetadataExtractor
extends FileMetadataExtractorTestCase {
static Logger log = Logger.getLogger("TestXmlMetadataExtractor");
// Variant to test SaxMetadataExtractor
public static class TestSax extends TestXmlMetadataExtractor {
public FileMetadataExtractorFactory getFactory() {
return new FileMetadataExtractorFactory() {
public FileMetadataExtractor
createFileMetadataExtractor(MetadataTarget target, String mimeType)
throws PluginException {
return new SaxMetadataExtractor(Arrays.asList(TEST_TAGS));
}};
}
// SaxMetadataExtractor ignores unmatched tags
public void testNestedTag() throws Exception {
String text =
"<root>" +
"<FirstTag>FirstValue</FirstTag>" +
"<SecondTag>SecondValue" +
"<ThirdTag>ThirdValue</ThirdTag>" +
"MoreValueSecond</SecondTag>" +
"</root>";
assertRawEquals(ListUtil.list("firsttag", "FirstValue",
"thirdtag", "ThirdValue"),
extractFrom(text));
}
}
// Variant to test SimpleXmlMetadataExtractor
public static class TestSimple extends TestXmlMetadataExtractor {
public FileMetadataExtractorFactory getFactory() {
return new FileMetadataExtractorFactory() {
public FileMetadataExtractor
createFileMetadataExtractor(MetadataTarget target, String mimeType)
throws PluginException {
return new SimpleXmlMetadataExtractor(Arrays.asList(TEST_TAGS));
}};
}
// SimpleXmlMetadataExtractor handles nested tags inelegantly
public void testNestedTag() throws Exception {
String text =
"<root>" +
"<FirstTag>FirstValue</FirstTag>" +
"<SecondTag>SecondValue" +
"<ThirdTag>ThirdValue</ThirdTag>" +
"MoreValueSecond</SecondTag>" +
"</root>";
assertRawEquals(ListUtil.list("firsttag", "FirstValue",
"secondtag", "SecondValue<ThirdTag>ThirdValue</ThirdTag>MoreValueSecond",
"thirdtag", "ThirdValue"),
extractFrom(text));
}
}
/**
* This test class transforms the old-style raw tags into XPath equivalents
* that locate a node anywhere in the DOM tree.
*
* @author phil
*/
public static class MyXmlMetadataExtractor extends XmlDomMetadataExtractor {
public MyXmlMetadataExtractor(Collection<String> keys)
throws XPathExpressionException {
super(keys.size());
int i = 0;
XPath xpath = XPathFactory.newInstance().newXPath();
for (String key : keys) {
xpathKeys[i] = key;
xpathExprs[i] = xpath.compile("//" + key);
nodeValues[i] = TEXT_VALUE;
i++;
}
}
}
// Variant to test XmlMetadataExtractor which uses XPath expressions
public static class TestXPath extends TestXmlMetadataExtractor {
public FileMetadataExtractorFactory getFactory() {
return new FileMetadataExtractorFactory() {
public FileMetadataExtractor
createFileMetadataExtractor(MetadataTarget target, String mimeType)
throws PluginException {
try {
return new MyXmlMetadataExtractor(Arrays.asList(TEST_TAGS));
} catch (XPathExpressionException ex) {
PluginException ex2 =
new PluginException("Error parsing XPath expressions");
ex2.initCause(ex);
throw ex2;
}
}
};
}
public void testNestedTag() throws Exception {
String text =
"<root>" +
"<FirstTag>FirstValue</FirstTag>" +
"<SecondTag>SecondValue" +
"<ThirdTag>ThirdValue</ThirdTag>" +
"MoreValueSecond</SecondTag>" +
"</root>";
// The XML Document parser resolves this differently
assertRawEquals(ListUtil.list("FirstTag", "FirstValue",
"SecondTag", "SecondValueThirdValueMoreValueSecond",
"ThirdTag", "ThirdValue"),
extractFrom(text));
}
}
public static Test suite() {
return variantSuites(new Class[] {
TestSax.class,
TestSimple.class,
TestXPath.class
});
}
public String getMimeType() {
return MIME_TYPE_XML;
}
public void testSingleTag() throws Exception {
assertRawEquals("FirstTag", "FirstValue",
extractFrom("<FirstTag>FirstValue</FirstTag>"));
assertRawEquals("SecondTag", "SecondValue",
extractFrom("<SecondTag>SecondValue</SecondTag>"));
}
public void testSingleTagNoContent() throws Exception {
assertRawEmpty(extractFrom("<FirstTag></FirstTag>"));
}
public void testSingleTagUnmatched() throws Exception {
assertRawEmpty(extractFrom("<FirstTag>FirstValue"));
assertRawEmpty(extractFrom("FirstValue</FirstTag>"));
}
public void testSingleTagMalformed() throws Exception {
assertRawEmpty(extractFrom("<FirstTag>FirstValue"));
assertRawEmpty(extractFrom("<FirstTag FirstValue</FirstTag>"));
// SAX parses this although there is the trailing space
// in the opening tag:
// assertRawEmpty("<FirstTag >FirstValue</FirstTag>");
assertRawEmpty(extractFrom("<FirstTag>FirstValue</FirstTag"));
// SAX parses this although there is the trailing space
// in the closing tag:
// assertRawEmpty(extractFrom("<FirstTag>FirstValue</FirstTag >"));
}
public void testSingleTagIgnoreCase() throws Exception {
assertRawEquals("FirstTag", "FirstValue",
extractFrom("<FirstTag>FirstValue</FirstTag>"));
}
public void testMultipleTag() throws Exception {
String text =
"<root>" +
"<FirstTag>FirstValue</FirstTag>" +
"<SecondTag>SecondValue</SecondTag>" +
"<ThirdTag>ThirdValue</ThirdTag>" +
"<FourthTag>FourthValue</FourthTag>" +
"<FifthTag>FifthValue</FifthTag>" +
"</root>";
assertRawEquals(ListUtil.list("FirstTag", "FirstValue",
"SecondTag", "SecondValue",
"ThirdTag", "ThirdValue",
"FourthTag", "FourthValue",
"FifthTag", "FifthValue"),
extractFrom(text));
}
public void testMultipleTagWithNoise() throws Exception {
String text =
"<root>" +
"<OtherTag>OtherValue</OtherTag>" +
"<SecondTag>SecondValue</SecondTag>" +
"<OtherTag>OtherValue</OtherTag>" +
"<OtherTag>OtherValue</OtherTag>" +
"<FourthTag>FourthValue</FourthTag>" +
"<OtherTag>OtherValue</OtherTag>" +
"<FirstTag>FirstValue</FirstTag>" +
"<OtherTag>OtherValue</OtherTag>" +
"<OtherTag>OtherValue</OtherTag>" +
"<OtherTag>OtherValue</OtherTag>" +
"<FifthTag>FifthValue</FifthTag>" +
"<OtherTag>OtherValue</OtherTag>" +
"<ThirdTag>ThirdValue</ThirdTag>" +
"</root>";
assertRawEquals(ListUtil.list("firsttag", "FirstValue",
"secondtag", "SecondValue",
"thirdtag", "ThirdValue",
"fourthtag", "FourthValue",
"fifthtag", "FifthValue"),
extractFrom(text));
}
public void testXmlDecoding() throws Exception {
String text =
"<root>" +
"<FirstTag>"Quoted" Title</FirstTag>" +
"<SecondTag>foo"bar" </SecondTag>" +
"<ThirdTag>l<g>a&q"a'z</ThirdTag>" +
"</root>";
assertRawEquals(ListUtil.list("FirstTag", "\"Quoted\" Title",
"SecondTag", "foo\"bar\" ",
"ThirdTag", "l<g>a&q\"a'z"),
extractFrom(text));
}
static final String[] TEST_TAGS = {
"FirstTag",
"SecondTag",
"ThirdTag",
"FourthTag",
"FifthTag",
};
private class MyFileMetadataExtractorFactory
implements FileMetadataExtractorFactory {
MyFileMetadataExtractorFactory() {
}
public FileMetadataExtractor
createFileMetadataExtractor(MetadataTarget target, String mimeType)
throws PluginException {
return new SaxMetadataExtractor(Arrays.asList(TEST_TAGS));
}
}
}
|
package jenkins.security;
import hudson.cli.CLI;
import hudson.cli.CLICommand;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import java.io.File;
import java.io.PrintStream;
import jenkins.security.security218.Payload;
import org.jenkinsci.remoting.RoleChecker;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
import org.jvnet.hudson.test.recipes.PresetData;
import org.kohsuke.args4j.Argument;
@SuppressWarnings("deprecation") // Remoting-based CLI usages intentional
public class Security218CliTest {
@Rule
public JenkinsRule r = new JenkinsRule();
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeCommonsBeanutils1() throws Exception {
probe(Payload.CommonsBeanutils1, PayloadCaller.EXIT_CODE_REJECTED);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-218")
public void probeCommonsCollections1() throws Exception {
probe(Payload.CommonsCollections1, 1);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-218")
public void probeCommonsCollections2() throws Exception {
// The issue with CommonsCollections2 does not appear in manual tests on Jenkins, but it may be a risk
// in newer commons-collections version => remoting implementation should filter this class anyway
probe(Payload.CommonsCollections2, PayloadCaller.EXIT_CODE_REJECTED);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeCommonsCollections3() throws Exception {
probe(Payload.CommonsCollections3, 1);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeCommonsCollections4() throws Exception {
probe(Payload.CommonsCollections4, PayloadCaller.EXIT_CODE_REJECTED);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeCommonsCollections5() throws Exception {
probe(Payload.CommonsCollections5, 1);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeCommonsCollections6() throws Exception {
probe(Payload.CommonsCollections6, 1);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeFileUpload1() throws Exception {
probe(Payload.FileUpload1, 3);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-218")
public void probeGroovy1() throws Exception {
probe(Payload.Groovy1, PayloadCaller.EXIT_CODE_REJECTED);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeJdk7u21() throws Exception {
probe(Payload.Jdk7u21, PayloadCaller.EXIT_CODE_REJECTED);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeJRMPClient() throws Exception {
probe(Payload.JRMPClient, PayloadCaller.EXIT_CODE_REJECTED);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeJRMPListener() throws Exception {
probe(Payload.JRMPListener, 3);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeJSON1() throws Exception {
probe(Payload.JSON1, PayloadCaller.EXIT_CODE_REJECTED);
}
//TODO: Fix the conversion layer (not urgent)
// There is an issue in the conversion layer after the migration to another XALAN namespace
// with newer libs. SECURITY-218 does not appear in this case in manual tests anyway
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-218")
public void probeSpring1() throws Exception {
// Reason it is 1 is that it is testing a test that is not in our version of Spring
// Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler
probe(Payload.Spring1, 1);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-317")
public void probeSpring2() throws Exception {
// Reason it is 1 is that it is testing a test that is not in our version of Spring 4
// Caused by: java.lang.ClassNotFoundException: org.springframework.core.SerializableTypeWrapper$TypeProvider
probe(Payload.Spring2, 1);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-360")
public void ldap() throws Exception {
// with a proper fix, this should fail with EXIT_CODE_REJECTED
// otherwise this will fail with -1 exit code
probe(Payload.Ldap, PayloadCaller.EXIT_CODE_REJECTED);
}
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Test
@Issue("SECURITY-429")
public void jsonLibSignedObject() throws Exception {
probe(Payload.JsonLibSignedObject, 1);
}
private void probe(Payload payload, int expectedResultCode) throws Exception {
File file = File.createTempFile("security-218", payload + "-payload");
File moved = new File(file.getAbsolutePath() + "-moved");
// Bypassing _main because it does nothing interesting here.
// Hardcoding CLI protocol version 1 (CliProtocol) because it is easier to sniff.
try (CLI cli = new CLI(r.getURL())) {
int exitCode = cli.execute("send-payload",
payload.toString(), "mv " + file.getAbsolutePath() + " " + moved.getAbsolutePath());
assertEquals("Unexpected result code.", expectedResultCode, exitCode);
assertTrue("Payload should not invoke the move operation " + file, !moved.exists());
file.delete();
}
}
@TestExtension()
public static class SendPayloadCommand extends CLICommand {
@Override
public String getShortDescription() {
return hudson.cli.Messages.ConsoleCommand_ShortDescription();
}
@Argument(metaVar = "payload", usage = "ID of the payload", required = true, index = 0)
public String payload;
@Argument(metaVar = "command", usage = "Command to be launched by the payload", required = true, index = 1)
public String command;
@Override
protected int run() throws Exception {
Payload payloadItem = Payload.valueOf(this.payload);
PayloadCaller callable = new PayloadCaller(payloadItem, command);
return channel.call(callable);
}
@Override
protected void printUsageSummary(PrintStream stderr) {
stderr.println("Sends a payload over the channel");
}
}
public static class PayloadCaller implements Callable<Integer, Exception> {
private final Payload payload;
private final String command;
public static final int EXIT_CODE_OK = 0;
public static final int EXIT_CODE_REJECTED = 42;
public static final int EXIT_CODE_ASSIGNMENT_ISSUE = 43;
public PayloadCaller(Payload payload, String command) {
this.payload = payload;
this.command = command;
}
@Override
public Integer call() throws Exception {
final Object ysoserial = payload.getPayloadClass().newInstance().getObject(command);
// Invoke backward call
try {
Channel.current().call(new Callable<String, Exception>() {
private static final long serialVersionUID = 1L;
@Override
public String call() throws Exception {
// We don't care what happens here. Object should be sent over the channel
return ysoserial.toString();
}
@Override
public void checkRoles(RoleChecker checker) throws SecurityException {
// do nothing
}
});
} catch (Exception ex) {
Throwable cause = ex;
while (cause.getCause() != null) {
cause = cause.getCause();
}
if (cause instanceof SecurityException) {
// It should happen if the remote channel reject a class.
// That's what we have done in SECURITY-218 => may be OK
if (cause.getMessage().contains("Rejected")) {
return PayloadCaller.EXIT_CODE_REJECTED;
} else {
// Something wrong
throw ex;
}
}
final String message = cause.getMessage();
if (message != null && message.contains("cannot be cast to java.util.Set")) {
// We ignore this exception, because there is a known issue in the test payload
// CommonsCollections1, CommonsCollections2 and Groovy1 fail with this error,
// but actually it means that the conversion has been triggered
return EXIT_CODE_ASSIGNMENT_ISSUE;
} else {
throw ex;
}
}
return EXIT_CODE_OK;
}
@Override
public void checkRoles(RoleChecker checker) throws SecurityException {
// Do nothing
}
}
}
|
package org.zstack.test.mevoco;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.allocator.HostCapacityOverProvisioningManager;
import org.zstack.header.configuration.DiskOfferingInventory;
import org.zstack.header.configuration.InstanceOfferingInventory;
import org.zstack.header.host.HostInventory;
import org.zstack.header.host.HostVO;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.network.l2.L2NetworkInventory;
import org.zstack.header.network.l3.IpRangeInventory;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.network.l3.UsedIpVO;
import org.zstack.header.storage.primary.ImageCacheVO;
import org.zstack.header.storage.primary.PrimaryStorageInventory;
import org.zstack.header.storage.primary.PrimaryStorageOverProvisioningManager;
import org.zstack.header.storage.primary.PrimaryStorageVO;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmNicInventory;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.kvm.KVMAgentCommands.AttachDataVolumeCmd;
import org.zstack.kvm.KVMAgentCommands.StartVmCmd;
import org.zstack.kvm.KVMSystemTags;
import org.zstack.mevoco.KVMAddOns.NicQos;
import org.zstack.mevoco.KVMAddOns.VolumeQos;
import org.zstack.mevoco.MevocoConstants;
import org.zstack.mevoco.MevocoSystemTags;
import org.zstack.network.service.flat.FlatDhcpBackend.ApplyDhcpCmd;
import org.zstack.network.service.flat.FlatDhcpBackend.DhcpInfo;
import org.zstack.network.service.flat.FlatDhcpBackend.PrepareDhcpCmd;
import org.zstack.network.service.flat.FlatNetworkServiceSimulatorConfig;
import org.zstack.network.service.flat.FlatNetworkSystemTags;
import org.zstack.core.db.SimpleQuery;
import org.zstack.header.allocator.HostCapacityOverProvisioningManager;
import org.zstack.header.identity.*;
import org.zstack.header.query.QueryOp;
import org.zstack.header.storage.primary.PrimaryStorageOverProvisioningManager;
import org.zstack.network.service.flat.FlatNetworkServiceSimulatorConfig;
import org.zstack.simulator.kvm.KVMSimulatorConfig;
import org.zstack.storage.primary.local.LocalStorageSimulatorConfig;
import org.zstack.storage.primary.local.LocalStorageSimulatorConfig.Capacity;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.test.identity.IdentityCreator;
import org.zstack.utils.Utils;
import org.zstack.utils.data.SizeUnit;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import org.zstack.utils.network.NetworkUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.zstack.core.Platform._;
/**
* test predefined policies
*/
public class TestMevoco21 {
CLogger logger = Utils.getLogger(TestMevoco21.class);
Deployer deployer;
Api api;
ComponentLoader loader;
CloudBus bus;
DatabaseFacade dbf;
SessionInventory session;
LocalStorageSimulatorConfig config;
FlatNetworkServiceSimulatorConfig fconfig;
KVMSimulatorConfig kconfig;
PrimaryStorageOverProvisioningManager psRatioMgr;
HostCapacityOverProvisioningManager hostRatioMgr;
long totalSize = SizeUnit.GIGABYTE.toByte(100);
@Before
public void setUp() throws Exception {
DBUtil.reDeployDB();
WebBeanConstructor con = new WebBeanConstructor();
deployer = new Deployer("deployerXml/mevoco/TestMevoco.xml", con);
deployer.addSpringConfig("mevocoRelated.xml");
deployer.load();
loader = deployer.getComponentLoader();
bus = loader.getComponent(CloudBus.class);
dbf = loader.getComponent(DatabaseFacade.class);
config = loader.getComponent(LocalStorageSimulatorConfig.class);
fconfig = loader.getComponent(FlatNetworkServiceSimulatorConfig.class);
kconfig = loader.getComponent(KVMSimulatorConfig.class);
psRatioMgr = loader.getComponent(PrimaryStorageOverProvisioningManager.class);
hostRatioMgr = loader.getComponent(HostCapacityOverProvisioningManager.class);
Capacity c = new Capacity();
c.total = totalSize;
c.avail = totalSize;
config.capacityMap.put("host1", c);
deployer.build();
api = deployer.getApi();
session = api.loginAsAdmin();
}
private void validate(List<PolicyVO> ps, String policyName, String statementAction, AccountConstant.StatementEffect effect) {
for (PolicyVO vo : ps) {
if (vo.getName().equals(policyName)) {
List<PolicyInventory.Statement> ss = JSONObjectUtil.toCollection(vo.getData(), ArrayList.class, PolicyInventory.Statement.class);
for (PolicyInventory.Statement s : ss) {
for (String action : s.getActions()) {
if (action.equals(statementAction) && effect == s.getEffect()) {
return;
}
}
}
}
}
Assert.fail(String.format("cannot find policy[name: %s, action: %s, effect: %s\n\n %s", policyName, statementAction,
effect, JSONObjectUtil.toJsonString(PolicyInventory.valueOf(ps))));
}
/*
private void validate(List<PolicyVO> ps, String policyName, List<String> statementActions, AccountConstant.StatementEffect effect) {
for (PolicyVO vo : ps) {
if (vo.getName().equals(policyName)) {
List<PolicyInventory.Statement> ss = JSONObjectUtil.toCollection(vo.getData(), ArrayList.class, PolicyInventory.Statement.class);
for (PolicyInventory.Statement s : ss) {
if (s.getActions().containsAll(statementActions) && effect == s.getEffect()) {
return;
}
}
}
}
Assert.fail(String.format("cannot find policy[name: %s, action: %s, effect: %s\n\n %s", policyName, statementActions,
effect, JSONObjectUtil.toJsonString(PolicyInventory.valueOf(ps))));
}
*/
@Test
public void test() throws ApiSenderException {
IdentityCreator creator = new IdentityCreator(api);
AccountInventory test = creator.createAccount("test", "test");
SimpleQuery<PolicyVO> q = dbf.createQuery(PolicyVO.class);
q.add(PolicyVO_.accountUuid, SimpleQuery.Op.EQ, test.getUuid());
List<PolicyVO> ps = q.list();
validate(ps, "VM.CREATE", "instance:APICreateVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.UPDATE", "instance:APIUpdateVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.START", "instance:APIStartVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.STOP", "instance:APIStopVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.REBOOT", "instance:APIRebootVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.DESTROY", "instance:APIDestroyVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.RECOVER", "instance:APIRecoverVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.EXPUNGE", "instance:APIExpungeVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.CONSOLE", "instance:APIRequestConsoleAccessMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.ISO.ADD", "instance:APIAttachIsoToVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.ISO.REMOVE", "instance:APIDetachIsoFromVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.MIGRATE", "instance:APIMigrateVmMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.L3.ATTACH", "instance:APIAttachL3NetworkToVmMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.L3.DETACH", "instance:APIDetachL3NetworkFromVmMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.INSTANCE-OFFERING.CHANGE", "instance:APIChangeInstanceOfferingMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.CREATE", "volume:APICreateDataVolumeMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.UPDATE", "volume:APIUpdateVolumeMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.ATTACH", "volume:APIAttachDataVolumeToVmMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.DETACH", "volume:APIDetachDataVolumeFromVmMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.CHANGE-STATE", "volume:APIChangeVolumeStateMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.DELETE", "volume:APIDeleteDataVolumeMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.EXPUNGE", "volume:APIExpungeDataVolumeMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.SNAPSHOT.CREATE", "volumeSnapshot:APICreateVolumeSnapshotMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.SNAPSHOT.UPDATE", "volumeSnapshot:APIUpdateVolumeSnapshotMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.SNAPSHOT.DELETE", "volumeSnapshot:APIDeleteVolumeSnapshotMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.SNAPSHOT.REVERT", "volumeSnapshot:APIRevertVolumeFromSnapshotMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.CREATE", "securityGroup:APICreateSecurityGroupMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.UPDATE", "securityGroup:APIUpdateSecurityGroupMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.CHANGE-STATE", "securityGroup:APIChangeSecurityGroupStateMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.DELETE", "securityGroup:APIDeleteSecurityGroupMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.ADD-NIC", "securityGroup:APIAddVmNicToSecurityGroupMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.REMOVE-NIC", "securityGroup:APIDeleteVmNicFromSecurityGroupMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.ADD-RULE", "securityGroup:APIAddSecurityGroupRuleMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.REMOVE-RULE", "securityGroup:APIDeleteSecurityGroupRuleMsg", AccountConstant.StatementEffect.Allow);
APIQueryPolicyMsg qmsg = new APIQueryPolicyMsg();
qmsg.addQueryCondition("accountUuid", QueryOp.EQ, test.getUuid());
APIQueryPolicyReply r = api.query(qmsg, APIQueryPolicyReply.class, creator.getAccountSession());
Assert.assertFalse(r.getInventories().isEmpty());
UserInventory user = creator.createUser("user", "password");
qmsg = new APIQueryPolicyMsg();
qmsg.addQueryCondition("user.uuid", QueryOp.EQ, user.getUuid());
qmsg.addQueryCondition("name", QueryOp.EQ, "DEFAULT-READ");
r = api.query(qmsg, APIQueryPolicyReply.class, creator.getAccountSession());
Assert.assertEquals(1, r.getInventories().size());
}
}
|
package com.conveyal.gtfs.loader;
import com.conveyal.gtfs.TestUtils;
import com.conveyal.gtfs.dto.CalendarDTO;
import com.conveyal.gtfs.dto.FareDTO;
import com.conveyal.gtfs.dto.FareRuleDTO;
import com.conveyal.gtfs.dto.FeedInfoDTO;
import com.conveyal.gtfs.dto.FrequencyDTO;
import com.conveyal.gtfs.dto.PatternDTO;
import com.conveyal.gtfs.dto.PatternStopDTO;
import com.conveyal.gtfs.dto.RouteDTO;
import com.conveyal.gtfs.dto.ShapePointDTO;
import com.conveyal.gtfs.dto.StopDTO;
import com.conveyal.gtfs.dto.StopTimeDTO;
import com.conveyal.gtfs.dto.TripDTO;
import com.conveyal.gtfs.util.InvalidNamespaceException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import static com.conveyal.gtfs.GTFS.createDataSource;
import static com.conveyal.gtfs.GTFS.makeSnapshot;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
/**
* This class contains CRUD tests for {@link JdbcTableWriter} (i.e., editing GTFS entities in the RDBMS). Set up
* consists of creating a scratch database and an empty feed snapshot, which is the necessary starting condition
* for building a GTFS feed from scratch. It then runs the various CRUD tests and finishes by dropping the database
* (even if tests fail).
*/
public class JDBCTableWriterTest {
private static final Logger LOG = LoggerFactory.getLogger(JDBCTableWriterTest.class);
private static String testDBName;
private static DataSource testDataSource;
private static String testNamespace;
private static String simpleServiceId = "1";
private static String firstStopId = "1";
private static String lastStopId = "2";
private static double firstStopLat = 34.2222;
private static double firstStopLon = -87.333;
private static double lastStopLat = 34.2233;
private static double lastStopLon = -87.334;
private static String sharedShapeId = "shared_shape_id";
private static final ObjectMapper mapper = new ObjectMapper();
private static JdbcTableWriter createTestTableWriter (Table table) throws InvalidNamespaceException {
return new JdbcTableWriter(table, testDataSource, testNamespace);
}
@BeforeClass
public static void setUpClass() throws SQLException, IOException, InvalidNamespaceException {
// Create a new database
testDBName = TestUtils.generateNewDB();
String dbConnectionUrl = String.format("jdbc:postgresql://localhost/%s", testDBName);
testDataSource = createDataSource (dbConnectionUrl, null, null);
LOG.info("creating feeds table because it isn't automatically generated unless you import a feed");
Connection connection = testDataSource.getConnection();
connection.createStatement()
.execute("create table if not exists feeds (namespace varchar primary key, md5 varchar, " +
"sha1 varchar, feed_id varchar, feed_version varchar, filename varchar, loaded_date timestamp, " +
"snapshot_of varchar)");
connection.commit();
LOG.info("feeds table created");
// Create an empty snapshot to create a new namespace and all the tables
FeedLoadResult result = makeSnapshot(null, testDataSource);
testNamespace = result.uniqueIdentifier;
// Create a service calendar and two stops, both of which are necessary to perform pattern and trip tests.
createWeekdayCalendar(simpleServiceId, "20180103", "20180104");
createSimpleStop(firstStopId, "First Stop", firstStopLat, firstStopLon);
createSimpleStop(lastStopId, "Last Stop", lastStopLat, lastStopLon);
}
@AfterClass
public static void tearDownClass() {
TestUtils.dropDB(testDBName);
}
@Test
public void canCreateUpdateAndDeleteFeedInfoEntities() throws IOException, SQLException, InvalidNamespaceException {
// Store Table and Class values for use in test.
final Table feedInfoTable = Table.FEED_INFO;
final Class<FeedInfoDTO> feedInfoDTOClass = FeedInfoDTO.class;
// create new object to be saved
FeedInfoDTO feedInfoInput = new FeedInfoDTO();
String publisherName = "test-publisher";
feedInfoInput.feed_publisher_name = publisherName;
feedInfoInput.feed_publisher_url = "example.com";
feedInfoInput.feed_lang = "en";
feedInfoInput.default_route_color = "1c8edb";
feedInfoInput.default_route_type = "3";
// convert object to json and save it
JdbcTableWriter createTableWriter = createTestTableWriter(feedInfoTable);
String createOutput = createTableWriter.create(mapper.writeValueAsString(feedInfoInput), true);
LOG.info("create {} output:", feedInfoTable.name);
LOG.info(createOutput);
// parse output
FeedInfoDTO createdFeedInfo = mapper.readValue(createOutput, feedInfoDTOClass);
// make sure saved data matches expected data
assertThat(createdFeedInfo.feed_publisher_name, equalTo(publisherName));
// try to update record
String updatedPublisherName = "test-publisher-updated";
createdFeedInfo.feed_publisher_name = updatedPublisherName;
// covert object to json and save it
JdbcTableWriter updateTableWriter = createTestTableWriter(feedInfoTable);
String updateOutput = updateTableWriter.update(
createdFeedInfo.id,
mapper.writeValueAsString(createdFeedInfo),
true
);
LOG.info("update {} output:", feedInfoTable.name);
LOG.info(updateOutput);
FeedInfoDTO updatedFeedInfoDTO = mapper.readValue(updateOutput, feedInfoDTOClass);
// make sure saved data matches expected data
assertThat(updatedFeedInfoDTO.feed_publisher_name, equalTo(updatedPublisherName));
// try to delete record
JdbcTableWriter deleteTableWriter = createTestTableWriter(feedInfoTable);
int deleteOutput = deleteTableWriter.delete(
createdFeedInfo.id,
true
);
LOG.info("deleted {} records from {}", deleteOutput, feedInfoTable.name);
// make sure record does not exist in DB
assertThatSqlQueryYieldsZeroRows(String.format(
"select * from %s.%s where id=%d",
testNamespace,
feedInfoTable.name,
createdFeedInfo.id
));
}
/**
* Ensure that potentially malicious SQL injection is sanitized properly during create operations.
* TODO: We might should perform this check on multiple entities and for update and/or delete operations.
*/
@Test
public void canPreventSQLInjection() throws IOException, SQLException, InvalidNamespaceException {
// create new object to be saved
FeedInfoDTO feedInfoInput = new FeedInfoDTO();
String publisherName = "' OR 1 = 1; SELECT '1";
feedInfoInput.feed_publisher_name = publisherName;
feedInfoInput.feed_publisher_url = "example.com";
feedInfoInput.feed_lang = "en";
feedInfoInput.default_route_color = "1c8edb";
feedInfoInput.default_route_type = "3";
// convert object to json and save it
JdbcTableWriter createTableWriter = createTestTableWriter(Table.FEED_INFO);
String createOutput = createTableWriter.create(mapper.writeValueAsString(feedInfoInput), true);
LOG.info("create output:");
LOG.info(createOutput);
// parse output
FeedInfoDTO createdFeedInfo = mapper.readValue(createOutput, FeedInfoDTO.class);
// make sure saved data matches expected data
assertThat(createdFeedInfo.feed_publisher_name, equalTo(publisherName));
}
@Test
public void canCreateUpdateAndDeleteFares() throws IOException, SQLException, InvalidNamespaceException {
// Store Table and Class values for use in test.
final Table fareTable = Table.FARE_ATTRIBUTES;
final Class<FareDTO> fareDTOClass = FareDTO.class;
// create new object to be saved
FareDTO fareInput = new FareDTO();
String fareId = "2A";
fareInput.fare_id = fareId;
fareInput.currency_type = "USD";
fareInput.price = 2.50;
fareInput.agency_id = "RTA";
fareInput.payment_method = 0;
// Empty value should be permitted for transfers and transfer_duration
fareInput.transfers = null;
fareInput.transfer_duration = null;
FareRuleDTO fareRuleInput = new FareRuleDTO();
// Fare ID should be assigned to "child entity" by editor automatically.
fareRuleInput.fare_id = null;
fareRuleInput.route_id = null;
// FIXME There is currently no check for valid zone_id values in contains_id, origin_id, and destination_id.
fareRuleInput.contains_id = "any";
fareRuleInput.origin_id = "value";
fareRuleInput.destination_id = "permitted";
fareInput.fare_rules = new FareRuleDTO[]{fareRuleInput};
// convert object to json and save it
JdbcTableWriter createTableWriter = createTestTableWriter(fareTable);
String createOutput = createTableWriter.create(mapper.writeValueAsString(fareInput), true);
LOG.info("create {} output:", fareTable.name);
LOG.info(createOutput);
// parse output
FareDTO createdFare = mapper.readValue(createOutput, fareDTOClass);
// make sure saved data matches expected data
assertThat(createdFare.fare_id, equalTo(fareId));
assertThat(createdFare.fare_rules[0].fare_id, equalTo(fareId));
// try to update record
String updatedFareId = "3B";
createdFare.fare_id = updatedFareId;
// covert object to json and save it
JdbcTableWriter updateTableWriter = createTestTableWriter(fareTable);
String updateOutput = updateTableWriter.update(
createdFare.id,
mapper.writeValueAsString(createdFare),
true
);
LOG.info("update {} output:", fareTable.name);
LOG.info(updateOutput);
FareDTO updatedFareDTO = mapper.readValue(updateOutput, fareDTOClass);
// make sure saved data matches expected data
assertThat(updatedFareDTO.fare_id, equalTo(updatedFareId));
assertThat(updatedFareDTO.fare_rules[0].fare_id, equalTo(updatedFareId));
// try to delete record
JdbcTableWriter deleteTableWriter = createTestTableWriter(fareTable);
int deleteOutput = deleteTableWriter.delete(
createdFare.id,
true
);
LOG.info("deleted {} records from {}", deleteOutput, fareTable.name);
// make sure fare_attributes record does not exist in DB
assertThatSqlQueryYieldsZeroRows(String.format(
"select * from %s.%s where id=%d",
testNamespace,
fareTable.name,
createdFare.id
));
// make sure fare_rules record does not exist in DB
assertThatSqlQueryYieldsZeroRows(String.format(
"select * from %s.%s where id=%d",
testNamespace,
Table.FARE_RULES.name,
createdFare.fare_rules[0].id
));
}
@Test
public void canCreateUpdateAndDeleteRoutes() throws IOException, SQLException, InvalidNamespaceException {
// Store Table and Class values for use in test.
final Table routeTable = Table.ROUTES;
final Class<RouteDTO> routeDTOClass = RouteDTO.class;
// create new object to be saved
String routeId = "500";
RouteDTO createdRoute = createSimpleTestRoute(routeId, "RTA", "500", "Hollingsworth", 3);
// make sure saved data matches expected data
assertThat(createdRoute.route_id, equalTo(routeId));
// TODO: Verify with a SQL query that the database now contains the created data (we may need to use the same
// db connection to do this successfully?)
// try to update record
String updatedRouteId = "600";
createdRoute.route_id = updatedRouteId;
// covert object to json and save it
JdbcTableWriter updateTableWriter = createTestTableWriter(routeTable);
String updateOutput = updateTableWriter.update(
createdRoute.id,
mapper.writeValueAsString(createdRoute),
true
);
LOG.info("update {} output:", routeTable.name);
LOG.info(updateOutput);
RouteDTO updatedRouteDTO = mapper.readValue(updateOutput, routeDTOClass);
// make sure saved data matches expected data
assertThat(updatedRouteDTO.route_id, equalTo(updatedRouteId));
// TODO: Verify with a SQL query that the database now contains the updated data (we may need to use the same
// db connection to do this successfully?)
// try to delete record
JdbcTableWriter deleteTableWriter = createTestTableWriter(routeTable);
int deleteOutput = deleteTableWriter.delete(
createdRoute.id,
true
);
LOG.info("deleted {} records from {}", deleteOutput, routeTable.name);
// make sure route record does not exist in DB
assertThatSqlQueryYieldsZeroRows(String.format(
"select * from %s.%s where id=%d",
testNamespace,
routeTable.name,
createdRoute.id
));
}
/**
* Test that a frequency trip entry CANNOT be added for a timetable-based pattern. Expects an exception to be thrown.
*/
@Test(expected = IllegalStateException.class)
public void cannotCreateFrequencyForTimetablePattern() throws InvalidNamespaceException, IOException, SQLException {
PatternDTO simplePattern = createRouteAndSimplePattern("900", "8", "The Loop");
TripDTO tripInput = constructFrequencyTrip(simplePattern.pattern_id, simplePattern.route_id, 6 * 60 * 60);
JdbcTableWriter createTripWriter = createTestTableWriter(Table.TRIPS);
createTripWriter.create(mapper.writeValueAsString(tripInput), true);
}
/**
* When multiple patterns reference a single shape_id, the returned JSON from an update to any of these patterns
* (whether the shape points were updated or not) should have a new shape_id because of the "copy on update" logic
* that ensures the shared shape is not modified.
*/
@Test
public void shouldChangeShapeIdOnPatternUpdate() throws IOException, SQLException, InvalidNamespaceException {
String patternId = "10";
ShapePointDTO[] shapes = new ShapePointDTO[]{
new ShapePointDTO(2, 0.0, sharedShapeId, firstStopLat, firstStopLon, 0),
new ShapePointDTO(2, 150.0, sharedShapeId, lastStopLat, lastStopLon, 1)
};
PatternStopDTO[] patternStops = new PatternStopDTO[]{
new PatternStopDTO(patternId, firstStopId, 0),
new PatternStopDTO(patternId, lastStopId, 1)
};
PatternDTO simplePattern = createRouteAndPattern("1001", patternId, "The Line", sharedShapeId, shapes, patternStops, 0);
assertThat(simplePattern.shape_id, equalTo(sharedShapeId));
// Create pattern with shared shape. Note: typically we would encounter shared shapes on imported feeds (e.g.,
// BART), but this should simulate the situation well enough.
String secondPatternId = "11";
patternStops[0].pattern_id = secondPatternId;
patternStops[1].pattern_id = secondPatternId;
PatternDTO patternWithSharedShape = createRouteAndPattern("1002", secondPatternId, "The Line 2", sharedShapeId, shapes, patternStops, 0);
// Verify that shape_id is shared.
assertThat(patternWithSharedShape.shape_id, equalTo(sharedShapeId));
// Update any field on one of the patterns.
JdbcTableWriter patternUpdater = createTestTableWriter(Table.PATTERNS);
patternWithSharedShape.name = "The shape_id should update";
String sharedPatternOutput = patternUpdater.update(patternWithSharedShape.id, mapper.writeValueAsString(patternWithSharedShape), true);
// The output should contain a new backend-generated shape_id.
PatternDTO updatedSharedPattern = mapper.readValue(sharedPatternOutput, PatternDTO.class);
LOG.info("Updated pattern output: {}", sharedPatternOutput);
String newShapeId = updatedSharedPattern.shape_id;
assertThat(newShapeId, not(equalTo(sharedShapeId)));
// Ensure that pattern record in database reflects updated shape ID.
assertThatSqlQueryYieldsRowCount(String.format(
"select * from %s.%s where shape_id='%s' and pattern_id='%s'",
testNamespace,
Table.PATTERNS.name,
newShapeId,
secondPatternId
), 1);
}
/**
* Checks that creating a frequency trip functions properly. This also updates the pattern to include pattern stops,
* which is a prerequisite for creating a frequency trip with stop times.
*/
@Test
public void canCreateUpdateAndDeleteFrequencyTripForFrequencyPattern() throws IOException, SQLException, InvalidNamespaceException {
// Store Table and Class values for use in test.
final Table tripsTable = Table.TRIPS;
int startTime = 6 * 60 * 60;
PatternDTO simplePattern = createRouteAndSimplePattern("1000", "9", "The Line");
TripDTO tripInput = constructFrequencyTrip(simplePattern.pattern_id, simplePattern.route_id, startTime);
JdbcTableWriter createTripWriter = createTestTableWriter(tripsTable);
// Update pattern with pattern stops, set to use frequencies, and TODO shape points
JdbcTableWriter patternUpdater = createTestTableWriter(Table.PATTERNS);
simplePattern.use_frequency = 1;
simplePattern.pattern_stops = new PatternStopDTO[]{
new PatternStopDTO(simplePattern.pattern_id, firstStopId, 0),
new PatternStopDTO(simplePattern.pattern_id, lastStopId, 1)
};
String updatedPatternOutput = patternUpdater.update(simplePattern.id, mapper.writeValueAsString(simplePattern), true);
LOG.info("Updated pattern output: {}", updatedPatternOutput);
// Create new trip for the pattern
String createTripOutput = createTripWriter.create(mapper.writeValueAsString(tripInput), true);
TripDTO createdTrip = mapper.readValue(createTripOutput, TripDTO.class);
// Update trip
// TODO: Add update and delete tests for updating pattern stops, stop_times, and frequencies.
String updatedTripId = "100A";
createdTrip.trip_id = updatedTripId;
JdbcTableWriter updateTripWriter = createTestTableWriter(tripsTable);
String updateTripOutput = updateTripWriter.update(tripInput.id, mapper.writeValueAsString(createdTrip), true);
TripDTO updatedTrip = mapper.readValue(updateTripOutput, TripDTO.class);
// Check that saved data matches expected data
assertThat(updatedTrip.frequencies[0].start_time, equalTo(startTime));
assertThat(updatedTrip.trip_id, equalTo(updatedTripId));
// Delete trip record
JdbcTableWriter deleteTripWriter = createTestTableWriter(tripsTable);
int deleteOutput = deleteTripWriter.delete(
createdTrip.id,
true
);
LOG.info("deleted {} records from {}", deleteOutput, tripsTable.name);
// Check that record does not exist in DB
assertThatSqlQueryYieldsZeroRows(
String.format(
"select * from %s.%s where id=%d",
testNamespace,
tripsTable.name,
createdTrip.id
));
}
@Test
public void canUpdateServiceId() {
// load GTFS file into editor
}
private void assertThatSqlQueryYieldsRowCount(String sql, int expectedRowCount) throws SQLException {
LOG.info(sql);
int recordCount = 0;
ResultSet rs = testDataSource.getConnection().prepareStatement(sql).executeQuery();
while (rs.next()) recordCount++;
assertThat("Records matching query should equal expected count.", recordCount, equalTo(expectedRowCount));
}
void assertThatSqlQueryYieldsZeroRows(String sql) throws SQLException {
assertThatSqlQueryYieldsRowCount(sql, 0);
}
/**
* Construct (without writing to the database) a trip with a frequency entry.
*/
private TripDTO constructFrequencyTrip(String patternId, String routeId, int startTime) {
TripDTO tripInput = new TripDTO();
tripInput.pattern_id = patternId;
tripInput.route_id = routeId;
tripInput.service_id = simpleServiceId;
tripInput.stop_times = new StopTimeDTO[]{
new StopTimeDTO(firstStopId, 0, 0, 0),
new StopTimeDTO(lastStopId, 60, 60, 1)
};
FrequencyDTO frequency = new FrequencyDTO();
frequency.start_time = startTime;
frequency.end_time = 9 * 60 * 60;
frequency.headway_secs = 15 * 60;
tripInput.frequencies = new FrequencyDTO[]{frequency};
return tripInput;
}
/**
* Creates a pattern by first creating a route and then a pattern for that route.
*/
private static PatternDTO createRouteAndPattern(String routeId, String patternId, String name, String shapeId, ShapePointDTO[] shapes, PatternStopDTO[] patternStops, int useFrequency) throws InvalidNamespaceException, SQLException, IOException {
// Create new route
createSimpleTestRoute(routeId, "RTA", "500", "Hollingsworth", 3);
// Create new pattern for route
PatternDTO input = new PatternDTO();
input.pattern_id = patternId;
input.route_id = routeId;
input.name = name;
input.use_frequency = useFrequency;
input.shape_id = shapeId;
input.shapes = shapes;
input.pattern_stops = patternStops;
// Write the pattern to the database
JdbcTableWriter createPatternWriter = createTestTableWriter(Table.PATTERNS);
String output = createPatternWriter.create(mapper.writeValueAsString(input), true);
LOG.info("create {} output:", Table.PATTERNS.name);
LOG.info(output);
// Parse output
return mapper.readValue(output, PatternDTO.class);
}
/**
* Creates a pattern by first creating a route and then a pattern for that route.
*/
private static PatternDTO createRouteAndSimplePattern(String routeId, String patternId, String name) throws InvalidNamespaceException, SQLException, IOException {
return createRouteAndPattern(routeId, patternId, name, null, new ShapePointDTO[]{}, new PatternStopDTO[]{}, 0);
}
/**
* Create and store a simple stop entity.
*/
private static StopDTO createSimpleStop(String stopId, String stopName, double latitude, double longitude) throws InvalidNamespaceException, IOException, SQLException {
JdbcTableWriter createStopWriter = new JdbcTableWriter(Table.STOPS, testDataSource, testNamespace);
StopDTO input = new StopDTO();
input.stop_id = stopId;
input.stop_name = stopName;
input.stop_lat = latitude;
input.stop_lon = longitude;
String output = createStopWriter.create(mapper.writeValueAsString(input), true);
LOG.info("create {} output:", Table.STOPS.name);
LOG.info(output);
return mapper.readValue(output, StopDTO.class);
}
/**
* Create and store a simple route for testing.
*/
private static RouteDTO createSimpleTestRoute(String routeId, String agencyId, String shortName, String longName, int routeType) throws InvalidNamespaceException, IOException, SQLException {
RouteDTO input = new RouteDTO();
input.route_id = routeId;
input.agency_id = agencyId;
// Empty value should be permitted for transfers and transfer_duration
input.route_short_name = shortName;
input.route_long_name = longName;
input.route_type = routeType;
// convert object to json and save it
JdbcTableWriter createTableWriter = createTestTableWriter(Table.ROUTES);
String output = createTableWriter.create(mapper.writeValueAsString(input), true);
LOG.info("create {} output:", Table.ROUTES.name);
LOG.info(output);
// parse output
return mapper.readValue(output, RouteDTO.class);
}
/**
* Create and store a simple calendar that runs on each weekday.
*/
private static CalendarDTO createWeekdayCalendar(String serviceId, String startDate, String endDate) throws IOException, SQLException, InvalidNamespaceException {
JdbcTableWriter createCalendarWriter = new JdbcTableWriter(Table.CALENDAR, testDataSource, testNamespace);
CalendarDTO calendarInput = new CalendarDTO();
calendarInput.service_id = serviceId;
calendarInput.monday = 1;
calendarInput.tuesday = 1;
calendarInput.wednesday = 1;
calendarInput.thursday = 1;
calendarInput.friday = 1;
calendarInput.saturday = 0;
calendarInput.sunday = 0;
calendarInput.start_date = startDate;
calendarInput.end_date = endDate;
String output = createCalendarWriter.create(mapper.writeValueAsString(calendarInput), true);
LOG.info("create {} output:", Table.CALENDAR.name);
LOG.info(output);
return mapper.readValue(output, CalendarDTO.class);
}
}
|
package com.mijecu25.dsa.algorithms.swap;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.mijecu25.dsa.algorithms.swap.XORSwap;
/**
* Test for XORSwap class.
*
* @author Miguel Velez
* @version 0.1.3.4
*/
public class TestXORSwap {
private int[] list1 = {1, 2, 3, 4};
private int[] list2 = {5, 6, 7, 8};
@Before
public void initialize() {
;
}
/**
* Test swap(int[] intArray1, int array1Index, int[] intArray2, int array2Index)
*/
@Test
public void swap1() {
// Get the first and second element of the first and second lists
int a = this.list1[0];
int b = this.list2[1];
// Swap the first element of the first list with the last element
// of the second list
XORSwap.swap(this.list1, 0, this.list2, 1);
// Assert that the values were swapped
Assert.assertTrue(this.list1[0] == b);
Assert.assertTrue(this.list2[1] == a);
}
/**
* Test swap(int[] intArray1, int[] intArray2, int index)
*/
@Test
public void swap2() {
// Get the last elements of both lists
int a = this.list1[this.list1.length-1];
int b = this.list2[this.list2.length-1];
// Swap the last elements
XORSwap.swap(this.list1, this.list2, this.list1.length-1);
// Assert that the values were swapped
Assert.assertTrue(this.list1[this.list1.length-1] == b);
Assert.assertTrue(this.list2[this.list2.length-1] == a);
}
/**
* Test swap(int[] intArray1, int[] intArray2)
*/
@Test
public void swap3() {
// Get the lists
int[] a = new int[this.list1.length];
System.arraycopy(this.list1, 0, a, 0, this.list1.length);
int[] b = new int[this.list2.length];
System.arraycopy(this.list2, 0, b, 0, this.list2.length);
// Swap the last elements
XORSwap.swap(this.list1, this.list2);
// Assert that the values were swapped
for(int i = 0; i < this.list1.length; i++) {
Assert.assertTrue(this.list1[i] == b[i]);
Assert.assertTrue(this.list2[i] == a[i]);
}
// Try swapping lists of different lengths
XORSwap.swap(this.list1, new int[0]);
}
/**
* Test swap(int[] intArray1, int index1, int index2)
*/
@Test
public void swap4() {
// Get elements from a list
int a = this.list1[this.list1.length-1];
int b = this.list1[0];
// Swap the last elements
XORSwap.swap(this.list1, 0, this.list1.length-1);
// Assert that the values were swapped
Assert.assertTrue(this.list1[this.list1.length-1] == b);
Assert.assertTrue(this.list1[0] == a);
}
}
|
package com.unitedinternet.troilus.example;
import com.unitedinternet.troilus.Schema;
public interface RoomTable {
public static final String TABLE = "rooms";
public static final String ID = "room_id";
public static final String HOTEL_ID = "hotel_id";
public static final String NUMBER_OF_BEDS = "number_of_beds";
public static final String CREATE_STMT = Schema.load("com/unitedinternet/troilus/example/rooms.ddl");
}
|
package etomica.atom;
import etomica.atom.iterator.AtomIterator;
import etomica.atom.iterator.AtomIteratorArrayListSimple;
import etomica.util.Debug;
/**
* Resizable-array implementation of the List interface. Implements
* all optional list operations, and permits all elements, including
* null. In addition to implementing the List interface,
* this class provides methods to manipulate the size of the array that is
* used internally to store the list. (This class is roughly equivalent to
* Vector, except that it is unsynchronized.)
*
* The size, isEmpty, get, set,
* iterator, and listIterator operations run in constant
* time. The add operation runs in amortized constant time,
* that is, adding n elements requires O(n) time. All of the other operations
* run in linear time (roughly speaking). The constant factor is low compared
* to that for the LinkedList implementation.
*
* Each ArrayList instance has a capacity. The capacity is
* the size of the array used to store the elements in the list. It is always
* at least as large as the list size. As elements are added an ArrayList,
* its capacity grows automatically. The details of the growth policy are not
* specified beyond the fact that adding an element has constant amortized
* time cost.
*
* An application can increase the capacity of an ArrayList instance
* before adding a large number of elements using the ensureCapacity
* operation. This may reduce the amount of incremental reallocation.
*
* Note that this implementation is not synchronized. If
* multiple threads access an ArrayList instance concurrently, and at
* least one of the threads modifies the list structurally, it must be
* synchronized externally. (A structural modification is any operation that
* adds or deletes one or more elements, or explicitly resizes the backing
* array; merely setting the value of an element is not a structural
* modification.) This is typically accomplished by synchronizing on some
* object that naturally encapsulates the list. If no such object exists, the
* list should be "wrapped" using the Collections.synchronizedList
* method. This is best done at creation time, to prevent accidental
* unsynchronized access to the list:
*
* List list = Collections.synchronizedList(new ArrayList(...));
*
*
* The iterators returned by this class's iterator and
* listIterator methods are fail-fast: if list is structurally
* modified at any time after the iterator is created, in any way except
* through the iterator's own remove or add methods, the iterator will throw a
* ConcurrentModificationException. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
* future.
*
* @author Josh Bloch
* @version 1.17 09/30/98
* @see Collection
* @see List
* @see LinkedList
* @see Vector
* @see Collections#synchronizedList(List)
* @since JDK1.2
*/
public class AtomArrayList implements Cloneable,
java.io.Serializable {
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Atom elementData[];
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
private float trimThreshold;
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list.
*/
public AtomArrayList(int initialCapacity) {
super();
this.elementData = new Atom[initialCapacity];
trimThreshold = 0.8F;
}
/**
* Constructs an empty list.
*/
public AtomArrayList() {
this(10);
}
/**
* Trims the capacity of this ArrayList instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an ArrayList instance.
*/
public void trimToSize() {
if (size < elementData.length) {
Atom oldData[] = elementData;
elementData = new Atom[size];
System.arraycopy(oldData, 0, elementData, 0, size);
}
}
/**
* Trims the capacity of this AtomArrayList instance (calling
* trimToSize) if the fraction of the actual usage is less than
* trimThreshold.
*/
public void maybeTrimToSize() {
if (size < elementData.length * trimThreshold) {
trimToSize();
}
}
/**
* Returns the trim threshhold, the minimum fraction of the array
* element usage, below which the array is reallocated in
* maybeTrimToSize. trim threshold defaults to 0.8.
*/
public float getTrimThreshold() {
return trimThreshold;
}
/**
* Sets the trim threshhold, the minimum fraction of the array element
* usage, below which the array is reallocated in maybeTrimToSize.
* trim threshold defaults to 0.8.
*/
public void setTrimThreshold(float newTrimThreshold) {
trimThreshold = newTrimThreshold;
}
/**
* Increases the capacity of this ArrayList instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity.
*/
public void ensureCapacity(int minCapacity) {
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Atom oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
elementData = new Atom[newCapacity];
System.arraycopy(oldData, 0, elementData, 0, size);
}
}
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list.
*/
public int size() {
return size;
}
/**
* Tests if this list has no elements.
*
* @return true if this list has no elements;
* false otherwise.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns true if this list contains the specified element.
*
* @param o element whose presence in this List is to be tested.
*/
public boolean contains(Atom elem) {
return indexOf(elem) >= 0;
}
/**
* Searches for the first occurence of the given argument, testing
* for equality using the equals method.
*
* @param elem an atom.
* @return the index of the first occurrence of the argument in this
* list; returns -1 if the atom is not found.
* @see Atom#equals(Atom)
*/
public int indexOf(Atom elem) {
if (elem == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (elem.equals(elementData[i]))
return i;
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified atom in
* this list.
*
* @param elem the desired element.
* @return the index of the last occurrence of the specified atom in
* this list; returns -1 if the atom is not found.
*/
public int lastIndexOf(Atom elem) {
if (elem == null) {
for (int i = size-1; i >= 0; i
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i
if (elem.equals(elementData[i]))
return i;
}
return -1;
}
/**
* Returns a shallow copy of this ArrayList instance. (The
* elements themselves are not copied.)
*
* @return a clone of this ArrayList instance.
*/
public Object clone() {
try {
AtomArrayList v = (AtomArrayList)super.clone();
v.elementData = new Atom[size];
System.arraycopy(elementData, 0, v.elementData, 0, size);
// v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
/**
* Returns an array containing all of the elements in this list
* in the correct order.
*
* @return an array containing all of the elements in this list
* in the correct order.
*/
public Atom[] toArray() {
Atom[] result = new Atom[size];
System.arraycopy(elementData, 0, result, 0, size);
return result;
}
/**
* Returns an array containing all of the elements in this list in the
* correct order. The runtime type of the returned array is that of the
* specified array. If the list fits in the specified array, it is
* returned therein. Otherwise, a new array is allocated with the runtime
* type of the specified array and the size of this list.
*
* If the list fits in the specified array with room to spare (i.e., the
* array has more elements than the list), the element in the array
* immediately following the end of the collection is set to
* null. This is useful in determining the length of the list
* only if the caller knows that the list does not contain any
* null elements.
*
* @param a the array into which the elements of the list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list.
* @throws ArrayStoreException if the runtime type of a is not a supertype
* of the runtime type of every element in this list.
*/
public Atom[] toArray(Atom a[]) {
if (a.length < size)
a = new Atom[size];
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
// Positional Access Operations
/**
* Returns the element at the specified position in this list.
* Behavior is undefined if the given index is negative or is larger than the
* number of elements in the list. If Debug.ON is true, an exception is thrown
* if the index is out of range. First index is 0.
*
* @param index index of element to return.
* @return the element at the specified position in this list.
*/
public Atom get(int index) {
RangeCheck(index);
return elementData[index];
}
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of element to replace.
* @param element element to be stored at the specified position.
* @return the element previously at the specified position.
* @throws IndexOutOfBoundsException if index out of range
* (index < 0 || index >= size()).
*/
public Atom set(int index, Atom element) {
RangeCheck(index);
Atom oldValue = elementData[index];
elementData[index] = element;
return oldValue;
}
/**
* Appends the specified element to the end of this list.
*
* @param o element to be appended to this list.
* @return true (as per the general contract of Collection.add).
*/
public boolean add(Atom atom) {
ensureCapacity(size + 1);
elementData[size++] = atom;
return true;
}
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted.
* @param element element to be inserted.
* @throws IndexOutOfBoundsException if index is out of range
* (index < 0 || index > size()).
*/
public void add(int index, Atom element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1);
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
public void addAll(AtomArrayList atoms) {
ensureCapacity(size+atoms.size());
int newSize = size + atoms.size();
for (int i=size; i<newSize; i++) {
elementData[i] = atoms.get(i-size);
}
size = newSize;
}
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed.
* @return the element that was removed from the list.
* @throws IndexOutOfBoundsException if index out of range (index
* < 0 || index >= size()).
*/
public Atom remove(int index) {
RangeCheck(index);
Atom oldValue = elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
/**
* Removes the element at the specified position in the list.
* If the element is not the last item in the list, the element is
* replaced with the last element.
* @param index the index of the element to be removed.
* @return the element that was removed from the list.
* @throws IndexOutOfBoundsException if the index is out of range
* (index < 0 || index >= size()).
*/
public Atom removeAndReplace(int index) {
RangeCheck(index);
Atom oldAtom = elementData[index];
size
if (index < size) {
elementData[index] = elementData[size];
elementData[size] = null;
}
return oldAtom;
}
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
// Let gc do its work
//XXX this is extra work unless the atom is eventually deleted from the system
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
/**
* Removes from this List all of the elements whose index is between
* fromIndex, inclusive and toIndex, exclusive. Shifts any succeeding
* elements to the left (reduces their index).
* This call shortens the list by (toIndex - fromIndex) elements.
* (If toIndex==fromIndex, this operation has no effect.)
*
* @param fromIndex index of first element to be removed.
* @param fromIndex index after last element to be removed.
*/
protected void removeRange(int fromIndex, int toIndex) {
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// Let gc do its work
int newSize = size - (toIndex-fromIndex);
while (size != newSize)
elementData[--size] = null;
}
/**
* Check if the given index is in range. If not, throw an appropriate
* runtime exception.
*/
private void RangeCheck(int index) {
if (Debug.ON && (index >= size || index < 0))
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}
/**
* Save the state of the ArrayList instance to a stream (that
* is, serialize it).
*
* @serialData The length of the array backing the ArrayList
* instance is emitted (int), followed by all of its elements
* (each an Atom) in the proper order.
*/
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
s.defaultWriteObject();
// Write out array length
s.writeInt(elementData.length);
// Write out all elements in the proper order.
for (int i=0; i<size; i++)
s.writeObject(elementData[i]);
}
/**
* Reconstitute the ArrayList instance from a stream (that is,
* deserialize it).
*/
private synchronized void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in array length and allocate array
int arrayLength = s.readInt();
elementData = new Atom[arrayLength];
// Read in all elements in the proper order.
for (int i=0; i<size; i++)
elementData[i] = (Atom)s.readObject();
}
/**
* Returns an iterator over the elements in this list in proper
* sequence.
*
* This implementation returns a straightforward implementation of the
* iterator interface, relying on the backing list's size(),
* get(int), and remove(int) methods.
*
* Note that the iterator returned by this method will throw an
* UnsupportedOperationException in response to its
* remove method unless the list's remove(int) method is
* overridden.
*
* This implementation can be made to throw runtime exceptions in the face
* of concurrent modification, as described in the specification for the
* (protected) modCount field.
*
* @return an iterator over the elements in this list in proper sequence.
*
* @see #modCount
*/
public AtomIterator iterator() {
return new AtomIteratorArrayListSimple(this);
}
public String toString() {
StringBuffer buffer = new StringBuffer();
for(int i=0; i<size; i++) {
buffer.append(elementData[i].toString());
buffer.append(" ");
}
return buffer.toString();
}
}
|
package org.javarosa.referral.model;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.instance.DataModelTree;
import org.javarosa.core.model.utils.ExternalizableHelper;
import org.javarosa.core.util.Externalizable;
import org.javarosa.core.util.UnavailableExternalizerException;
import org.javarosa.xform.util.XFormAnswerDataSerializer;
public class Referrals implements Externalizable {
//The id of the form that these referrals are for
private int formId;
/** ReferralCondition */
Vector referralConditions;
public Referrals() {
referralConditions = new Vector();
}
public Referrals(int formId , Vector referralConditions) {
this.formId = formId;
this.referralConditions = referralConditions;
}
/**
* @return the formId
*/
public int getFormId() {
return formId;
}
/**
* @param formId the formId to set
*/
public void setFormId(int formId) {
this.formId = formId;
}
public Vector getPositiveReferrals(DataModelTree model, XFormAnswerDataSerializer serializer) {
Vector referralStrings = new Vector();
Enumeration en = referralConditions.elements();
while(en.hasMoreElements()) {
ReferralCondition condition = (ReferralCondition)en.nextElement();
IAnswerData data = model.getDataValue(condition.getQuestionReference());
if (data instanceof SelectMultiData) {
SelectMultiData mulData = (SelectMultiData) data;
if (mulData != null && ((Vector) mulData.getValue()).size() > 0) {
referralStrings.addElement(condition.getReferralText());
}
condition.getReferralText();
} else {
Object serData = serializer.serializeAnswerData(data);
if (serData != null && data != null) {
if (serData instanceof String) {
if (serData.equals(condition.getReferralValue())) {
referralStrings.addElement(condition
.getReferralText());
}
}
}
}
}
return referralStrings;
}
/*
* (non-Javadoc)
*
* @see
* org.javarosa.core.util.Externalizable#readExternal(java.io.DataInputStream
* )
*/
public void readExternal(DataInputStream in) throws IOException,
InstantiationException, IllegalAccessException,
UnavailableExternalizerException {
this.formId = in.readInt();
referralConditions = ExternalizableHelper.readExternal(in, ReferralCondition.class);
}
/* (non-Javadoc)
* @see org.javarosa.core.util.Externalizable#writeExternal(java.io.DataOutputStream)
*/
public void writeExternal(DataOutputStream out) throws IOException {
out.writeInt(this.formId);
ExternalizableHelper.writeExternal(referralConditions, out);
}
}
|
package Debrief.ReaderWriter.Word;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import junit.framework.TestCase;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import Debrief.GUI.Frames.Application;
import Debrief.ReaderWriter.Replay.ImportReplay;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.NarrativeWrapper;
import Debrief.Wrappers.TrackWrapper;
import MWC.GUI.Editable;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GenericData.HiResDate;
import MWC.TacticalData.NarrativeEntry;
public class ImportWord
{
private static List<String> SkipNames = null;
/**
* where we write our data
*
*/
private final Layers _layers;
public ImportWord(final Layers target)
{
_layers = target;
if (SkipNames == null)
{
SkipNames = new ArrayList<String>();
SkipNames.add("HMS");
SkipNames.add("Hms");
SkipNames.add("USS");
SkipNames.add("RNAS");
SkipNames.add("HNLMS");
}
}
public void importThis(final String fName, final InputStream is)
{
HWPFDocument doc = null;
try
{
doc = new HWPFDocument(is);
}
catch (IOException e)
{
e.printStackTrace();
}
if (doc == null)
return;
Range r = doc.getRange();
// StyleSheet styleSheet = doc.getStyleSheet();
int lenParagraph = r.numParagraphs();
for (int x = 0; x < lenParagraph; x++)
{
Paragraph p = r.getParagraph(x);
String text = p.text();
if (text.trim().length() == 0)
{
continue;
}
// ok, get the narrative type
NarrEntry thisN;
try
{
thisN = new NarrEntry(text);
switch (thisN.type)
{
case "FCS":
{
// add a narrative entry
NarrativeWrapper nw = getNarrativeLayer();
String hisTrack = trackFor(thisN.platform, thisN.platform);
NarrativeEntry ne =
new NarrativeEntry(hisTrack, new HiResDate(thisN.dtg), thisN.text);
nw.add(ne);
// create track for this
break;
}
default:
{
// add a plain narrative entry
break;
}
}
System.out.println("date:" + thisN.dtg + " content:" + thisN.text);
}
catch (ParseException e)
{
Application.logError2(1, "Failed whilst parsing Word Document,at line:"
+ x, e);
}
}
}
Map<String, String> nameMatches = new HashMap<String, String>();
private String trackFor(String originalName, String name)
{
String platform = name.trim();
String match = nameMatches.get(platform);
if (match == null)
{
// search the layers
Layer theL = _layers.findLayer(platform);
if (theL != null)
{
match = theL.getName();
nameMatches.put(originalName, match);
}
else
{
// try skipping then names
Iterator<String> nameIter = SkipNames.iterator();
while (nameIter.hasNext() && match == null)
{
String thisSkip = (String) nameIter.next();
if (platform.startsWith(thisSkip))
{
String subStr = platform.substring(thisSkip.length()).trim();
match = trackFor(originalName, subStr);
}
}
}
}
return match;
}
private NarrativeWrapper getNarrativeLayer()
{
NarrativeWrapper nw =
(NarrativeWrapper) _layers.findLayer(ImportReplay.NARRATIVE_LAYER);
if (nw == null)
{
nw = new NarrativeWrapper(ImportReplay.NARRATIVE_LAYER);
_layers.addThisLayer(nw);
}
return nw;
}
private static class NarrEntry
{
Date dtg;
String type;
String platform;
String text;
public NarrEntry(String entry) throws ParseException
{
DateFormat dateF = new SimpleDateFormat("HH:mm:ss");
dateF.setTimeZone(TimeZone.getTimeZone("GMT"));
String[] parts = entry.split(",");
int ctr = 0;
if (parts.length > 5)
{
String yrStr = parts[ctr++];
String monStr = parts[ctr++];
String dayStr = parts[ctr++];
String timeStr = parts[ctr++];
type = parts[ctr++].trim();
platform = parts[ctr++].trim();
@SuppressWarnings("deprecation")
Date datePart =
new Date(Integer.parseInt(yrStr) - 1900,
Integer.parseInt(monStr) - 1, Integer.parseInt(dayStr));
Date timePart = dateF.parse(timeStr);
dtg = new Date(datePart.getTime() + timePart.getTime());
// ok, and the message part
int ind = entry.indexOf(platform);
text = entry.substring(ind + platform.length() + 2);
}
}
}
public static class TestImportAIS extends TestCase
{
public void testFullImport() throws Exception
{
testImport("src/2003_2007.doc", 6);
}
public void testNameHandler()
{
Layers layers = new Layers();
TrackWrapper track = new TrackWrapper();
track.setName("Nelson");
layers.addThisLayer(track);
TrackWrapper track2 = new TrackWrapper();
track2.setName("Iron Duck");
layers.addThisLayer(track2);
ImportWord iw = new ImportWord(layers);
String match = iw.trackFor("HMS Boat", "HMS Boat");
assertNull("not found match", match);
match = iw.trackFor("HMS Nelson", "HMS Nelson");
assertNotNull("found match", match);
match = iw.trackFor("Hms Nelson", "Hms Nelson");
assertNotNull("found match", match);
match = iw.trackFor("RNAS Nelson", "RNAS Nelson");
assertNotNull("found match", match);
// check we've created new entries
assertEquals("name matches", 3, iw.nameMatches.size());
// and the two word name
match = iw.trackFor("Hms Iron Duck", "Hms Iron Duck");
assertNotNull("found match", match);
// check we've created new entries
assertEquals("name matches", 4, iw.nameMatches.size());
}
private void testImport(final String testFile, final int len)
throws Exception
{
final File testI = new File(testFile);
assertTrue(testI.exists());
final InputStream is = new FileInputStream(testI);
final Layers tLayers = new Layers();
final ImportWord importer = new ImportWord(tLayers);
importer.importThis(testFile, is);
// hmmm, how many tracks
assertEquals("got new tracks", len, tLayers.size());
final TrackWrapper thisT = (TrackWrapper) tLayers.findLayer("BW LIONESS");
final Enumeration<Editable> fixes = thisT.getPositions();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
System.out.println(thisF.getDateTimeGroup().getDate() + " COG:"
+ (int) Math.toDegrees(thisF.getCourse()) + " SOG:"
+ (int) thisF.getSpeed());
}
}
}
}
|
package org.wliu.hdfs_hdp220;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.compress.BZip2Codec;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionOutputStream;
import org.apache.hadoop.io.compress.GzipCodec;
import org.apache.hadoop.util.ReflectionUtils;
public class HDFSPut {
public static final String FSNAME = "talend";
public static OutputStream getFSOutputStream(Configuration conf, String hdfsDest) throws IOException, InterruptedException, URISyntaxException {
FileSystem fs = null;
fs = FileSystem.get(new java.net.URI(conf.get("fs.default.name")), conf, FSNAME);
Path path_dest = new Path(hdfsDest);
FSDataOutputStream fsOut = fs.create(path_dest, true);
return fsOut;
}
public static OutputStream getBZip2OutStream(Configuration conf, String hdfsDest) throws IOException, InterruptedException, URISyntaxException {
FileSystem fs = null;
fs = FileSystem.get(new java.net.URI(conf.get("fs.default.name")), conf, FSNAME);
Path path_dest = new Path(hdfsDest);
FSDataOutputStream fsOut = fs.create(path_dest, true);
CompressionCodec codecOutput = ReflectionUtils.newInstance(BZip2Codec.class, conf);
CompressionOutputStream cmprOutput = codecOutput.createOutputStream(fsOut);
return cmprOutput;
}
public static OutputStream getGZipOutStream(Configuration conf, String hdfsDest) throws IOException, InterruptedException, URISyntaxException {
FileSystem fs = null;
fs = FileSystem.get(new java.net.URI(conf.get("fs.default.name")), conf, FSNAME);
Path path_dest = new Path(hdfsDest);
FSDataOutputStream fsOut = fs.create(path_dest, true);
GzipCodec codecOutput = new GzipCodec();
codecOutput.setConf(conf);
CompressionOutputStream cmprOutput = codecOutput.createOutputStream(fsOut);
return cmprOutput;
}
public static void closeOutputStream(OutputStream outStream) {
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
// @java.file.header
package org.gridgain.grid.compute;
import org.gridgain.grid.*;
import org.gridgain.grid.lang.*;
import org.gridgain.grid.marshaller.optimized.*;
import org.gridgain.grid.resources.*;
import org.gridgain.grid.spi.deployment.*;
import org.gridgain.grid.spi.loadbalancing.*;
import org.gridgain.grid.util.*;
import org.gridgain.grid.util.lang.*;
import org.jetbrains.annotations.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
/**
* Defines compute grid functionality for executing tasks and closures over nodes
* in the projection. The methods are grouped as follows:
* <ul>
* <li>{@code apply(...)} methods execute {@link GridClosure} jobs over nodes in the projection.</li>
* <li>
* {@code call(...)} methods execute {@link Callable} jobs over nodes in the projection.
* Use {@link GridCallable} for better performance as it implements {@link Serializable}.
* </li>
* <li>
* {@code run(...)} methods execute {@link Runnable} jobs over nodes in the projection.
* Use {@link GridRunnable} for better performance as it implements {@link Serializable}.
* </li>
* <li>{@code broadcast(...)} methods broadcast jobs to all nodes in the projection.</li>
* <li>{@code affinity(...)} methods colocate jobs with nodes on which a specified key is cached.</li>
* </ul>
* Note that if attempt is made to execute a computation over an empty projection (i.e. projection that does
* not have any alive nodes), then {@link GridEmptyProjectionException} will be thrown out of result future.
* <h1 class="header">Serializable</h1>
* Also note that {@link Runnable} and {@link Callable} implementations must support serialization as required
* by the configured marshaller. For example, {@link GridOptimizedMarshaller} requires {@link Serializable}
* objects by default, but can be configured not to. Generally speaking objects that implement {@link Serializable}
* or {@link Externalizable} will perform better. For {@link Runnable} and {@link Callable} interfaces
* GridGain has analogous {@link GridRunnable} and {@link GridCallable} classes which are
* {@link Serializable}.
* <h1 class="header">Resource Injection</h1>
* All compute jobs, including closures, runnables, callables, and tasks can be injected with
* grid resources. Both, field and method based injections are supported. The following grid
* resources can be injected:
* <ul>
* <li>{@link GridTaskSessionResource}</li>
* <li>{@link GridInstanceResource}</li>
* <li>{@link GridLoggerResource}</li>
* <li>{@link GridHomeResource}</li>
* <li>{@link GridExecutorServiceResource}</li>
* <li>{@link GridLocalNodeIdResource}</li>
* <li>{@link GridMBeanServerResource}</li>
* <li>{@link GridMarshallerResource}</li>
* <li>{@link GridSpringApplicationContextResource}</li>
* <li>{@link GridSpringResource}</li>
* </ul>
* Refer to corresponding resource documentation for more information.
* Here is an example of how to inject instance of {@link Grid} into a computation:
* <pre name="code" class="java">
* public class MyGridJob extends GridRunnable {
* ...
* @GridInstanceResource
* private Grid grid;
* ...
* }
* </pre>
* <h1 class="header">Computation SPIs</h1>
* Note that regardless of which method is used for executing computations, all relevant SPI implementations
* configured for this grid instance will be used (i.e. failover, load balancing, collision resolution,
* checkpoints, etc.). If you need to override configured defaults, you should use compute task together with
* {@link GridComputeTaskSpis} annotation. Refer to {@link GridComputeTask} documentation for more information.
*
* @author @java.author
* @version @java.version
*/
public interface GridCompute {
/**
* Gets grid projection to which this {@code GridCompute} instance belongs.
*
* @return Grid projection to which this {@code GridCompute} instance belongs.
*/
public GridProjection projection();
/**
* Executes given job on the node where data for provided affinity key is located
* (a.k.a. affinity co-location).
*
* @param cacheName Name of the cache to use for affinity co-location.
* @param affKey Affinity key.
* @param job Job which will be co-located on the node with given affinity key.
* @return Future for this execution.
* @see GridComputeJobContext#cacheName()
* @see GridComputeJobContext#affinityKey()
*/
public GridFuture<?> affinityRun(@Nullable String cacheName, Object affKey, Runnable job);
/**
* Executes given job on the node where data for provided affinity key is located
* (a.k.a. affinity co-location).
*
* @param cacheName Name of the cache to use for affinity co-location.
* @param affKey Affinity key.
* @param job Job which will be co-located on the node with given affinity key.
* @return Future with job result.
* @see GridComputeJobContext#cacheName()
* @see GridComputeJobContext#affinityKey()
*/
public <R> GridFuture<R> affinityCall(@Nullable String cacheName, Object affKey, Callable<R> job);
/**
* Executes given task on the grid projection. For step-by-step explanation of task execution process
* refer to {@link GridComputeTask} documentation.
*
* @param taskCls Class of the task to execute. If class has {@link GridComputeTaskName} annotation,
* then task is deployed under a name specified within annotation. Otherwise, full
* class name is used as task name.
* @param arg Optional argument of task execution, can be {@code null}.
* @return Task future.
*/
public <T, R> GridComputeTaskFuture<R> execute(Class<? extends GridComputeTask<T, R>> taskCls, @Nullable T arg);
/**
* Executes given task on the grid projection. For step-by-step explanation of task execution process
* refer to {@link GridComputeTask} documentation.
*
* @param task Instance of task to execute. If task class has {@link GridComputeTaskName} annotation,
* then task is deployed under a name specified within annotation. Otherwise, full
* class name is used as task name.
* @param arg Optional argument of task execution, can be {@code null}.
* @return Task future.
*/
public <T, R> GridComputeTaskFuture<R> execute(GridComputeTask<T, R> task, @Nullable T arg);
/**
* Executes given task on the grid projection. For step-by-step explanation of task execution process
* refer to {@link GridComputeTask} documentation.
* <p>
* If task for given name has not been deployed yet, then {@code taskName} will be
* used as task class name to auto-deploy the task (see {@link #localDeployTask(Class, ClassLoader)} method).
*
* @param taskName Name of the task to execute.
* @param arg Optional argument of task execution, can be {@code null}.
* @return Task future.
* @see GridComputeTask for information about task execution.
*/
public <T, R> GridComputeTaskFuture<R> execute(String taskName, @Nullable T arg);
/**
* Broadcasts given job to all nodes in grid projection.
*
* @param job Job to broadcast to all projection nodes.
* @return Future for this execution.
*/
public GridFuture<?> broadcast(Runnable job);
/**
* Broadcasts given job to all nodes in grid projection. Every participating node will return
* job result. Collection of all returned job results is returned from the result future.
*
* @param job Job to broadcast to all projection nodes.
* @return Future with collection of results for this execution.
*/
public <R> GridFuture<Collection<R>> broadcast(Callable<R> job);
/**
* Broadcasts given closure job with passed in argument to all nodes in grid projection.
* Every participating node will return job result. Collection of all returned job results
* is returned from the result future.
*
* @param job Job to broadcast to all projection nodes.
* @param arg Job closure argument.
* @return Future with collection of results for this execution.
*/
public <R, T> GridFuture<Collection<R>> broadcast(GridClosure<T, R> job, @Nullable T arg);
/**
* Executes job on a node in the grid projection. Node for execution is selected
* using underlying load balancing SPI.
*
* @param job Job closure to execute.
* @return Future of this execution.
* @see GridLoadBalancingSpi
*/
public GridFuture<?> run(Runnable job);
/**
* Executes collection of jobs on nodes within grid projection. For each job a next
* load balanced node will be selected for execution. Nodes for execution are selected
* using underlying load balancing SPI.
*
* @param jobs Collection of jobs to execute.
* @return Future for this execution.
* @see GridLoadBalancingSpi
*/
public GridFuture<?> run(Collection<? extends Runnable> jobs);
/**
* Executes job on a node in the grid projection. Node for execution is selected
* using underlying load balancing SPI.
*
* @param job Job closure to execute.
* @return Future of this execution.
* @see GridLoadBalancingSpi
*/
public <R> GridFuture<R> call(Callable<R> job);
/**
* Executes collection of jobs on nodes within grid projection. For each job a next
* load balanced node will be selected for execution. Nodes for execution are selected
* using underlying load balancing SPI. Collection of all returned job results is
* returned from the result future.
*
* @param jobs Collection of jobs to execute.
* @return Future with collection of results for this execution.
* @see GridLoadBalancingSpi
*/
public <R> GridFuture<Collection<R>> call(Collection<? extends Callable<R>> jobs);
/**
* Executes given jobs on this projection.
* <p>
* This method will block until the execution is complete. All default SPI implementations
* configured for this grid instance will be used (i.e. failover, load balancing, collision
* resolution, etc.).
* Note that if you need greater control on any aspects of Java code execution on the grid
* you should implement {@link GridComputeTask} which will provide you with full control over the execution.
* <p>
* Here's a general example of the Java method that takes a text message and calculates its length
* by splitting it by spaces, calculating the length of each word on individual (remote) grid node
* and then summing (reducing) results from all nodes to produce the final length of the input string
* using function APIs, typedefs, and execution closures on the grid:
* <pre name="code" class="java">
* public static int length(final String msg) throws GridException {
* return GridGain.grid().call(SPREAD, F.yield(msg.split(" "), F.cInvoke("length")), F.sumIntReducer());
* }
* </pre>
* <p>
* Note that class {@link GridAbsClosure} implements {@link Runnable} and class {@link GridOutClosure}
* implements {@link Callable} interface. Note also that class {@link GridFunc} and typedefs provide rich
* APIs and functionality for closures and predicates based processing in GridGain. While Java interfaces
* {@link Runnable} and {@link Callable} allow for lowest common denominator for APIs - it is advisable
* to use richer Functional Programming support provided by GridGain available in {@link org.gridgain.grid.lang}
* package.
* <p>
* Notice that {@link Runnable} and {@link Callable} implementations must support serialization as required
* by the configured marshaller. For example, JDK marshaller will require that implementations would
* be serializable. Other marshallers, e.g. JBoss marshaller, may not have this limitation. Please consult
* with specific marshaller implementation for the details. Note that all closures and predicates in
* {@link org.gridgain.grid.lang} package are serializable and can be freely used in the distributed
* context with all marshallers currently shipped with GridGain.
*
* @param jobs Closures to executes.
* @param rdc Result reducing closure.
* @return Value produced by reducing closure.
* @see #withName(String)
*/
public <R1, R2> GridFuture<R2> call(Collection<? extends Callable<R1>> jobs, GridReducer<R1, R2> rdc);
/**
* Runs job producing result with given argument on this projection.
* <p>
* This method doesn't block and immediately returns with future of execution.
*
* @param job Job to run.
* @param arg Job argument.
* @return Closure result future.
* @see #call(Callable)
* @see #withName(String)
*/
public <R, T> GridFuture<R> apply(GridClosure<T, R> job, @Nullable T arg);
/**
* Runs job, taking argument and producing result on this projection with given
* collection of arguments. The job is sequentially executed on every single
* argument from the collection so that number of actual executions will be
* equal to size of collection of arguments.
* <p>
* This method doesn't block and immediately returns with future of execution.
*
* @param job Job to run.
* @param args Job arguments (closure free variables).
* @return Future of job results collection.
* @see #call(Callable)
* @see #withName(String)
*/
public <T, R> GridFuture<Collection<R>> apply(GridClosure<T, R> job, @Nullable Collection<? extends T> args);
/**
* Runs closure job with given collection of arguments. The job is sequentially
* executed on every single argument from the collection so that number of actual
* executions will be equal to size of collection of arguments. Then method reduces
* these job results to a single execution result using provided reducer.
*
* @param job Job to run.
* @param args Job arguments.
* @param rdc Job result reducer.
* @return Result reduced from job results with given reducer.
* @see #withName(String)
*/
public <R1, R2, T> GridFuture<R2> apply(GridClosure<T, R1> job, @Nullable Collection<? extends T> args,
GridReducer<R1, R2> rdc);
/**
* Creates new {@link ExecutorService} which will execute all submitted
* {@link Callable} and {@link Runnable} tasks on this projection. This essentially
* creates a <b><i>Distributed Thread Pool</i</b> that can be used as a
* replacement for local thread pools.
* <p>
* User may run {@link Callable} and {@link Runnable} tasks
* just like normally with {@link ExecutorService java.util.ExecutorService}.
* <p>
* The typical Java example could be:
* <pre name="code" class="java">
* ...
* ExecutorService exec = grid.compute().executorService();
*
* Future<String> fut = exec.submit(new MyCallable());
* ...
* String res = fut.get();
* ...
* </pre>
*
* @return {@code ExecutorService} which delegates all calls to grid.
*/
public ExecutorService executorService();
/**
* Gets task future based on session ID. If task execution was started on local node and this
* projection includes local node then the future for this task will be returned.
*
* @param sesId Session ID for task execution.
* @param <R> Task result type.
* @return Task future if task was started on this node and this node belongs to this projection,
* or {@code null} otherwise.
*/
@Nullable public <R> GridComputeTaskFuture<R> taskFuture(GridUuid sesId);
/**
* Cancels task with the given ID, if it currently running inside this projection.
*
* @param sesId Task session ID.
* @throws GridException If task cancellation failed.
*/
public void cancelTask(GridUuid sesId) throws GridException;
/**
* Cancels job with the given ID, if it currently running inside this projection.
*
* @param jobId Job ID.
* @throws GridException If task cancellation failed.
*/
public void cancelJob(GridUuid jobId) throws GridException;
/**
* Sets task name for the next executed task on this projection in the <b>current thread</b>.
* When task starts execution name is reset, so one name is used only once.
* <p>
* You may use this method to set task name when you cannot use
* {@link GridComputeTaskName} annotation.
* <p>
* Here is an example.
* <pre name="code" class="java">
* GridGain.grid().withName("MyTask").run(
* BROADCAST,
* new GridRunnable() {
* @Override public void run() {
* System.out.println("Hello!");
* }
* }
* );
* </pre>
*
* @param taskName Task name.
* @return Grid projection ({@code this}).
*/
public GridCompute withName(String taskName);
/**
* Sets task timeout for the next executed task on this projection in the <b>current thread</b>.
* When task starts timeout is reset, so one timeout is used only once.
* <p>
* Here is an example.
* <pre name="code" class="java">
* GridGain.grid().withTimeout(10000).run(
* BROADCAST,
* new GridRunnable() {
* @Override public void run() {
* System.out.println("Hello!");
* }
* }
* );
* </pre>
*
* @param timeout Task timeout in milliseconds.
* @return Grid projection ({@code this}).
*/
public GridCompute withTimeout(long timeout);
/**
* Sets no failover flag for the next executed task on this projection in the <b>current thread</b>.
* If flag is set, job will be never failed over even if it fails with exception.
* When task starts flag is reset, so all other task will use default failover policy
* (implemented in {@link GridComputeTask#result(GridComputeJobResult, List)} method).
* <p>
* Here is an example.
* <pre name="code" class="java">
* GridGain.grid().compute().withNoFailover().run(
* BROADCAST,
* new GridRunnable() {
* @Override public void run() {
* System.out.println("Hello!");
* }
* }
* );
* </pre>
*
* @return Grid projection ({@code this}).
*/
public GridCompute withNoFailover();
/**
* Explicitly deploys given grid task on the local node. Upon completion of this method,
* a task can immediately be executed on the grid, considering that all participating
* remote nodes also have this task deployed. If peer-class-loading is enabled
* (see {@link GridConfiguration#isPeerClassLoadingEnabled()}), then other nodes
* will automatically deploy task upon execution request from the originating node without
* having to manually deploy it.
* <p>
* Another way of class deployment which is supported is deployment from local class path.
* Class from local class path has a priority over P2P deployed.
* <p>
* Note that class can be deployed multiple times on remote nodes, i.e. re-deployed. GridGain
* maintains internal version of deployment for each instance of deployment (analogous to
* class and class loader in Java). Execution happens always on the latest deployed instance.
* <p>
* This method has no effect if the class passed in was already deployed.
*
* @param taskCls Task class to deploy. If task class has {@link GridComputeTaskName} annotation,
* then task will be deployed under a name specified within annotation. Otherwise, full
* class name will be used as task's name.
* @param clsLdr Task resources/classes class loader. This class loader is in charge
* of loading all necessary resources.
* @throws GridException If task is invalid and cannot be deployed.
* @see GridDeploymentSpi
*/
public void localDeployTask(Class<? extends GridComputeTask> taskCls, ClassLoader clsLdr) throws GridException;
/**
* Gets map of all locally deployed tasks keyed by their task name satisfying all given predicates.
* If no tasks were locally deployed, then empty map is returned. If no predicates provided - all
* locally deployed tasks, if any, will be returned.
*
* @return Map of locally deployed tasks keyed by their task name.
*/
public Map<String, Class<? extends GridComputeTask<?, ?>>> localTasks();
/**
* Makes the best attempt to undeploy a task with given name from the projection. Note that this
* method returns immediately and does not wait until the task will actually be
* undeployed on every node.
*
* @param taskName Name of the task to undeploy. If task class has {@link GridComputeTaskName} annotation,
* then task was deployed under a name specified within annotation. Otherwise, full
* class name should be used as task's name.
* @throws GridException Thrown if undeploy failed.
*/
public void undeployTask(String taskName) throws GridException;
}
|
package com.github.davidmoten.geo.mem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import com.google.common.collect.Lists;
public class GeomemTest {
private static final double topLeftLat = -5;
private static final double topLeftLong = 100;
private static final double bottomRightLat = -45;
private static final double bottomRightLong = 170;
private static final double PRECISION = 0.00001;
@Test
public void testGeomemFindWhenNoData() {
Geomem<String, String> g = new Geomem<String, String>();
g.find(topLeftLat, topLeftLong, bottomRightLat, bottomRightLong, 0,
1000);
}
@Test
public void testGeomemFindWhenOneEntryInsideRegion() {
Geomem<String, String> g = new Geomem<String, String>();
g.add(-15, 120, 500, "A1", "a1");
List<Info<String, String>> list = Lists.newArrayList(g.find(topLeftLat,
topLeftLong, bottomRightLat, bottomRightLong, 0, 1000));
assertEquals(1, list.size());
assertEquals(-15, list.get(0).lat(), PRECISION);
assertEquals(120, list.get(0).lon(), PRECISION);
assertEquals(500L, list.get(0).time());
assertEquals("A1", list.get(0).value());
assertEquals("a1", list.get(0).id().get());
}
@Test
public void testGeomemFindWhenOneEntryOutsideRegion() {
Geomem<String, String> g = new Geomem<String, String>();
g.add(15, 120, 500, "A1", "a1");
List<Info<String, String>> list = Lists.newArrayList(g.find(topLeftLat,
topLeftLong, bottomRightLat, bottomRightLong, 0, 1000));
assertTrue(list.isEmpty());
}
}
|
package com.github.nylle.javafixture;
import com.github.nylle.javafixture.testobjects.ITestGeneric;
import com.github.nylle.javafixture.testobjects.ITestGenericInside;
import com.github.nylle.javafixture.testobjects.TestClassWithNestedClasses;
import com.github.nylle.javafixture.testobjects.TestEnum;
import com.github.nylle.javafixture.testobjects.TestObjectGeneric;
import com.github.nylle.javafixture.testobjects.TestObjectWithDeepNesting;
import com.github.nylle.javafixture.testobjects.TestObjectWithEnumMap;
import com.github.nylle.javafixture.testobjects.TestObjectWithEnumSet;
import com.github.nylle.javafixture.testobjects.TestObjectWithGenericConstructor;
import com.github.nylle.javafixture.testobjects.TestObjectWithGenerics;
import com.github.nylle.javafixture.testobjects.TestObjectWithNestedGenericInterfaces;
import com.github.nylle.javafixture.testobjects.TestObjectWithNestedGenerics;
import com.github.nylle.javafixture.testobjects.TestObjectWithNestedMapsAndLists;
import com.github.nylle.javafixture.testobjects.TestObjectWithoutDefaultConstructor;
import com.github.nylle.javafixture.testobjects.TestPrimitive;
import com.github.nylle.javafixture.testobjects.example.AccountManager;
import com.github.nylle.javafixture.testobjects.example.Contract;
import com.github.nylle.javafixture.testobjects.example.ContractCategory;
import com.github.nylle.javafixture.testobjects.example.ContractPosition;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static com.github.nylle.javafixture.Fixture.fixture;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
class FixtureTest {
private final Configuration configuration = new Configuration();
@Test
void canCreateDefaultConfiguration() {
var result = Fixture.configuration();
assertThat(result.getMaxCollectionSize()).isEqualTo(10);
assertThat(result.getMinCollectionSize()).isEqualTo(2);
assertThat(result.getStreamSize()).isEqualTo(3);
assertThat(result.usePositiveNumbersOnly()).isFalse();
assertThat(result.getClock().instant()).isBeforeOrEqualTo(Instant.now());
assertThat(result.getClock().getZone()).isEqualTo(ZoneOffset.UTC);
}
@Nested
@DisplayName("when using Class<T>")
class WhenClass {
@Test
void canCreatePrimitives() {
Fixture fixture = new Fixture(configuration);
int integerResult = fixture.create(int.class);
assertThat(integerResult).isNotNull();
assertThat(integerResult).isInstanceOf(Integer.class);
boolean booleanResult = fixture.create(boolean.class);
assertThat(booleanResult).isNotNull();
assertThat(booleanResult).isInstanceOf(Boolean.class);
char charResult = fixture.create(char.class);
assertThat(charResult).isNotNull();
assertThat(charResult).isInstanceOf(Character.class);
}
@Test
void canCreateInstance() {
Fixture fixture = new Fixture(configuration);
TestPrimitive result = fixture.create(TestPrimitive.class);
assertThat(result).isNotNull();
assertThat(result).isInstanceOf(TestPrimitive.class);
}
@Test
void canCreateInstanceWithoutDefaultConstructor() {
Fixture fixture = new Fixture(configuration);
TestObjectWithoutDefaultConstructor result = fixture.create(TestObjectWithoutDefaultConstructor.class);
assertThat(result).isNotNull();
assertThat(result).isInstanceOf(TestObjectWithoutDefaultConstructor.class);
}
@Test
void canCreateMany() {
Fixture fixture = new Fixture(configuration);
List<TestPrimitive> result = fixture.createMany(TestPrimitive.class).collect(Collectors.toList());
assertThat(result).isNotNull();
assertThat(result.size()).isEqualTo(3);
assertThat(result.get(0)).isInstanceOf(TestPrimitive.class);
assertThat(result.get(1)).isInstanceOf(TestPrimitive.class);
assertThat(result.get(2)).isInstanceOf(TestPrimitive.class);
}
@Test
void canAddManyTo() {
Fixture fixture = new Fixture(configuration);
List<TestPrimitive> result = new ArrayList<>();
result.add(new TestPrimitive());
fixture.addManyTo(result, TestPrimitive.class);
assertThat(result).isNotNull();
assertThat(result.size()).isEqualTo(4);
assertThat(result.get(1)).isInstanceOf(TestPrimitive.class);
}
@Test
void canCreateManyWithCustomization() {
Fixture fixture = new Fixture(configuration);
List<TestPrimitive> result = fixture.build(TestPrimitive.class)
.with(x -> x.setHello("world"))
.with("integer", 3)
.without("publicField")
.createMany(3)
.collect(Collectors.toList());
TestPrimitive first = result.get(0);
assertThat(first).isInstanceOf(TestPrimitive.class);
assertThat(first.getHello()).isEqualTo("world");
assertThat(first.getInteger()).isEqualTo(3);
assertThat(first.publicField).isNull();
TestPrimitive second = result.get(1);
assertThat(second).isInstanceOf(TestPrimitive.class);
assertThat(second.getHello()).isEqualTo("world");
assertThat(second.getInteger()).isEqualTo(3);
assertThat(second.publicField).isNull();
TestPrimitive third = result.get(2);
assertThat(third).isInstanceOf(TestPrimitive.class);
assertThat(third.getHello()).isEqualTo("world");
assertThat(third.getInteger()).isEqualTo(3);
assertThat(third.publicField).isNull();
assertThat(first.getPrimitive()).isNotEqualTo(second.getPrimitive());
assertThat(second.getPrimitive()).isNotEqualTo(third.getPrimitive());
}
@Test
void canOverrideBySetter() {
Fixture fixture = new Fixture(configuration);
TestPrimitive result = fixture.build(TestPrimitive.class).with(x -> x.setHello("world")).create();
assertThat(result.getHello()).isEqualTo("world");
}
@Test
void canOverridePublicField() {
Fixture fixture = new Fixture(configuration);
TestPrimitive result = fixture.build(TestPrimitive.class).with(x -> x.publicField = "world").create();
assertThat(result.publicField).isEqualTo("world");
}
@Test
void canOverridePrivateField() {
Fixture fixture = new Fixture(configuration);
TestPrimitive result = fixture.build(TestPrimitive.class).with("hello", "world").create();
assertThat(result.getHello()).isEqualTo("world");
}
@Test
void canOmitPrivateField() {
Fixture fixture = new Fixture(configuration);
TestPrimitive result = fixture.build(TestPrimitive.class).without("hello").create();
assertThat(result.getHello()).isNull();
}
@Test
void canOmitPrivatePrimitiveFieldAndInitializesDefaultValue() {
Fixture fixture = new Fixture(configuration);
TestPrimitive result = fixture.build(TestPrimitive.class).without("primitive").create();
assertThat(result.getPrimitive()).isEqualTo(0);
}
@Test
void canBeCustomizedWithType() {
var expected = Period.ofDays(42);
var result = fixture().build(Contract.class)
.with(Period.class, expected)
.create();
var actual = result.getBaseContractPosition().getRemainingPeriod();
assertThat(actual).isSameAs(expected);
}
@Test
void canPerformAction() {
Fixture fixture = new Fixture(configuration);
ContractPosition cp = fixture.create(ContractPosition.class);
Contract contract = fixture.build(Contract.class).with(x -> x.addContractPosition(cp)).with(x -> x.setBaseContractPosition(cp)).create();
assertThat(contract.getContractPositions().contains(contract.getBaseContractPosition())).isTrue();
}
@Test
void canCreateComplexModel() {
Fixture fixture = new Fixture(configuration);
Contract result = fixture.create(Contract.class);
assertThat(result).isInstanceOf(Contract.class);
assertThat(result.getBaseContractPosition()).isInstanceOf(ContractPosition.class);
assertThat(result.getAccountManagers()).isInstanceOf(AccountManager[].class);
assertThat(result.getContractPositions()).isInstanceOf(Set.class);
assertThat(result.getContractPositions().size()).isGreaterThan(0);
assertThat(result.getCategory()).isInstanceOf(ContractCategory.class);
assertThat(result.getCreationDate()).isInstanceOf(LocalDateTime.class);
ContractPosition firstContractPosition = result.getContractPositions().iterator().next();
assertThat(firstContractPosition).isInstanceOf(ContractPosition.class);
assertThat(firstContractPosition.getContract()).isInstanceOf(Contract.class);
assertThat(firstContractPosition.getStartDate()).isInstanceOf(LocalDate.class);
assertThat(firstContractPosition.getRemainingPeriod()).isInstanceOf(Period.class);
assertThat(firstContractPosition.getFile()).isInstanceOf(File.class);
}
@Test
void canCreateThrowable() {
Fixture fixture = new Fixture(configuration);
Throwable result = fixture.create(Throwable.class);
assertThat(result).isInstanceOf(Throwable.class);
assertThat(result.getMessage().length()).isGreaterThan(0);
assertThat(result.getLocalizedMessage().length()).isGreaterThan(0);
assertThat(result.getStackTrace().length).isGreaterThan(0);
assertThat(result.getStackTrace()[0]).isInstanceOf(StackTraceElement.class);
assertThat(result.getCause()).isNull(); //if cause == this, the getter returns null
}
@Test
void canCreateNestedParameterizedCollections() {
Fixture fixture = new Fixture(configuration);
var classWithMapWithList = fixture.create(TestObjectWithNestedMapsAndLists.class);
var nestedList = classWithMapWithList.getNestedList();
assertThat(nestedList).isNotEmpty();
assertThat(nestedList).isNotEmpty();
var innerList = nestedList.get(0);
assertThat(innerList).isNotEmpty();
assertThat(innerList.get(0)).isNotEmpty();
var mapWithMap = classWithMapWithList.getMapWithMap();
assertThat(mapWithMap).isNotEmpty();
assertThat(mapWithMap.values()).isNotEmpty();
var firstValue = mapWithMap.values().iterator().next();
assertThat(firstValue).isNotEmpty();
assertThat(firstValue.values()).isNotEmpty();
var mapWithList = classWithMapWithList.getMapWithList();
assertThat(mapWithList).isNotEmpty();
assertThat(mapWithList.values()).isNotEmpty();
var firstList = mapWithList.values().iterator().next();
assertThat(firstList).isNotEmpty();
var deeplyNestedList = classWithMapWithList.getDeeplyNestedList();
assertThat(deeplyNestedList).isNotEmpty();
var firstEntry = deeplyNestedList.get(0);
assertThat(firstEntry).isNotEmpty();
var firstMapEntry = firstEntry.values().iterator().next();
assertThat(firstMapEntry).isNotEmpty();
assertThat(firstMapEntry.get(0)).isNotEmpty();
}
@Test
void canCreateParameterizedObject() {
final Fixture fixture = new Fixture(new Configuration().collectionSizeRange(2, 2));
final var result = fixture.create(TestObjectWithGenerics.class);
assertThat(result).isInstanceOf(TestObjectWithGenerics.class);
assertThat(result.getGenerics()).hasSize(2);
assertThat(result.getGenerics().get(0).getT()).isInstanceOf(String.class);
assertThat(result.getGenerics().get(0).getU()).isInstanceOf(Integer.class);
assertThat(result.getGenerics().get(0).getString()).isInstanceOf(String.class);
assertThat(result.getGeneric()).isInstanceOf(TestObjectGeneric.class);
assertThat(result.getGeneric().getT()).isInstanceOf(String.class);
assertThat(result.getGeneric().getU()).isInstanceOf(Integer.class);
assertThat(result.getAClass()).isInstanceOf(Class.class);
assertThat(result.getAClass()).isEqualTo(Object.class);
assertThat(result.getOptional()).isInstanceOf(Optional.class);
assertThat(result.getOptional().isPresent()).isTrue();
assertThat(result.getOptional().get()).isInstanceOf(Boolean.class);
}
@Test
void canCreateNestedParameterizedObject() {
final Fixture fixture = new Fixture(new Configuration().collectionSizeRange(2, 2));
final var result = fixture.create(TestObjectWithNestedGenerics.class);
assertThat(result).isInstanceOf(TestObjectWithNestedGenerics.class);
assertThat(result.getOptionalGeneric()).isInstanceOf(Optional.class);
assertThat(result.getOptionalGeneric().isPresent()).isTrue();
assertThat(result.getOptionalGeneric().get()).isInstanceOf(TestObjectGeneric.class);
assertThat(result.getOptionalGeneric().get().getT()).isInstanceOf(String.class);
assertThat(result.getOptionalGeneric().get().getU()).isInstanceOf(Integer.class);
assertThat(result.getGenericOptional()).isInstanceOf(TestObjectGeneric.class);
assertThat(result.getGenericOptional().getT()).isInstanceOf(String.class);
assertThat(result.getGenericOptional().getU()).isInstanceOf(Optional.class);
assertThat(result.getGenericOptional().getU()).isPresent();
assertThat(result.getGenericOptional().getU().get()).isInstanceOf(Integer.class);
}
@Test
void canCreateNestedParameterizedInterfaces() {
final var result = fixture().create(TestObjectWithNestedGenericInterfaces.class);
assertThat(result).isInstanceOf(TestObjectWithNestedGenericInterfaces.class);
assertThat(result.getTestGeneric()).isInstanceOf(ITestGeneric.class);
assertThat(result.getTestGeneric().publicField).isInstanceOf(Integer.class);
assertThat(result.getTestGeneric().getT()).isInstanceOf(String.class);
assertThat(result.getTestGeneric().getU()).isInstanceOf(ITestGenericInside.class);
assertThat(result.getTestGeneric().getU().getOptionalBoolean()).isInstanceOf(Optional.class);
assertThat(result.getTestGeneric().getU().getOptionalBoolean()).isPresent();
assertThat(result.getTestGeneric().getU().getOptionalBoolean().get()).isInstanceOf(Boolean.class);
assertThat(result.getTestGeneric().getU().getOptionalT()).isInstanceOf(Optional.class);
assertThat(result.getTestGeneric().getU().getOptionalT()).isPresent();
assertThat(result.getTestGeneric().getU().getOptionalT().get()).isInstanceOf(Integer.class);
assertThat(result.getTestGeneric().getU().getTestGeneric()).isInstanceOf(TestObjectGeneric.class);
assertThat(result.getTestGeneric().getU().getTestGeneric().getT()).isInstanceOf(String.class);
assertThat(result.getTestGeneric().getU().getTestGeneric().getU()).isInstanceOf(Integer.class);
}
@Test
void createThroughRandomConstructor() {
Fixture fixture = new Fixture(configuration);
var result = fixture.construct(TestObjectWithGenericConstructor.class);
assertThat(result).isInstanceOf(TestObjectWithGenericConstructor.class);
assertThat(result.getValue()).isInstanceOf(String.class);
assertThat(result.getInteger()).isInstanceOf(Optional.class);
assertThat(result.getInteger()).isPresent();
assertThat(result.getInteger().get()).isInstanceOf(Integer.class);
assertThat(result.getPrivateField()).isNull();
}
}
@Nested
@DisplayName("when using SpecimenType<T>")
class WhenSpecimenType {
@Test
void canCreateGenericObject() {
Fixture fixture = new Fixture(configuration);
var result = fixture.create(new SpecimenType<TestObjectGeneric<String, Optional<Integer>>>() {});
assertThat(result).isInstanceOf(TestObjectGeneric.class);
assertThat(result.getT()).isInstanceOf(String.class);
assertThat(result.getU()).isInstanceOf(Optional.class);
assertThat(result.getU()).isPresent();
assertThat(result.getU().get()).isInstanceOf(Integer.class);
}
@Test
void canCreateGenericInterface() {
Fixture fixture = new Fixture(configuration);
var result = fixture.create(new SpecimenType<ITestGeneric<String, ITestGenericInside<Integer>>>() {});
assertThat(result).isInstanceOf(ITestGeneric.class);
assertThat(result.publicField).isInstanceOf(Integer.class);
assertThat(result.getT()).isInstanceOf(String.class);
assertThat(result.getU()).isInstanceOf(ITestGenericInside.class);
assertThat(result.getU().getOptionalBoolean()).isInstanceOf(Optional.class);
assertThat(result.getU().getOptionalBoolean()).isPresent();
assertThat(result.getU().getOptionalBoolean().get()).isInstanceOf(Boolean.class);
assertThat(result.getU().getOptionalT()).isInstanceOf(Optional.class);
assertThat(result.getU().getOptionalT()).isPresent();
assertThat(result.getU().getOptionalT().get()).isInstanceOf(Integer.class);
assertThat(result.getU().getTestGeneric()).isInstanceOf(TestObjectGeneric.class);
assertThat(result.getU().getTestGeneric().getT()).isInstanceOf(String.class);
assertThat(result.getU().getTestGeneric().getU()).isInstanceOf(Integer.class);
}
@Test
void canCreateMapsAndLists() {
Fixture fixture = new Fixture(configuration);
var result = fixture.create(new SpecimenType<Map<String, Map<String, List<Optional<String>>>>>() {});
assertThat(result).isInstanceOf(Map.class);
assertThat(result.values()).isNotEmpty();
var subMap = result.values().iterator().next();
assertThat(subMap).isInstanceOf(Map.class);
assertThat(subMap.values()).isNotEmpty();
var innerList = subMap.values().iterator().next();
assertThat(innerList).isNotEmpty();
assertThat(innerList.get(0)).isInstanceOf(Optional.class);
assertThat(innerList.get(0)).isPresent();
assertThat(innerList.get(0).get()).isInstanceOf(String.class);
assertThat(innerList.get(0).get()).isNotEmpty();
}
@Test
void canCreateEnumSets() {
Fixture fixture = new Fixture(new Configuration().collectionSizeRange(2, 2));
var result = fixture.create(TestObjectWithEnumSet.class);
assertThat(result.getId()).isNotBlank();
assertThat(result.getEnums()).isNotEmpty();
assertThat(result.getEnums().iterator().next()).isInstanceOf(TestEnum.class);
}
@Test
void canCreateEnumMaps() {
Fixture fixture = new Fixture(new Configuration().collectionSizeRange(2, 2));
var result = fixture.create(TestObjectWithEnumMap.class);
assertThat(result.getId()).isNotBlank();
assertThat(result.getEnums()).isNotEmpty();
assertThat(result.getEnums().keySet().iterator().next()).isInstanceOf(TestEnum.class);
}
@Test
void canCreateMany() {
Fixture fixture = new Fixture(configuration);
var result = fixture.createMany(new SpecimenType<Optional<Integer>>() {}).collect(toList());
assertThat(result).isNotNull();
assertThat(result).isNotEmpty();
assertThat(result.get(0)).isInstanceOf(Optional.class);
assertThat(result.get(0)).isPresent();
assertThat(result.get(0).get()).isInstanceOf(Integer.class);
}
@Test
void canAddManyTo() {
Fixture fixture = new Fixture(configuration);
List<Optional<String>> result = new ArrayList<>();
result.add(Optional.of("existing"));
fixture.addManyTo(result, new SpecimenType<>() {});
assertThat(result).isNotNull();
assertThat(result.size()).isEqualTo(4);
assertThat(result.get(0)).isPresent();
assertThat(result.get(0).get()).isEqualTo("existing");
assertThat(result.get(1)).isInstanceOf(Optional.class);
assertThat(result.get(1)).isPresent();
assertThat(result.get(1).get()).isInstanceOf(String.class);
assertThat(result.get(1).get()).isNotEmpty();
}
@Test
void canBeCustomized() {
Fixture fixture = new Fixture(configuration);
var result = fixture.build(new SpecimenType<TestObjectGeneric<List<String>, String>>() {})
.without("primitiveInt")
.without("string")
.with("u", "foo")
.with(x -> x.getT().add("bar"))
.create();
assertThat(result.getT()).isInstanceOf(List.class);
assertThat(result.getT().size()).isGreaterThan(1);
assertThat(result.getT().get(result.getT().size() - 1)).isEqualTo("bar");
assertThat(result.getU()).isEqualTo("foo");
assertThat(result.getString()).isNull();
assertThat(result.getPrimitiveInt()).isEqualTo(0);
}
@Test
void canBeCustomizedWithType() {
Fixture sut = new Fixture(configuration);
var expected = new TestObjectGeneric<String, Integer>();
var result = sut.build(TestObjectWithDeepNesting.class)
.with(new SpecimenType<>() {}, expected)
.create();
var actual = result.getNested().getGeneric();
assertThat(actual).isSameAs(expected);
}
@Test
void createThroughRandomConstructor() {
Fixture fixture = new Fixture(configuration);
var result = fixture.construct(new SpecimenType<TestObjectWithGenericConstructor>() {});
assertThat(result).isInstanceOf(TestObjectWithGenericConstructor.class);
assertThat(result.getValue()).isInstanceOf(String.class);
assertThat(result.getInteger()).isInstanceOf(Optional.class);
assertThat(result.getInteger()).isPresent();
assertThat(result.getInteger().get()).isInstanceOf(Integer.class);
assertThat(result.getPrivateField()).isNull();
}
}
@Test
@Disabled("This is a known bug")
void customizeFieldInNestedDerivedClass() {
var fixture = new Fixture();
var result = fixture.build(TestClassWithNestedClasses.NestedStaticDerivedClass.class)
.with("string", "foo")
.create();
assertThat(result.getStrings()).isNotEmpty();
assertThat(result.getString()).isEqualTo("foo");
}
}
|
package hello.controllers;
import static org.hamcrest.core.StringContains.containsString;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import hello.configuration.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
public class GreetingControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void getGreeting() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/greeting").accept(MediaType.TEXT_HTML)).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello, World!")));
}
@Test
public void getJsonGreeting() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/greeting").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().string(containsString("Hello, World!")));
}
@Test
public void getGreetingName() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/greeting?name=Rob").accept(MediaType.TEXT_HTML))
.andExpect(status().isOk()).andExpect(content().string(containsString("Hello, Rob!")));
}
@Test
public void getJsonGreetingName() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/greeting?name=Rob").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().string(containsString("Hello, Rob!")));
}
}
|
package mho.wheels.iterables;
import mho.wheels.random.IsaacPRNG;
import mho.wheels.structures.Pair;
import mho.wheels.structures.Triple;
import java.math.BigInteger;
import java.util.List;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.testing.Testing.*;
@SuppressWarnings({"UnusedDeclaration", "ConstantConditions"})
public class RandomProviderDemos {
private static final boolean USE_RANDOM = false;
private static final int SMALL_LIMIT = 1000;
private static int LIMIT;
private static IterableProvider P;
private static void initialize() {
if (USE_RANDOM) {
P = RandomProvider.EXAMPLE;
LIMIT = 1000;
} else {
P = ExhaustiveProvider.INSTANCE;
LIMIT = 10000;
}
}
private static void demoConstructor() {
initialize();
for (Void v : take(LIMIT, repeat((Void) null))) {
System.out.println("RandomProvider() = " + new RandomProvider());
}
}
private static void demoConstructor_List_Integer() {
initialize();
for (List<Integer> is : take(LIMIT, P.lists(IsaacPRNG.SIZE, P.integers()))) {
System.out.println("RandomProvider(" + is + ") = " + new RandomProvider(is));
}
}
private static void demoGetScale() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println("getScale(" + rp + ") = " + rp.getScale());
}
}
private static void demoGetSecondaryScale() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println("getSecondaryScale(" + rp + ") = " + rp.getSecondaryScale());
}
}
private static void demoGetSeed() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println("getSeed(" + rp + ") = " + rp.getSeed());
}
}
private static void demoAlt() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println("alt(" + rp + ") = " + rp.alt());
}
}
private static void demoWithScale() {
initialize();
for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProviders(), P.alt().naturalIntegers()))) {
System.out.println("withScale(" + p.a + ", " + p.b + ") = " + p.a.withScale(p.b));
}
}
private static void demoWithSecondaryScale() {
initialize();
for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProviders(), P.alt().naturalIntegers()))) {
System.out.println("withSecondaryScale(" + p.a + ", " + p.b + ") = " + p.a.withSecondaryScale(p.b));
}
}
private static void demoBooleans() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("booleans(" + rp + ") = " + its(rp.booleans()));
}
}
private static void demoIntegers() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("integers(" + rp + ") = " + its(rp.integers()));
}
}
private static void demoLongs() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("longs(" + rp + ") = " + its(rp.longs()));
}
}
private static void demoUniformSample_Iterable() {
initialize();
Iterable<Pair<RandomProvider, List<Integer>>> ps = P.pairs(
P.randomProvidersDefault(),
P.alt().lists(P.alt().withNull(P.alt().integers()))
);
for (Pair<RandomProvider, List<Integer>> p : take(SMALL_LIMIT, ps)) {
String listString = tail(init(p.b.toString()));
System.out.println("uniformSample(" + p.a + ", " + listString + ") = " + its(p.a.uniformSample(p.b)));
}
}
private static void demoUniformSample_String() {
initialize();
Iterable<Pair<RandomProvider, String>> ps = P.pairs(P.randomProvidersDefault(), P.alt().strings());
for (Pair<RandomProvider, String> p : take(SMALL_LIMIT, ps)) {
System.out.println("uniformSample(" + p.a + ", " + nicePrint(p.b) + ") = " +
cits(p.a.uniformSample(p.b)));
}
}
private static void demoOrderings() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("orderings(" + rp + ") = " + its(rp.orderings()));
}
}
private static void demoRoundingModes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("roundingModes(" + rp + ") = " + its(rp.roundingModes()));
}
}
private static void demoPositiveBytes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveBytes(" + rp + ") = " + its(rp.positiveBytes()));
}
}
private static void demoPositiveShorts() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveShorts(" + rp + ") = " + its(rp.positiveShorts()));
}
}
private static void demoPositiveIntegers() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveIntegers(" + rp + ") = " + its(rp.positiveIntegers()));
}
}
private static void demoPositiveLongs() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveLongs(" + rp + ") = " + its(rp.positiveLongs()));
}
}
private static void demoNegativeBytes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeBytes(" + rp + ") = " + its(rp.negativeBytes()));
}
}
private static void demoNegativeShorts() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeShorts(" + rp + ") = " + its(rp.negativeShorts()));
}
}
private static void demoNegativeIntegers() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeIntegers(" + rp + ") = " + its(rp.negativeIntegers()));
}
}
private static void demoNegativeLongs() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeLongs(" + rp + ") = " + its(rp.negativeLongs()));
}
}
private static void demoNaturalBytes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("naturalBytes(" + rp + ") = " + its(rp.naturalBytes()));
}
}
private static void demoNaturalShorts() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("naturalShorts(" + rp + ") = " + its(rp.naturalShorts()));
}
}
private static void demoNaturalIntegers() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("naturalIntegers(" + rp + ") = " + its(rp.naturalIntegers()));
}
}
private static void demoNaturalLongs() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("naturalLongs(" + rp + ") = " + its(rp.naturalLongs()));
}
}
private static void demoNonzeroBytes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroBytes(" + rp + ") = " + its(rp.nonzeroBytes()));
}
}
private static void demoNonzeroShorts() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroShorts(" + rp + ") = " + its(rp.nonzeroShorts()));
}
}
private static void demoNonzeroIntegers() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroIntegers(" + rp + ") = " + its(rp.nonzeroIntegers()));
}
}
private static void demoNonzeroLongs() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroLongs(" + rp + ") = " + its(rp.nonzeroLongs()));
}
}
private static void demoBytes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("bytes(" + rp + ") = " + its(rp.bytes()));
}
}
private static void demoShorts() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("shorts(" + rp + ") = " + its(rp.shorts()));
}
}
private static void demoAsciiCharacters() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("asciiCharacters(" + rp + ") = " + cits(rp.asciiCharacters()));
}
}
private static void demoCharacters() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("characters(" + rp + ") = " + cits(rp.characters()));
}
}
private static void demoRangeUp_byte() {
initialize();
for (Pair<RandomProvider, Byte> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.alt().bytes()))) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoRangeUp_short() {
initialize();
Iterable<Pair<RandomProvider, Short>> ps = P.pairs(P.randomProvidersDefault(), P.alt().shorts());
for (Pair<RandomProvider, Short> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoRangeUp_int() {
initialize();
Iterable<Pair<RandomProvider, Integer>> ps = P.pairs(P.randomProvidersDefault(), P.alt().integers());
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoRangeUp_long() {
initialize();
for (Pair<RandomProvider, Long> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.alt().longs()))) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoRangeUp_char() {
initialize();
Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.alt().characters());
for (Pair<RandomProvider, Character> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + nicePrint(p.b) + ") = " + cits(p.a.rangeUp(p.b)));
}
}
private static void demoRangeDown_byte() {
initialize();
for (Pair<RandomProvider, Byte> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.alt().bytes()))) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoRangeDown_short() {
initialize();
Iterable<Pair<RandomProvider, Short>> ps = P.pairs(P.randomProvidersDefault(), P.alt().shorts());
for (Pair<RandomProvider, Short> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoRangeDown_int() {
initialize();
Iterable<Pair<RandomProvider, Integer>> ps = P.pairs(P.randomProvidersDefault(), P.alt().integers());
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoRangeDown_long() {
initialize();
for (Pair<RandomProvider, Long> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.alt().longs()))) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoRangeDown_char() {
initialize();
Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.alt().characters());
for (Pair<RandomProvider, Character> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + nicePrint(p.b) + ") = " + cits(p.a.rangeDown(p.b)));
}
}
private static void demoRange_byte_byte() {
initialize();
Iterable<Triple<RandomProvider, Byte, Byte>> ts = P.triples(
P.randomProvidersDefault(),
P.alt().bytes(),
P.alt().alt().bytes()
);
for (Triple<RandomProvider, Byte, Byte> p : take(LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c)));
}
}
private static void demoRange_short_short() {
initialize();
Iterable<Triple<RandomProvider, Short, Short>> ts = P.triples(
P.randomProvidersDefault(),
P.alt().shorts(),
P.alt().alt().shorts()
);
for (Triple<RandomProvider, Short, Short> p : take(LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c)));
}
}
private static void demoRange_int_int() {
initialize();
Iterable<Triple<RandomProvider, Integer, Integer>> ts = P.triples(
P.randomProvidersDefault(),
P.alt().integers(),
P.alt().alt().integers()
);
for (Triple<RandomProvider, Integer, Integer> p : take(LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c)));
}
}
private static void demoRange_long_long() {
initialize();
Iterable<Triple<RandomProvider, Long, Long>> ts = P.triples(
P.randomProvidersDefault(),
P.alt().longs(),
P.alt().alt().longs()
);
for (Triple<RandomProvider, Long, Long> p : take(LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c)));
}
}
private static void demoRange_BigInteger_BigInteger() {
initialize();
Iterable<Triple<RandomProvider, BigInteger, BigInteger>> ts = P.triples(
P.randomProvidersDefault(),
P.alt().bigIntegers(),
P.alt().alt().bigIntegers()
);
for (Triple<RandomProvider, BigInteger, BigInteger> p : take(LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c)));
}
}
private static void demoRange_char_char() {
initialize();
Iterable<Triple<RandomProvider, Character, Character>> ts = P.triples(
P.randomProvidersDefault(),
P.alt().characters(),
P.alt().alt().characters()
);
for (Triple<RandomProvider, Character, Character> p : take(SMALL_LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + cits(p.a.range(p.b, p.c)));
}
}
private static void demoPositiveIntegersGeometric() {
initialize();
Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale());
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("positiveIntegersGeometric(" + rp + ") = " + its(rp.positiveIntegersGeometric()));
}
}
private static void demoNegativeIntegersGeometric() {
initialize();
Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale());
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("negativeIntegersGeometric(" + rp + ") = " + its(rp.negativeIntegersGeometric()));
}
}
private static void demoNaturalIntegersGeometric() {
initialize();
Iterable<RandomProvider> rps = filter(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("naturalIntegersGeometric(" + rp + ") = " + its(rp.naturalIntegersGeometric()));
}
}
private static void demoNonzeroIntegersGeometric() {
initialize();
Iterable<RandomProvider> rps = filter(x -> x.getScale() >= 2, P.randomProvidersDefaultSecondaryScale());
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nonzeroIntegersGeometric(" + rp + ") = " + its(rp.nonzeroIntegersGeometric()));
}
}
private static void demoIntegersGeometric() {
initialize();
Iterable<RandomProvider> rps = filter(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("integersGeometric(" + rp + ") = " + its(rp.integersGeometric()));
}
}
private static void demoRangeUpGeometric() {
initialize();
Iterable<Pair<RandomProvider, Integer>> ps = filter(
p -> p.a.getScale() > p.b && (p.b > 1 || p.a.getScale() >= Integer.MAX_VALUE + p.b),
P.pairs(P.randomProvidersDefaultSecondaryScale(), P.alt().alt().integersGeometric())
);
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUpGeometric(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUpGeometric(p.b)));
}
}
private static void demoRangeDownGeometric() {
initialize();
Iterable<Pair<RandomProvider, Integer>> ps = filter(
p -> p.a.getScale() < p.b && (p.b <= -1 || p.a.getScale() > p.b - Integer.MAX_VALUE),
P.pairs(P.randomProvidersDefaultSecondaryScale(), P.alt().alt().integersGeometric())
);
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDownGeometric(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDownGeometric(p.b)));
}
}
private static void demoEquals_RandomProvider() {
initialize();
for (Pair<RandomProvider, RandomProvider> p : take(LIMIT, P.pairs(P.randomProviders()))) {
System.out.println(p.a + (p.a.equals(p.b) ? " = " : " ≠ ") + p.b);
}
}
private static void demoEquals_null() {
initialize();
for (RandomProvider r : take(LIMIT, P.randomProviders())) {
//noinspection ObjectEqualsNull
System.out.println(r + (r.equals(null) ? " = " : " ≠ ") + null);
}
}
private static void demoHashCode() {
initialize();
for (RandomProvider r : take(LIMIT, P.randomProviders())) {
System.out.println("hashCode(" + r + ") = " + r.hashCode());
}
}
private static void demoToString() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println(rp);
}
}
}
|
package org.mutabilitydetector;
import org.junit.Test;
import org.mutabilitydetector.unittesting.MutabilityAssertionError;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertImmutable;
@SuppressWarnings("ALL")
public class ErrorLocationTest {
// ArrayFieldMutabilityChecker: code location points to the field (correct).
// Potential Improvements: Line number. Whole declaration of the field with access modifier, type etc...
public final static class ClassWithArrayField {
private final int[] arrayField = null;
}
@Test
public void isImmutableClassWithArrayField() throws Exception {
try {
assertImmutable(ClassWithArrayField.class);
} catch (MutabilityAssertionError e) {
assertEquals(e.getMessage(),
"\n" +
"Expected: org.mutabilitydetector.ErrorLocationTest$ClassWithArrayField to be IMMUTABLE\n" +
" but: org.mutabilitydetector.ErrorLocationTest$ClassWithArrayField is actually NOT_IMMUTABLE\n" +
" Reasons:\n" +
" Field is an array. [Field: arrayField, Class: org.mutabilitydetector.ErrorLocationTest$ClassWithArrayField]\n" +
" Allowed reasons:\n" +
" None.");
}
}
// CollectionWithMutableElementTypeToFieldChecker: code location points to the field, as well as the collection declaration with the mutable type (correct)
// Potential improvements: Line number.
// Other improvements: avoid multiple reasons for this case (ABSTRACT_COLLECTION_TYPE_TO_FIELD, COLLECTION_FIELD_WITH_MUTABLE_ELEMENT_TYPE)
public final static class MutableClass {
public String publicField;
}
public final static class ClassWithCollectionWithMutableElementTypeToField {
private final List<MutableClass> collectionWithMutableType = new ArrayList<MutableClass>();
}
@Test
public void isImmutableCollectionWithMutableElementTypeToField() throws Exception {
try {
assertImmutable(ClassWithCollectionWithMutableElementTypeToField.class);
} catch (MutabilityAssertionError e) {
assertEquals(e.getMessage(),
"\n" +
"Expected: org.mutabilitydetector.ErrorLocationTest$ClassWithCollectionWithMutableElementTypeToField to be IMMUTABLE\n" +
" but: org.mutabilitydetector.ErrorLocationTest$ClassWithCollectionWithMutableElementTypeToField is actually NOT_IMMUTABLE\n" +
" Reasons:\n" +
" Field can have a mutable type (java.util.ArrayList) assigned to it. [Field: collectionWithMutableType, Class: org.mutabilitydetector.ErrorLocationTest$ClassWithCollectionWithMutableElementTypeToField]\n" +
" Field can have collection with mutable element type (java.util.List<org.mutabilitydetector.ErrorLocationTest$MutableClass>) assigned to it. [Field: collectionWithMutableType, Class: org.mutabilitydetector.ErrorLocationTest$ClassWithCollectionWithMutableElementTypeToField]\n" +
" Allowed reasons:\n" +
" None.");
}
}
// MutableTypeToFieldChecker
// TODO: finish this one
// CanSubclassChecker: code location points to the class (correct).
// Potential improvements: Class declaration line with access modifier, etc. List of available subclasses if there are already any.
public static class NonFinalClass {
}
@Test
public void isImmutableCanSubclass() throws Exception {
try {
assertImmutable(NonFinalClass.class);
} catch (MutabilityAssertionError e) {
assertEquals(e.getMessage(),
"\n" +
"Expected: org.mutabilitydetector.ErrorLocationTest$NonFinalClass to be IMMUTABLE\n" +
" but: org.mutabilitydetector.ErrorLocationTest$NonFinalClass is actually NOT_IMMUTABLE\n" +
" Reasons:\n" +
" Can be subclassed, therefore parameters declared to be this type could be mutable subclasses at runtime. [Class: org.mutabilitydetector.ErrorLocationTest$NonFinalClass]\n" +
" Allowed reasons:\n" +
" None.");
}
}
// InherentTypeMutabilityChecker: code location points to the class (correct).
// Other improvements: change output to "is declared as an interface" for interfaces. Avoid multiple reasons for abstract classes (ABSTRACT_TYPE_INHERENTLY_MUTABLE + CAN_BE_SUBCLASSED)
public abstract static class AbstractClass {
}
public static interface AnInterface {
}
@Test
public void isImmutableInherentlyMutable_Abstract() throws Exception {
try {
assertImmutable(AbstractClass.class);
} catch (MutabilityAssertionError e) {
assertEquals(e.getMessage(),
"\n" +
"Expected: org.mutabilitydetector.ErrorLocationTest$AbstractClass to be IMMUTABLE\n" +
" but: org.mutabilitydetector.ErrorLocationTest$AbstractClass is actually NOT_IMMUTABLE\n" +
" Reasons:\n" +
" Can be subclassed, therefore parameters declared to be this type could be mutable subclasses at runtime. [Class: org.mutabilitydetector.ErrorLocationTest$AbstractClass]\n" +
" Is inherently mutable, as declared as an abstract type. [Class: org.mutabilitydetector.ErrorLocationTest$AbstractClass]\n" +
" Allowed reasons:\n" +
" None.");
}
}
@Test
public void isImmutableInherentlyMutable_Interface() throws Exception {
try {
assertImmutable(AnInterface.class);
} catch (MutabilityAssertionError e) {
assertEquals(e.getMessage(),
"\n" +
"Expected: org.mutabilitydetector.ErrorLocationTest$AnInterface to be IMMUTABLE\n" +
" but: org.mutabilitydetector.ErrorLocationTest$AnInterface is actually NOT_IMMUTABLE\n" +
" Reasons:\n" +
" Is inherently mutable, as declared as an abstract type. [Class: org.mutabilitydetector.ErrorLocationTest$AnInterface]\n" +
" Allowed reasons:\n" +
" None.");
}
}
// NonFinalFieldChecker: code location points to the field (correct).
// Potential improvements: Line number. Field declaration with access modifiers, etc...
public final static class ClassWithNonFinalField {
private String publicField;
}
@Test
public void isImmutableNonFinalField() throws Exception {
try {
assertImmutable(ClassWithNonFinalField.class);
} catch (MutabilityAssertionError e) {
assertEquals(e.getMessage(),
"\n" +
"Expected: org.mutabilitydetector.ErrorLocationTest$ClassWithNonFinalField to be IMMUTABLE\n" +
" but: org.mutabilitydetector.ErrorLocationTest$ClassWithNonFinalField is actually EFFECTIVELY_IMMUTABLE\n" +
" Reasons:\n" +
" Field is not final, if shared across threads the Java Memory Model will not guarantee it is initialised before it is read. [Field: publicField, Class: org.mutabilitydetector.ErrorLocationTest$ClassWithNonFinalField]\n" +
" Allowed reasons:\n" +
" None.");
}
}
// PublishedNonFinalFieldChecker: code location points to the field and class (correct).
// Potential improvements: Line number. Field declaration with access modifiers, etc...
// Other Improvements: avoid multiple reasons (PUBLISHED_NON_FINAL_FIELD, NON_FINAL_FIELD)
public final static class ClassWithPublicNonFinalField {
public String publicField;
}
public final static class ClassWithProtectedNonFinalField {
protected String publicField;
}
@Test
public void isImmutablePublishedNonFinalField_Public() throws Exception {
try {
assertImmutable(ClassWithPublicNonFinalField.class);
} catch (MutabilityAssertionError e) {
assertEquals(e.getMessage(),
"\n" +
"Expected: org.mutabilitydetector.ErrorLocationTest$ClassWithPublicNonFinalField to be IMMUTABLE\n" +
" but: org.mutabilitydetector.ErrorLocationTest$ClassWithPublicNonFinalField is actually NOT_IMMUTABLE\n" +
" Reasons:\n" +
" Field is visible outwith this class, and is not declared final. [Field: publicField, Class: org.mutabilitydetector.ErrorLocationTest$ClassWithPublicNonFinalField]\n" +
" Field is not final, if shared across threads the Java Memory Model will not guarantee it is initialised before it is read. [Field: publicField, Class: org.mutabilitydetector.ErrorLocationTest$ClassWithPublicNonFinalField]\n" +
" Allowed reasons:\n" +
" None.");
}
}
@Test
public void isImmutablePublishedNonFinalField_Protected() throws Exception {
try {
assertImmutable(ClassWithPublicNonFinalField.class);
} catch (MutabilityAssertionError e) {
assertEquals(e.getMessage(),
"\n" +
"Expected: org.mutabilitydetector.ErrorLocationTest$ClassWithPublicNonFinalField to be IMMUTABLE\n" +
" but: org.mutabilitydetector.ErrorLocationTest$ClassWithPublicNonFinalField is actually NOT_IMMUTABLE\n" +
" Reasons:\n" +
" Field is visible outwith this class, and is not declared final. [Field: publicField, Class: org.mutabilitydetector.ErrorLocationTest$ClassWithPublicNonFinalField]\n" +
" Field is not final, if shared across threads the Java Memory Model will not guarantee it is initialised before it is read. [Field: publicField, Class: org.mutabilitydetector.ErrorLocationTest$ClassWithPublicNonFinalField]\n" +
" Allowed reasons:\n" +
" None.");
}
}
// OldSetterMethodChecker: code location points to the field and class, name of the setter method is displayed. This is not wrong but actually just the name of the setter method and the class would be needed.
// Potential improvements: Line number.
// Other Improvements: avoid multiple reasons (FIELD_CAN_BE_REASSIGNED, NON_FINAL_FIELD)
public final static class ClassWithSetterMethod {
private String field;
public void setField(String field) {
this.field = field;
}
}
@Test
public void isImmutableClassWithSetterMethod() throws Exception {
try {
assertImmutable(ClassWithSetterMethod.class);
} catch (MutabilityAssertionError e) {
assertEquals(e.getMessage(),
"\n" +
"Expected: org.mutabilitydetector.ErrorLocationTest$ClassWithSetterMethod to be IMMUTABLE\n" +
" but: org.mutabilitydetector.ErrorLocationTest$ClassWithSetterMethod is actually NOT_IMMUTABLE\n" +
" Reasons:\n" +
" Field is not final, if shared across threads the Java Memory Model will not guarantee it is initialised before it is read. [Field: field, Class: org.mutabilitydetector.ErrorLocationTest$ClassWithSetterMethod]\n" +
" Field [field] can be reassigned within method [setField] [Field: field, Class: org.mutabilitydetector.ErrorLocationTest$ClassWithSetterMethod]\n" +
" Allowed reasons:\n" +
" None.");
}
}
// EscapedThisReferenceChecker: code location points to the class passing the this reference (ok).
// Potential improvements: Line number where this reference is passed.
// Other Improvements: avoid multiple reasons (FIELD_CAN_BE_REASSIGNED, NON_FINAL_FIELD)
public final class ClassWithThisReference {
private final ClassPassingThisReference thisReference;
public ClassWithThisReference(ClassPassingThisReference thisReference) {
this.thisReference = thisReference;
}
}
public final class ClassPassingThisReference {
private final ClassWithThisReference field;
public ClassPassingThisReference() {
this.field = new ClassWithThisReference(this);
}
}
@Test
public void isImmutableClassPassingThisReference() throws Exception {
try {
assertImmutable(ClassPassingThisReference.class);
} catch (MutabilityAssertionError e) {
assertEquals(e.getMessage(),
"\n" +
"Expected: org.mutabilitydetector.ErrorLocationTest$ClassPassingThisReference to be IMMUTABLE\n" +
" but: org.mutabilitydetector.ErrorLocationTest$ClassPassingThisReference is actually NOT_IMMUTABLE\n" +
" Reasons:\n" +
" Field can have a mutable type (org.mutabilitydetector.ErrorLocationTest) assigned to it. [Field: this$0, Class: org.mutabilitydetector.ErrorLocationTest$ClassPassingThisReference]\n" +
" Field can have a mutable type (org.mutabilitydetector.ErrorLocationTest$ClassWithThisReference) assigned to it. [Field: field, Class: org.mutabilitydetector.ErrorLocationTest$ClassPassingThisReference]\n" +
" The 'this' reference is passed outwith the constructor. [Class: org.mutabilitydetector.ErrorLocationTest$ClassPassingThisReference]\n" +
" Allowed reasons:\n" +
" None.");
}
}
}
|
package org.mvel2.tests.core;
import org.mvel2.*;
import static org.mvel2.MVEL.*;
import org.mvel2.ast.ASTNode;
import org.mvel2.compiler.AbstractParser;
import org.mvel2.compiler.CompiledExpression;
import org.mvel2.compiler.ExpressionCompiler;
import org.mvel2.integration.Interceptor;
import org.mvel2.integration.PropertyHandlerFactory;
import org.mvel2.integration.ResolverTools;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.ClassImportResolverFactory;
import org.mvel2.integration.impl.DefaultLocalVariableResolverFactory;
import org.mvel2.integration.impl.MapVariableResolverFactory;
import org.mvel2.integration.impl.StaticMethodImportResolverFactory;
import org.mvel2.optimizers.OptimizerFactory;
import org.mvel2.tests.core.res.*;
import org.mvel2.util.MethodStub;
import org.mvel2.util.ReflectionUtil;
import java.awt.*;
import java.io.BufferedReader;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.util.Collections.unmodifiableCollection;
import java.util.List;
@SuppressWarnings({"ALL"})
public class CoreConfidenceTests extends AbstractTest {
public void testWhileUsingImports() {
Map<String, Object> imports = new HashMap<String, Object>();
imports.put("ArrayList", java.util.ArrayList.class);
imports.put("List", java.util.List.class);
ParserContext context = new ParserContext(imports, null, "testfile");
ExpressionCompiler compiler = new ExpressionCompiler("List list = new ArrayList(); return (list == empty)");
assertTrue((Boolean) executeExpression(compiler.compile(context), new DefaultLocalVariableResolverFactory()));
}
public void testBooleanModeOnly2() {
assertEquals(false, (Object) DataConversion.convert(test("BWAH"), Boolean.class));
}
public void testBooleanModeOnly4() {
assertEquals(true, test("hour == (hour + 0)"));
}
// interpreted
public void testThisReferenceMapVirtualObjects() {
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap<String, Object>());
factory.createVariable("this", map);
assertEquals(true, eval("this.foo == 'bar'", map, factory));
}
// compiled - reflective
public void testThisReferenceMapVirtualObjects1() {
// Create our root Map object
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap<String, Object>());
factory.createVariable("this", map);
OptimizerFactory.setDefaultOptimizer("reflective");
// Run test
assertEquals(true, executeExpression(compileExpression("this.foo == 'bar'"), map, factory));
}
// compiled - asm
public void testThisReferenceMapVirtualObjects2() {
// Create our root Map object
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap<String, Object>());
factory.createVariable("this", map);
// I think we can all figure this one out.
if (!Boolean.getBoolean("mvel2.disable.jit")) OptimizerFactory.setDefaultOptimizer("ASM");
// Run test
assertEquals(true, executeExpression(compileExpression("this.foo == 'bar'"), map, factory));
}
public void testEvalToBoolean() {
assertEquals(true, (boolean) evalToBoolean("true ", "true"));
assertEquals(true, (boolean) evalToBoolean("true ", "true"));
}
public void testImport() {
assertEquals(HashMap.class, test("import java.util.HashMap; HashMap;"));
}
public void testImport2() {
HashMap[] maps = (HashMap[]) MVEL.eval("import java.util.*; HashMap[] maps = new HashMap[10]; maps", new HashMap());
// HashMap[] maps = (HashMap[]) test("import java.util.*; HashMap[] maps = new HashMap[10]; maps");
assertEquals(10, maps.length);
}
public void testStaticImport() {
assertEquals(2.0, test("import_static java.lang.Math.sqrt; sqrt(4)"));
}
/**
* Start collections framework based compliance tests
*/
public void testCreationOfSet() {
assertEquals("foo bar foo bar",
test("set = new java.util.LinkedHashSet(); " +
"set.add('foo');" +
"set.add('bar');" +
"output = '';" +
"foreach (item : set) {" +
"output = output + item + ' ';" +
"} " +
"foreach (item : set) {" +
"output = output + item + ' ';" +
"} " +
"output = output.trim();" +
"if (set.size() == 2) { return output; }"));
}
public void testCreationOfList() {
assertEquals(5, test("l = new java.util.LinkedList();" +
"l.add('fun');" +
"l.add('happy');" +
"l.add('fun');" +
"l.add('slide');" +
"l.add('crap');" +
"poo = new java.util.ArrayList(l);" +
"poo.size();"));
}
public void testMapOperations() {
assertEquals("poo5", test(
"l = new java.util.ArrayList();" +
"l.add('plop');" +
"l.add('poo');" +
"m = new java.util.HashMap();" +
"m.put('foo', l);" +
"m.put('cah', 'mah');" +
"m.put('bar', 'foo');" +
"m.put('sarah', 'mike');" +
"m.put('edgar', 'poe');" +
"" +
"if (m.edgar == 'poe') {" +
"return m.foo[1] + m.size();" +
"}"));
}
public void testStackOperations() {
assertEquals(10, test(
"stk = new java.util.Stack();" +
"stk.push(5);" +
"stk.push(5);" +
"stk.pop() + stk.pop();"
));
}
public void testSystemOutPrint() {
test("a = 0;\r\nSystem.out.println('This is a test');");
}
public void testVarInputs() {
ParserContext pCtx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler("test != foo && bo.addSomething(trouble) && 1 + 2 / 3 == 1; String bleh = foo; twa = bleh;");
compiler.setVerifyOnly(true);
compiler.compile(pCtx);
assertEquals(4, pCtx.getInputs().size());
assertTrue(pCtx.getInputs().containsKey("test"));
assertTrue(pCtx.getInputs().containsKey("foo"));
assertTrue(pCtx.getInputs().containsKey("bo"));
assertTrue(pCtx.getInputs().containsKey("trouble"));
assertEquals(2, pCtx.getVariables().size());
assertTrue(pCtx.getVariables().containsKey("bleh"));
assertTrue(pCtx.getVariables().containsKey("twa"));
assertEquals(String.class, pCtx.getVarOrInputType("bleh"));
}
public void testVarInputs2() {
ExpressionCompiler compiler = new ExpressionCompiler("test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;");
ParserContext ctx = new ParserContext();
ctx.setRetainParserState(true);
compiler.compile(ctx);
System.out.println(ctx.getVarOrInputType("bleh"));
}
public void testVarInputs3() {
ExpressionCompiler compiler = new ExpressionCompiler("addresses['home'].street");
compiler.compile();
assertFalse(compiler.getParserContextState().getInputs().keySet().contains("home"));
}
public void testVarInputs4() {
ExpressionCompiler compiler = new ExpressionCompiler("System.out.println( message );");
compiler.compile();
assertTrue(compiler.getParserContextState().getInputs().keySet().contains("message"));
}
public void testAnalyzer() {
ExpressionCompiler compiler = new ExpressionCompiler("order.id == 10");
compiler.compile();
for (String input : compiler.getParserContextState().getInputs().keySet()) {
System.out.println("input>" + input);
}
assertEquals(1, compiler.getParserContextState().getInputs().size());
assertTrue(compiler.getParserContextState().getInputs().containsKey("order"));
}
public void testClassImportViaFactory() {
MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
ClassImportResolverFactory classes = new ClassImportResolverFactory();
classes.addClass(HashMap.class);
ResolverTools.appendFactory(mvf, classes);
assertTrue(executeExpression(
compileExpression("HashMap map = new HashMap()", classes.getImportedClasses()), mvf) instanceof HashMap);
}
public void testSataticClassImportViaFactory() {
MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
ClassImportResolverFactory classes = new ClassImportResolverFactory();
classes.addClass(Person.class);
ResolverTools.appendFactory(mvf, classes);
assertEquals("tom",
executeExpression(compileExpression("p = new Person('tom'); return p.name;",
classes.getImportedClasses()), mvf));
}
public void testSataticClassImportViaFactoryAndWithModification() {
OptimizerFactory.setDefaultOptimizer("ASM");
MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
ClassImportResolverFactory classes = new ClassImportResolverFactory();
classes.addClass(Person.class);
ResolverTools.appendFactory(mvf, classes);
assertEquals(21, executeExpression(compileExpression(
"p = new Person('tom'); p.age = 20; with( p ) { age = p.age + 1 }; return p.age;",
classes.getImportedClasses()), mvf));
}
public void testCheeseConstructor() {
MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
ClassImportResolverFactory classes = new ClassImportResolverFactory();
classes.addClass(Cheese.class);
ResolverTools.appendFactory(mvf, classes);
assertTrue(executeExpression(
compileExpression("cheese = new Cheese(\"cheddar\", 15);", classes.getImportedClasses()), mvf) instanceof Cheese);
}
public void testInterceptors() {
Interceptor testInterceptor = new Interceptor() {
public int doBefore(ASTNode node, VariableResolverFactory factory) {
System.out.println("BEFORE Node: " + node.getName());
return 0;
}
public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) {
System.out.println("AFTER Node: " + node.getName());
return 0;
}
};
Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
interceptors.put("test", testInterceptor);
executeExpression(compileExpression("@test System.out.println('MIDDLE');", null, interceptors));
}
public void testExecuteCoercionTwice() {
OptimizerFactory.setDefaultOptimizer("reflective");
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("foo", new Foo());
vars.put("$value", new Long(5));
ExpressionCompiler compiler = new ExpressionCompiler("with (foo) { countTest = $value };");
ParserContext ctx = new ParserContext();
ctx.setSourceFile("test.mv");
ctx.setDebugSymbols(true);
CompiledExpression compiled = compiler.compile(ctx);
executeExpression(compiled, null, vars);
executeExpression(compiled, null, vars);
}
public void testExecuteCoercionTwice2() {
OptimizerFactory.setDefaultOptimizer("ASM");
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("foo", new Foo());
vars.put("$value", new Long(5));
ExpressionCompiler compiler = new ExpressionCompiler("with (foo) { countTest = $value };");
ParserContext ctx = new ParserContext();
ctx.setSourceFile("test.mv");
ctx.setDebugSymbols(true);
CompiledExpression compiled = compiler.compile(ctx);
executeExpression(compiled, null, vars);
executeExpression(compiled, null, vars);
}
public void testComments() {
assertEquals(10, test("// This is a comment\n5 + 5"));
}
public void testComments2() {
assertEquals(20, test("10 + 10; // This is a comment"));
}
public void testComments3() {
assertEquals(30, test("/* This is a test of\r\n" +
"MVEL's support for\r\n" +
"multi-line comments\r\n" +
"*/\r\n 15 + 15"));
}
public void testComments4() {
assertEquals(((10 + 20) * 2) - 10, test("/** This is a fun test script **/\r\n" +
"a = 10;\r\n" +
"/**\r\n" +
"* Here is a useful variable\r\n" +
"*/\r\n" +
"b = 20; // set b to '20'\r\n" +
"return ((a + b) * 2) - 10;\r\n" +
"// last comment\n"));
}
public void testComments5() {
assertEquals("dog", test("foo./*Hey!*/name"));
}
public void testSubtractNoSpace1() {
assertEquals(59, test("hour-1"));
}
public void testStrictTypingCompilation() {
ExpressionCompiler compiler = new ExpressionCompiler("a.foo;\nb.foo;\n x = 5");
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
try {
compiler.compile(ctx);
}
catch (CompileException e) {
e.printStackTrace();
assertEquals(2, e.getErrors().size());
return;
}
assertTrue(false);
}
public void testStrictStaticMethodCall() {
ExpressionCompiler compiler = new ExpressionCompiler("Bar.staticMethod()");
ParserContext ctx = new ParserContext();
ctx.addImport("Bar", Bar.class);
ctx.setStrictTypeEnforcement(true);
Serializable s = compiler.compile(ctx);
assertEquals(1, executeExpression(s));
}
public void testStrictTypingCompilation2() throws Exception {
ParserContext ctx = new ParserContext();
//noinspection RedundantArrayCreation
ctx.addImport("getRuntime", new MethodStub(Runtime.class.getMethod("getRuntime", new Class[]{})));
ctx.setStrictTypeEnforcement(true);
ExpressionCompiler compiler = new ExpressionCompiler("getRuntime()");
StaticMethodImportResolverFactory si = new StaticMethodImportResolverFactory(ctx);
Serializable expression = compiler.compile(ctx);
serializationTest(expression);
assertTrue(executeExpression(expression, si) instanceof Runtime);
}
public void testStrictTypingCompilation3() throws NoSuchMethodException {
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ExpressionCompiler compiler =
new ExpressionCompiler("message='Hello';b=7;\nSystem.out.println(message + ';' + b);\n" +
"System.out.println(message + ';' + b); b");
assertEquals(7, executeExpression(compiler.compile(ctx), new DefaultLocalVariableResolverFactory()));
}
public void testStrictTypingCompilation4() throws NoSuchMethodException {
ParserContext ctx = new ParserContext();
ctx.addImport(Foo.class);
ctx.setStrictTypeEnforcement(true);
ExpressionCompiler compiler =
new ExpressionCompiler("x_a = new Foo()");
compiler.compile(ctx);
assertEquals(Foo.class, ctx.getVariables().get("x_a"));
}
public void testProvidedExternalTypes() {
ExpressionCompiler compiler = new ExpressionCompiler("foo.bar");
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.addInput("foo", Foo.class);
compiler.compile(ctx);
}
public void testEqualityRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("price == (new Integer( 5 ) + 5 ) ");
compiler.compile();
}
public void testEvaluationRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("(p.age * 2)");
compiler.compile();
assertTrue(compiler.getParserContextState().getInputs().containsKey("p"));
}
public void testAssignmentRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("total = total + $cheese.price");
compiler.compile();
}
public void testTypeRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("total = 0");
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
compiler.compile(ctx);
assertEquals(Integer.class,
compiler.getParserContextState().getVarOrInputType("total"));
}
public void testMapPropertyCreateCondensed() {
assertEquals("foo", test("map = new java.util.HashMap(); map['test'] = 'foo'; map['test'];"));
}
public void testClassLiteral() {
assertEquals(String.class, test("java.lang.String"));
}
public void testDeepMethod() {
assertEquals(false, test("foo.bar.testList.add(new String()); foo.bar.testList == empty"));
}
public void testArrayAccessorAssign() {
assertEquals("foo", test("a = {'f00', 'bar'}; a[0] = 'foo'; a[0]"));
}
public void testListAccessorAssign() {
assertEquals("bar", test("a = new java.util.ArrayList(); a.add('foo'); a.add('BAR'); a[1] = 'bar'; a[1]"));
}
public void testBracketInString() {
test("System.out.println('1)your guess was:');");
}
public void testNesting() {
assertEquals("foo", test("new String(new String(new String(\"foo\")));"));
}
public void testTypeCast() {
assertEquals("10", test("(String) 10"));
}
public void testTypeCast2() {
assertEquals(0, test("map = new java.util.HashMap(); map.put('doggie', new java.util.ArrayList()); ((java.util.ArrayList) map['doggie']).size()"));
}
public void testTypeCast3() {
Map map = new HashMap();
map.put("foo", new Foo());
ParserContext pCtx = new ParserContext();
pCtx.setStrongTyping(true);
pCtx.addInput("foo", Foo.class);
Serializable s = MVEL.compileExpression("((org.mvel2.tests.core.res.Bar) foo.getBar()).name != null", pCtx);
assertEquals(true, MVEL.executeExpression(s, map));
assertEquals(1, pCtx.getInputs().size());
assertEquals(true, pCtx.getInputs().containsKey("foo"));
}
public void testMapAccessSemantics() {
Map<String, Object> outermap = new HashMap<String, Object>();
Map<String, Object> innermap = new HashMap<String, Object>();
innermap.put("test", "foo");
outermap.put("innermap", innermap);
assertEquals("foo", testCompiledSimple("innermap['test']", outermap, null));
}
public void testMapBindingSemantics() {
Map<String, Object> outermap = new HashMap<String, Object>();
Map<String, Object> innermap = new HashMap<String, Object>();
innermap.put("test", "foo");
outermap.put("innermap", innermap);
setProperty(outermap, "innermap['test']", "bar");
assertEquals("bar", testCompiledSimple("innermap['test']", outermap, null));
}
public void testMapNestedInsideList() {
ParserContext ctx = new ParserContext();
ctx.addImport("User", User.class);
ExpressionCompiler compiler = new ExpressionCompiler("users = [ 'darth' : new User('Darth', 'Vadar'),\n'bobba' : new User('Bobba', 'Feta') ]; [ users.get('darth'), users.get('bobba') ]");
// Serializable s = compiler.compile(ctx);
List list = (List) executeExpression(compiler.compile(ctx), new HashMap());
User user = (User) list.get(0);
assertEquals("Darth", user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba", user.getFirstName());
compiler = new ExpressionCompiler("users = [ 'darth' : new User('Darth', 'Vadar'),\n'bobba' : new User('Bobba', 'Feta') ]; [ users['darth'], users['bobba'] ]");
list = (List) executeExpression(compiler.compile(ctx), new HashMap());
user = (User) list.get(0);
assertEquals("Darth", user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba", user.getFirstName());
}
public void testListNestedInsideList() {
ParserContext ctx = new ParserContext();
ctx.addImport("User", User.class);
ExpressionCompiler compiler = new ExpressionCompiler("users = [ new User('Darth', 'Vadar'), new User('Bobba', 'Feta') ]; [ users.get( 0 ), users.get( 1 ) ]");
List list = (List) executeExpression(compiler.compile(ctx), new HashMap());
User user = (User) list.get(0);
assertEquals("Darth", user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba", user.getFirstName());
compiler = new ExpressionCompiler("users = [ new User('Darth', 'Vadar'), new User('Bobba', 'Feta') ]; [ users[0], users[1] ]");
list = (List) executeExpression(compiler.compile(ctx), new HashMap());
user = (User) list.get(0);
assertEquals("Darth", user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba", user.getFirstName());
}
public void testSetSemantics() {
Bar bar = new Bar();
Foo foo = new Foo();
assertEquals("dog", MVEL.getProperty("name", bar));
assertEquals("dog", MVEL.getProperty("name", foo));
}
public void testMapBindingSemantics2() {
OptimizerFactory.setDefaultOptimizer("ASM");
Map<String, Object> outermap = new HashMap<String, Object>();
Map<String, Object> innermap = new HashMap<String, Object>();
innermap.put("test", "foo");
outermap.put("innermap", innermap);
executeSetExpression(compileSetExpression("innermap['test']"), outermap, "bar");
assertEquals("bar", testCompiledSimple("innermap['test']", outermap, null));
}
public void testDynamicImports() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("java.util");
ExpressionCompiler compiler = new ExpressionCompiler("HashMap");
Serializable s = compiler.compile(ctx);
assertEquals(HashMap.class, executeExpression(s));
compiler = new ExpressionCompiler("map = new HashMap(); map.size()");
s = compiler.compile(ctx);
assertEquals(0, executeExpression(s, new DefaultLocalVariableResolverFactory()));
}
public void testDynamicImports3() {
String expression = "import java.util.*; HashMap map = new HashMap(); map.size()";
ExpressionCompiler compiler = new ExpressionCompiler(expression);
Serializable s = compiler.compile();
assertEquals(0, executeExpression(s, new DefaultLocalVariableResolverFactory()));
assertEquals(0, MVEL.eval(expression, new HashMap()));
}
public void testDynamicImportsInList() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("[ new User('Bobba', 'Feta') ]");
List list = (List) executeExpression(compiler.compile(ctx));
User user = (User) list.get(0);
assertEquals("Bobba", user.getFirstName());
}
public void testDynamicImportsInMap() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("[ 'bobba' : new User('Bobba', 'Feta') ]");
Map map = (Map) executeExpression(compiler.compile(ctx));
User user = (User) map.get("bobba");
assertEquals("Bobba", user.getFirstName());
}
public void testDynamicImportsOnNestedExpressions() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("new Cheesery(\"bobbo\", new Cheese(\"cheddar\", 15))");
Cheesery p1 = new Cheesery("bobbo", new Cheese("cheddar", 15));
Cheesery p2 = (Cheesery) executeExpression(compiler.compile(ctx), new DefaultLocalVariableResolverFactory());
assertEquals(p1, p2);
}
public void testDynamicImportsWithNullConstructorParam() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("new Cheesery(\"bobbo\", null)");
Cheesery p1 = new Cheesery("bobbo", null);
Cheesery p2 = (Cheesery) executeExpression(compiler.compile(ctx), new DefaultLocalVariableResolverFactory());
assertEquals(p1, p2);
}
public void testDynamicImportsWithIdentifierSameAsClassWithDiffCase() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ctx.setStrictTypeEnforcement(false);
ExpressionCompiler compiler = new ExpressionCompiler("bar.add(\"hello\")");
compiler.compile(ctx);
}
public void testTypedAssignment() {
assertEquals("foobar", test("java.util.Map map = new java.util.HashMap(); map.put('conan', 'foobar'); map['conan'];"));
}
public void testFQCNwithStaticInList() {
assertEquals(Integer.MIN_VALUE, test("list = [java.lang.Integer.MIN_VALUE]; list[0]"));
}
public void testPrecedenceOrder() {
assertTrue((Boolean) test("5 > 6 && 2 < 1 || 10 > 9"));
}
@SuppressWarnings({"unchecked"})
public void testDifferentImplSameCompile() {
Serializable compiled = compileExpression("a.funMap.hello");
Map testMap = new HashMap();
for (int i = 0; i < 100; i++) {
Base b = new Base();
b.funMap.put("hello", "dog");
testMap.put("a", b);
assertEquals("dog", executeExpression(compiled, testMap));
b = new Base();
b.funMap.put("hello", "cat");
testMap.put("a", b);
assertEquals("cat", executeExpression(compiled, testMap));
}
}
@SuppressWarnings({"unchecked"})
public void testInterfaceMethodCallWithSpace() {
Map map = new HashMap();
DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper();
map.put("drools", helper);
Cheese cheese = new Cheese("stilton", 15);
map.put("cheese", cheese);
executeExpression(compileExpression("drools.retract (cheese)"), map);
assertSame(cheese, helper.retracted.get(0));
}
@SuppressWarnings({"unchecked"})
public void testInterfaceMethodCallWithMacro() {
Map macros = new HashMap(1);
macros.put("retract",
new Macro() {
public String doMacro() {
return "drools.retract";
}
});
Map map = new HashMap();
DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper();
map.put("drools", helper);
Cheese cheese = new Cheese("stilton", 15);
map.put("cheese", cheese);
executeExpression(compileExpression(parseMacros("retract(cheese)", macros)), map);
assertSame(cheese, helper.retracted.get(0));
}
@SuppressWarnings({"UnnecessaryBoxing"})
public void testToList() {
String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1', c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )";
List list = (List) test(text);
assertSame("dog", list.get(0));
assertEquals("hello", list.get(1));
assertEquals(new Integer(42), list.get(2));
Map map = (Map) list.get(3);
assertEquals("value1", map.get("key1"));
List nestedList = (List) map.get("cat");
assertEquals(14, nestedList.get(0));
assertEquals("car", nestedList.get(1));
assertEquals(42, nestedList.get(2));
nestedList = (List) list.get(4);
assertEquals(42, nestedList.get(0));
map = (Map) nestedList.get(1);
assertEquals("value1", map.get("cat"));
}
@SuppressWarnings({"UnnecessaryBoxing"})
public void testToListStrictMode() {
String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1', c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )";
ParserContext ctx = new ParserContext();
ctx.addInput("misc", MiscTestClass.class);
ctx.addInput("foo", Foo.class);
ctx.addInput("c", String.class);
ctx.setStrictTypeEnforcement(true);
ExpressionCompiler compiler = new ExpressionCompiler(text);
List list = (List) executeExpression(compiler.compile(ctx), createTestMap());
assertSame("dog", list.get(0));
assertEquals("hello", list.get(1));
assertEquals(new Integer(42), list.get(2));
Map map = (Map) list.get(3);
assertEquals("value1", map.get("key1"));
List nestedList = (List) map.get("cat");
assertEquals(14, nestedList.get(0));
assertEquals("car", nestedList.get(1));
assertEquals(42, nestedList.get(2));
nestedList = (List) list.get(4);
assertEquals(42, nestedList.get(0));
map = (Map) nestedList.get(1);
assertEquals("value1", map.get("cat"));
}
public void testParsingStability1() {
assertEquals(true, test("( order.number == 1 || order.number == ( 1+1) || order.number == $id )"));
}
public void testParsingStability2() {
ExpressionCompiler compiler = new ExpressionCompiler("( dim.height == 1 || dim.height == ( 1+1) || dim.height == x )");
Map<String, Object> imports = new HashMap<String, Object>();
imports.put("java.awt.Dimension", Dimension.class);
final ParserContext parserContext = new ParserContext(imports,
null,
"sourceFile");
parserContext.setStrictTypeEnforcement(false);
compiler.compile(parserContext);
}
public void testParsingStability3() {
assertEquals(false, test("!( [\"X\", \"Y\"] contains \"Y\" )"));
}
public void testParsingStability4() {
assertEquals(true, test("vv=\"Edson\"; !(vv ~= \"Mark\")"));
}
public void testConcatWithLineBreaks() {
ExpressionCompiler parser = new ExpressionCompiler("\"foo\"+\n\"bar\"");
ParserContext ctx = new ParserContext();
ctx.setDebugSymbols(true);
ctx.setSourceFile("source.mv");
assertEquals("foobar", executeExpression(parser.compile(ctx)));
}
public void testMapWithStrictTyping() {
ExpressionCompiler compiler = new ExpressionCompiler("map['KEY1'] == $msg");
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.setStrongTyping(true);
ctx.addInput("$msg", String.class);
ctx.addInput("map", Map.class);
Serializable expr = compiler.compile(ctx);
Map map = new HashMap();
map.put("KEY1", "MSGONE");
Map vars = new HashMap();
vars.put("$msg", "MSGONE");
vars.put("map", map);
Boolean bool = (Boolean) executeExpression(expr, map, vars);
assertEquals(Boolean.TRUE, bool);
}
public void testMapAsContextWithStrictTyping() {
ExpressionCompiler compiler = new ExpressionCompiler("this['KEY1'] == $msg");
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.setStrongTyping(true);
ctx.addInput("$msg", String.class);
ctx.addInput("this", Map.class);
Serializable expr = compiler.compile(ctx);
Map map = new HashMap();
map.put("KEY1", "MSGONE");
Map vars = new HashMap();
vars.put("$msg", "MSGONE");
Boolean bool = (Boolean) executeExpression(expr, map, vars);
assertEquals(Boolean.TRUE, bool);
}
/**
* Community provided test cases
*/
@SuppressWarnings({"unchecked"})
public void testCalculateAge() {
Calendar c1 = Calendar.getInstance();
c1.set(1999, 0, 10); // 1999 jan 20
Map objectMap = new HashMap(1);
Map propertyMap = new HashMap(1);
propertyMap.put("GEBDAT", c1.getTime());
objectMap.put("EV_VI_ANT1", propertyMap);
assertEquals("N", testCompiledSimple("new org.mvel2.tests.core.res.PDFFieldUtil().calculateAge(EV_VI_ANT1.GEBDAT) >= 25 ? 'Y' : 'N'"
, null, objectMap));
}
/**
* Provided by: Alex Roytman
*/
public void testMethodResolutionWithNullParameter() {
Context ctx = new Context();
ctx.setBean(new Bean());
Map<String, Object> vars = new HashMap<String, Object>();
System.out.println("bean.today: " + eval("bean.today", ctx, vars));
System.out.println("formatDate(bean.today): " + eval("formatDate(bean.today)", ctx, vars));
//calling method with string param with null parameter works
System.out.println("formatString(bean.nullString): " + eval("formatString(bean.nullString)", ctx, vars));
System.out.println("bean.myDate = bean.nullDate: " + eval("bean.myDate = bean.nullDate; return bean.nullDate;", ctx, vars));
//calling method with Date param with null parameter fails
System.out.println("formatDate(bean.myDate): " + eval("formatDate(bean.myDate)", ctx, vars));
//same here
System.out.println(eval("formatDate(bean.nullDate)", ctx, vars));
}
/**
* Provided by: Phillipe Ombredanne
*/
public void testCompileParserContextShouldNotLoopIndefinitelyOnValidJavaExpression() {
String expr = " System.out.println( message );\n" +
"m.setMessage( \"Goodbye cruel world\" );\n" +
"System.out.println(m.getStatus());\n" +
"m.setStatus( Message.GOODBYE );\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Message", Message.class);
context.addInput("System", void.class);
context.addInput("message", Object.class);
context.addInput("m", Object.class);
compiler.compile(context);
}
public void testStaticNested() {
assertEquals(1, eval("org.mvel2.tests.core.AbstractTest$Message.GOODBYE", new HashMap()));
}
public void testStaticNestedWithImport() {
String expr = "Message.GOODBYE;\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Message", Message.class);
assertEquals(1, executeExpression(compiler.compile(context)));
}
public void testStaticNestedWithMethodCall() {
String expr = "item = new Item( \"Some Item\"); $msg.addItem( item ); return $msg";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Message", Message.class);
context.addImport("Item", Item.class);
// Serializable compiledExpression = compiler.compile(context);
Map vars = new HashMap();
vars.put("$msg", new Message());
Message msg = (Message) executeExpression(compiler.compile(context), vars);
Item item = (Item) msg.getItems().get(0);
assertEquals("Some Item", item.getName());
}
public void testsequentialAccessorsThenMethodCall() {
String expr = "System.out.println(drools.workingMemory); drools.workingMemory.ruleBase.removeRule(\"org.drools.examples\", \"some rule\"); ";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(true);
context.addInput("drools", KnowledgeHelper.class);
RuleBase ruleBase = new RuleBaseImpl();
WorkingMemory wm = new WorkingMemoryImpl(ruleBase);
KnowledgeHelper drools = new DefaultKnowledgeHelper(wm);
Map vars = new HashMap();
vars.put("drools", drools);
executeExpression(compiler.compile(context), vars);
}
/**
* Provided by: Aadi Deshpande
*/
public void testPropertyVerfierShoudldNotLoopIndefinately() {
String expr = "\t\tmodel.latestHeadlines = $list;\n" +
"model.latestHeadlines.add( 0, (model.latestHeadlines[2]) );";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
compiler.setVerifying(true);
ParserContext pCtx = new ParserContext();
pCtx.addInput("$list", List.class);
pCtx.addInput("model", Model.class);
compiler.compile(pCtx);
}
public void testCompileWithNewInsideMethodCall() {
String expr = " p.name = \"goober\";\n" +
" System.out.println(p.name);\n" +
" drools.insert(new Address(\"Latona\"));\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Person", Person.class);
context.addImport("Address", Address.class);
context.addInput("p", Person.class);
context.addInput("drools", Drools.class);
compiler.compile(context);
}
/**
* Submitted by: cleverpig
*/
public void testBug4() {
ClassA A = new ClassA();
ClassB B = new ClassB();
System.out.println(MVEL.getProperty("date", A));
System.out.println(MVEL.getProperty("date", B));
}
/**
* Submitted by: Michael Neale
*/
public void testInlineCollectionParser1() {
assertEquals("q", ((Map) test("['Person.age' : [1, 2, 3, 4],'Person.rating' : 'q']")).get("Person.rating"));
assertEquals("q", ((Map) test("['Person.age' : [1, 2, 3, 4], 'Person.rating' : 'q']")).get("Person.rating"));
}
public void testIndexer() {
assertEquals("foobar", testCompiledSimple("import java.util.LinkedHashMap; LinkedHashMap map = new LinkedHashMap();" +
" map.put('a', 'foo'); map.put('b', 'bar'); s = ''; foreach (key : map.keySet()) { System.out.println(map[key]); s += map[key]; }; return s;", createTestMap()));
}
public void testLateResolveOfClass() {
ExpressionCompiler compiler = new ExpressionCompiler("System.out.println(new Foo());");
ParserContext ctx = new ParserContext();
ctx.addImport(Foo.class);
compiler.removeParserContext();
System.out.println(executeExpression(compiler.compile(ctx)));
}
public void testClassAliasing() {
assertEquals("foobar", test("Foo = String; new Foo('foobar')"));
}
public void testRandomExpression1() {
assertEquals("HelloWorld", test("if ((x15 = foo.bar) == foo.bar && x15 == foo.bar) { return 'HelloWorld'; } else { return 'GoodbyeWorld' } "));
}
public void testRandomExpression2() {
assertEquals(11, test("counterX = 0; foreach (item:{1,2,3,4,5,6,7,8,9,10}) { counterX++; }; return counterX + 1;"));
}
public void testRandomExpression3() {
assertEquals(0, test("counterX = 10; foreach (item:{1,1,1,1,1,1,1,1,1,1}) { counterX -= item; } return counterX;"));
}
public void testRandomExpression4() {
assertEquals(true, test("result = org.mvel2.MVEL.eval('10 * 3'); result == (10 * 3);"));
}
public void testRandomExpression5() {
assertEquals(true, test("FooClassRef = foo.getClass(); fooInst = new FooClassRef(); name = org.mvel2.MVEL.eval('name', fooInst); return name == 'dog'"));
}
public void testRandomExpression6() {
assertEquals(500, test("exprString = '250' + ' ' + '*' + ' ' + '2'; compiledExpr = org.mvel2.MVEL.compileExpression(exprString);" +
" return org.mvel2.MVEL.executeExpression(compiledExpr);"));
}
public void testRandomExpression7() {
assertEquals("FOOBAR", test("'foobar'.toUpperCase();"));
}
public void testRandomExpression8() {
assertEquals(true, test("'someString'.intern(); 'someString'.hashCode() == 'someString'.hashCode();"));
}
public void testRandomExpression9() {
assertEquals(false, test("_abc = 'someString'.hashCode(); _xyz = _abc + 1; _abc == _xyz"));
}
public void testRandomExpression10() {
assertEquals(false, test("(_abc = (_xyz = 'someString'.hashCode()) + 1); _abc == _xyz"));
}
/**
* Submitted by: Guerry Semones
*/
private Map<Object, Object> outerMap;
private Map<Object, Object> innerMap;
public void testAddIntToMapWithMapSyntax() throws Throwable {
outerMap = new HashMap<Object, Object>();
innerMap = new HashMap<Object, Object>();
outerMap.put("innerMap", innerMap);
// fails because mvel2 checks for 'tak' in the outerMap,
// rather than inside innerMap in outerMap
PropertyAccessor.set(outerMap, "innerMap['foo']", 42);
// instead of here
assertEquals(42, innerMap.get("foo"));
}
public void testUpdateIntInMapWithMapSyntax() throws Throwable {
outerMap = new HashMap<Object, Object>();
innerMap = new HashMap<Object, Object>();
outerMap.put("innerMap", innerMap);
// fails because mvel2 checks for 'tak' in the outerMap,
// rather than inside innerMap in outerMap
innerMap.put("foo", 21);
PropertyAccessor.set(outerMap, "innerMap['foo']", 42);
// instead of updating it here
assertEquals(42, innerMap.get("foo"));
}
private HashMap<String, Object> context = new HashMap<String, Object>();
public void before() {
HashMap<String, Object> map = new HashMap<String, Object>();
MyBean bean = new MyBean();
bean.setVar(4);
map.put("bean", bean);
context.put("map", map);
}
public void testDeepProperty() {
before();
Object obj = executeExpression(compileExpression("map.bean.var"), context);
assertEquals(4, obj);
}
public void testDeepProperty2() {
before();
Object obj = executeExpression(compileExpression("map.bean.getVar()"), context);
assertEquals(4, obj);
}
public class MyBean {
int var;
public int getVar() {
return var;
}
public void setVar(int var) {
this.var = var;
}
}
public static class TargetClass {
private short _targetValue = 5;
public short getTargetValue() {
return _targetValue;
}
}
public void testNestedMethodCall() {
List elements = new ArrayList();
elements.add(new TargetClass());
Map variableMap = new HashMap();
variableMap.put("elements", elements);
eval(
"results = new java.util.ArrayList(); foreach (element : elements) { if( {5} contains element.targetValue.intValue()) { results.add(element); } }; results",
variableMap);
}
public void testBooleanEvaluation() {
assertEquals(true, test("true||false||false"));
}
public void testBooleanEvaluation2() {
assertEquals(true, test("equalityCheck(1,1)||fun||ackbar"));
}
/**
* Submitted by: Dimitar Dimitrov
*/
public void testFailing() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("os", "windows");
assertTrue((Boolean) eval("os ~= 'windows|unix'", map));
}
public void testSuccess() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("os", "windows");
assertTrue((Boolean) eval("'windows' ~= 'windows|unix'", map));
assertFalse((Boolean) eval("time ~= 'windows|unix'", new java.util.Date()));
}
public void testStaticWithExplicitParam() {
PojoStatic pojo = new PojoStatic("10");
eval("org.mvel2.tests.core.res.AStatic.Process('10')", pojo, new HashMap());
}
public void testSimpleExpression() {
PojoStatic pojo = new PojoStatic("10");
eval("value!= null", pojo, new HashMap());
}
public void testStaticWithExpressionParam() {
PojoStatic pojo = new PojoStatic("10");
assertEquals("java.lang.String", eval("org.mvel2.tests.core.res.AStatic.Process(value.getClass().getName().toString())", pojo));
}
public void testStringIndex() {
assertEquals(true, test("a = 'foobar'; a[4] == 'a'"));
}
public void testArrayConstructionSupport1() {
assertTrue(test("new String[5]") instanceof String[]);
}
public void testArrayConstructionSupport2() {
assertTrue((Boolean) test("xStr = new String[5]; xStr.size() == 5"));
}
public void testArrayConstructionSupport3() {
assertEquals("foo", test("xStr = new String[5][5]; xStr[4][0] = 'foo'; xStr[4][0]"));
}
public void testArrayConstructionSupport4() {
assertEquals(10, test("xStr = new String[5][10]; xStr[4][0] = 'foo'; xStr[4].length"));
}
public void testAssertKeyword() {
ExpressionCompiler compiler = new ExpressionCompiler("assert 1 == 2;");
Serializable s = compiler.compile();
try {
executeExpression(s);
}
catch (AssertionError e) {
return;
}
assertTrue(false);
}
public void testNullSafe() {
Foo foo = new Foo();
Map map = new HashMap();
map.put("foo", foo);
String expression = "foo.?bar.name == null";
Serializable compiled = compileExpression(expression);
OptimizerFactory.setDefaultOptimizer("reflective");
assertEquals(false, executeExpression(compiled, map));
foo.setBar(null);
assertEquals(true, executeExpression(compiled, map)); // execute a second time (to search for optimizer problems)
OptimizerFactory.setDefaultOptimizer("ASM");
compiled = compileExpression(expression);
foo.setBar(new Bar());
assertEquals(false, executeExpression(compiled, map));
foo.setBar(null);
assertEquals(true, executeExpression(compiled, map)); // execute a second time (to search for optimizer problems)
assertEquals(true, eval(expression, map));
}
public void testMethodInvocationWithCollectionElement() {
context = new HashMap();
context.put("pojo", new POJO());
context.put("number", "1192800637980");
Object result = MVEL.eval("pojo.function(pojo.dates[0].time)", context);
assertEquals(String.valueOf(((POJO) context.get("pojo")).getDates().iterator().next().getTime()), result);
}
public void testNestedWithInList() {
Recipient recipient1 = new Recipient();
recipient1.setName("userName1");
recipient1.setEmail("user1@domain.com");
Recipient recipient2 = new Recipient();
recipient2.setName("userName2");
recipient2.setEmail("user2@domain.com");
List list = new ArrayList();
list.add(recipient1);
list.add(recipient2);
String text =
"array = [" +
"(with ( new Recipient() ) {name = 'userName1', email = 'user1@domain.com' })," +
"(with ( new Recipient() ) {name = 'userName2', email = 'user2@domain.com' })];\n";
ParserContext context = new ParserContext();
context.addImport(Recipient.class);
ExpressionCompiler compiler = new ExpressionCompiler(text);
Serializable execution = compiler.compile(context);
List result = (List) executeExpression(execution, new HashMap());
assertEquals(list, result);
}
public void testNestedWithInComplexGraph3() {
Recipients recipients = new Recipients();
Recipient recipient1 = new Recipient();
recipient1.setName("user1");
recipient1.setEmail("user1@domain.com");
recipients.addRecipient(recipient1);
Recipient recipient2 = new Recipient();
recipient2.setName("user2");
recipient2.setEmail("user2@domain.com");
recipients.addRecipient(recipient2);
EmailMessage msg = new EmailMessage();
msg.setRecipients(recipients);
msg.setFrom("from@domain.com");
String text = "";
text += "new EmailMessage().{ ";
text += " recipients = new Recipients().{ ";
text += " recipients = [ new Recipient().{ name = 'user1', email = 'user1@domain.com' }, ";
text += " new Recipient().{ name = 'user2', email = 'user2@domain.com' } ] ";
text += " }, ";
text += " from = 'from@domain.com' }";
ParserContext context;
context = new ParserContext();
context.addImport(Recipient.class);
context.addImport(Recipients.class);
context.addImport(EmailMessage.class);
OptimizerFactory.setDefaultOptimizer("ASM");
ExpressionCompiler compiler = new ExpressionCompiler(text);
Serializable execution = compiler.compile(context);
assertEquals(msg, executeExpression(execution));
assertEquals(msg, executeExpression(execution));
assertEquals(msg, executeExpression(execution));
OptimizerFactory.setDefaultOptimizer("reflective");
context = new ParserContext(context.getParserConfiguration());
compiler = new ExpressionCompiler(text);
execution = compiler.compile(context);
assertEquals(msg, executeExpression(execution));
assertEquals(msg, executeExpression(execution));
assertEquals(msg, executeExpression(execution));
}
public static class Recipient {
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Recipient other = (Recipient) obj;
if (email == null) {
if (other.email != null) return false;
}
else if (!email.equals(other.email)) return false;
if (name == null) {
if (other.name != null) return false;
}
else if (!name.equals(other.name)) return false;
return true;
}
}
public static class Recipients {
private List<Recipient> list = Collections.EMPTY_LIST;
public void setRecipients(List<Recipient> recipients) {
this.list = recipients;
}
public boolean addRecipient(Recipient recipient) {
if (list == Collections.EMPTY_LIST) {
this.list = new ArrayList<Recipient>();
}
if (!this.list.contains(recipient)) {
this.list.add(recipient);
return true;
}
return false;
}
public boolean removeRecipient(Recipient recipient) {
return this.list.remove(recipient);
}
public List<Recipient> getRecipients() {
return this.list;
}
public Recipient[] toArray() {
return list.toArray(new Recipient[list.size()]);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((list == null) ? 0 : list.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Recipients other = (Recipients) obj;
if (list == null) {
if (other.list != null) return false;
}
return list.equals(other.list);
}
}
public static class EmailMessage {
private Recipients recipients;
private String from;
public EmailMessage() {
}
public Recipients getRecipients() {
return recipients;
}
public void setRecipients(Recipients recipients) {
this.recipients = recipients;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((from == null) ? 0 : from.hashCode());
result = prime * result + ((recipients == null) ? 0 : recipients.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final EmailMessage other = (EmailMessage) obj;
if (from == null) {
if (other.from != null) return false;
}
else if (!from.equals(other.from)) return false;
if (recipients == null) {
if (other.recipients != null) return false;
}
else if (!recipients.equals(other.recipients)) return false;
return true;
}
}
public class POJO {
private Set<Date> dates = new HashSet<Date>();
public POJO() {
dates.add(new Date());
}
public Set<Date> getDates() {
return dates;
}
public void setDates(Set<Date> dates) {
this.dates = dates;
}
public String function(long num) {
return String.valueOf(num);
}
}
public void testSubEvaluation() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("EV_BER_BER_NR", "12345");
map.put("EV_BER_BER_PRIV", Boolean.FALSE);
assertEquals("12345", testCompiledSimple("EV_BER_BER_NR + ((EV_BER_BER_PRIV != empty && EV_BER_BER_PRIV == true) ? \"/PRIVAT\" : '')", null, map));
map.put("EV_BER_BER_PRIV", Boolean.TRUE);
assertEquals("12345/PRIVAT", testCompiledSimple("EV_BER_BER_NR + ((EV_BER_BER_PRIV != empty && EV_BER_BER_PRIV == true) ? \"/PRIVAT\" : '')", null, map));
}
public void testNestedMethod1() {
Vector vectorA = new Vector();
Vector vectorB = new Vector();
vectorA.add("Foo");
Map map = new HashMap();
map.put("vecA", vectorA);
map.put("vecB", vectorB);
testCompiledSimple("vecB.add(vecA.remove(0)); vecA.add('Foo');", null, map);
assertEquals("Foo", vectorB.get(0));
}
public void testNegativeArraySizeBug() throws Exception {
String expressionString1 = "results = new java.util.ArrayList(); foreach (element : elements) { if( ( {30, 214, 158, 31, 95, 223, 213, 86, 159, 34, 32, 96, 224, 160, 85, 201, 29, 157, 100, 146, 82, 203, 194, 145, 140, 81, 27, 166, 212, 38, 28, 94, 168, 23, 87, 150, 35, 149, 193, 33, 132, 206, 93, 196, 24, 88, 195, 36, 26, 154, 167, 108, 204, 74, 46, 25, 153, 202, 79, 207, 143, 43, 16, 80, 198, 208, 144, 41, 97, 142, 83, 18, 162, 103, 155, 98, 44, 17, 205, 77, 156, 141, 165, 102, 84, 37, 101, 222, 40, 104, 99, 177, 182, 22, 180, 21, 137, 221, 179, 78, 42, 178, 19, 183, 139, 218, 219, 39, 220, 20, 184, 217, 138, 62, 190, 171, 123, 113, 59, 118, 225, 124, 169, 60, 117, 1} contains element.attribute ) ) { results.add(element); } }; results";
String expressionString2 = "results = new java.util.ArrayList(); foreach (element : elements) { if( ( {30, 214, 158, 31, 95, 223, 213, 86, 159, 34, 32, 96, 224, 160, 85, 201, 29, 157, 100, 146, 82, 203, 194, 145, 140, 81, 27, 166, 212, 38, 28, 94, 168, 23, 87, 150, 35, 149, 193, 33, 132, 206, 93, 196, 24, 88, 195, 36, 26, 154, 167, 108, 204, 74, 46, 25, 153, 202, 79, 207, 143, 43, 16, 80, 198, 208, 144, 41, 97, 142, 83, 18, 162, 103, 155, 98, 44, 17, 205, 77, 156, 141, 165, 102, 84, 37, 101, 222, 40, 104, 99, 177, 182, 22, 180, 21, 137, 221, 179, 78, 42, 178, 19, 183, 139, 218, 219, 39, 220, 20, 184, 217, 138, 62, 190, 171, 123, 113, 59, 118, 225, 124, 169, 60, 117, 1, 61, 189, 122, 68, 58, 119, 63, 226, 3, 172} contains element.attribute ) ) { results.add(element); } }; results";
List<Target> targets = new ArrayList<Target>();
targets.add(new Target(1));
targets.add(new Target(999));
Map vars = new HashMap();
vars.put("elements", targets);
assertEquals(1, ((List) testCompiledSimple(expressionString1, null, vars)).size());
assertEquals(1, ((List) testCompiledSimple(expressionString2, null, vars)).size());
}
public static final class Target {
private int _attribute;
public Target(int attribute_) {
_attribute = attribute_;
}
public int getAttribute() {
return _attribute;
}
}
public void testDynamicImports2() {
assertEquals(BufferedReader.class, test("import java.io.*; BufferedReader"));
}
public void testStringWithTernaryIf() {
test("System.out.print(\"Hello : \" + (foo != null ? \"FOO!\" : \"NO FOO\") + \". Bye.\");");
}
public void testCompactIfElse() {
assertEquals("foo", test("if (false) 'bar'; else 'foo';"));
}
public void testAndOpLiteral() {
assertEquals(true, test("true && true"));
}
public void testAnonymousFunctionDecl() {
assertEquals(3, test("anonFunc = function (a,b) { return a + b; }; anonFunc(1,2)"));
}
public void testFunctionSemantics() {
assertEquals(true, test("function fooFunction(a) { return a; }; x__0 = ''; 'boob' == fooFunction(x__0 = 'boob') && x__0 == 'boob';"));
}
public void testUseOfVarKeyword() {
assertEquals("FOO_BAR", test("var barfoo = 'FOO_BAR'; return barfoo;"));
}
public void testAssignment5() {
assertEquals(15, test("x = (10) + (5); x"));
}
public void testSetExpressions1() {
Map<String, Object> myMap = new HashMap<String, Object>();
final Serializable fooExpr = compileSetExpression("foo");
executeSetExpression(fooExpr, myMap, "blah");
assertEquals("blah", myMap.get("foo"));
executeSetExpression(fooExpr, myMap, "baz");
assertEquals("baz", myMap.get("foo"));
}
public void testEgressType() {
ExpressionCompiler compiler = new ExpressionCompiler("( $cheese )");
ParserContext context = new ParserContext();
context.addInput("$cheese", Cheese.class);
assertEquals(Cheese.class, compiler.compile(context).getKnownEgressType());
}
public void testDuplicateVariableDeclaration() {
ExpressionCompiler compiler = new ExpressionCompiler("String x = \"abc\"; Integer x = new Integer( 10 );");
ParserContext context = new ParserContext();
try {
compiler.compile(context);
fail("Compilation must fail with duplicate variable declaration exception.");
}
catch (CompileException ce) {
// success
}
}
public void testFullyQualifiedTypeAndCast() {
assertEquals(1, test("java.lang.Integer number = (java.lang.Integer) '1';"));
}
public void testThreadSafetyInterpreter1() {
//First evaluation
System.out.println("First evaluation: " + MVEL.eval("true"));
new Thread(new Runnable() {
public void run() {
// Second evaluation - this succeeds only if the first evaluation is not commented out
System.out.println("Second evaluation: " + MVEL.eval("true"));
}
}).start();
}
public void testArrayList() throws SecurityException, NoSuchMethodException {
Collection<String> collection = new ArrayList<String>();
collection.add("I CAN HAS CHEEZBURGER");
assertEquals(collection.size(), MVEL.eval("size()", collection));
}
public void testUnmodifiableCollection() throws SecurityException, NoSuchMethodException {
Collection<String> collection = new ArrayList<String>();
collection.add("I CAN HAS CHEEZBURGER");
collection = unmodifiableCollection(collection);
assertEquals(collection.size(), MVEL.eval("size()", collection));
}
public void testSingleton() throws SecurityException, NoSuchMethodException {
Collection<String> collection = Collections.singleton("I CAN HAS CHEEZBURGER");
assertEquals(collection.size(), MVEL.eval("size()", collection));
}
public void testRegExMatch() {
assertEquals(true, MVEL.eval("$test = 'foo'; $ex = 'f.*'; $test ~= $ex", new HashMap()));
}
public static class TestClass2 {
public void addEqualAuthorizationConstraint(Foo leg, Bar ctrlClass, Integer authorization) {
}
}
public void testJIRA93() {
Map testMap = createTestMap();
testMap.put("testClass2", new TestClass2());
Serializable s = compileExpression("testClass2.addEqualAuthorizationConstraint(foo, foo.bar, 5)");
for (int i = 0; i < 5; i++) {
executeExpression(s, testMap);
}
}
public void testJIRA96() {
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.addInput("fooString", String[].class);
ExpressionCompiler compiler = new ExpressionCompiler("fooString[0].toUpperCase()");
compiler.compile(ctx);
}
public void testStrongTyping() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
try {
new ExpressionCompiler("blah").compile(ctx);
}
catch (Exception e) {
// should fail
return;
}
assertTrue(false);
}
public void testStrongTyping2() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("blah", String.class);
try {
new ExpressionCompiler("1-blah").compile(ctx);
}
catch (Exception e) {
e.printStackTrace();
return;
}
assertTrue(false);
}
public void testStringToArrayCast() {
Object o = test("(char[]) 'abcd'");
assertTrue(o instanceof char[]);
}
public void testStringToArrayCast2() {
assertTrue((Boolean) test("_xyxy = (char[]) 'abcd'; _xyxy[0] == 'a'"));
}
public void testStaticallyTypedArrayVar() {
assertTrue((Boolean) test("char[] _c___ = new char[10]; _c___ instanceof char[]"));
}
public void testParserErrorHandling() {
final ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler("a[");
try {
compiler.compile(ctx);
}
catch (Exception e) {
return;
}
assertTrue(false);
}
public void testJIRA99_Interpreted() {
Map map = new HashMap();
map.put("x", 20);
map.put("y", 10);
map.put("z", 5);
assertEquals(20 - 10 - 5, MVEL.eval("x - y - z", map));
}
public void testJIRA99_Compiled() {
Map map = new HashMap();
map.put("x", 20);
map.put("y", 10);
map.put("z", 5);
assertEquals(20 - 10 - 5, testCompiledSimple("x - y - z", map));
}
public void testJIRA100() {
assertEquals(new BigDecimal(20), test("java.math.BigDecimal axx = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal bxx = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal cxx = axx + bxx; return cxx; "));
}
public void testAssignToBean() {
Person person = new Person();
MVEL.eval("this.name = 'foo'", person);
assertEquals("foo", person.getName());
executeExpression(compileExpression("this.name = 'bar'"), person);
assertEquals("bar", person.getName());
}
public void testParameterizedTypeInStrictMode() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("foo", HashMap.class, new Class[]{String.class, String.class});
ExpressionCompiler compiler = new ExpressionCompiler("foo.get('bar').toUpperCase()");
compiler.compile(ctx);
}
public void testParameterizedTypeInStrictMode2() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("ctx", Object.class);
ExpressionCompiler compiler = new ExpressionCompiler("org.mvel2.DataConversion.convert(ctx, String).toUpperCase()");
assertEquals(String.class, compiler.compile(ctx).getKnownEgressType());
}
public void testParameterizedTypeInStrictMode3() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("base", Base.class);
ExpressionCompiler compiler = new ExpressionCompiler("base.list");
assertTrue(compiler.compile(ctx).getParserContext().getLastTypeParameters()[0].equals(String.class));
}
public void testParameterizedTypeInStrictMode4() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("base", Base.class);
ExpressionCompiler compiler = new ExpressionCompiler("base.list.get(1).toUpperCase()");
CompiledExpression ce = compiler.compile(ctx);
assertEquals(String.class, ce.getKnownEgressType());
}
public void testMapAssignmentNestedExpression() {
Map map = new HashMap();
map.put("map", new HashMap());
String ex = "map[java.lang.Integer.MAX_VALUE] = 'bar'; map[java.lang.Integer.MAX_VALUE];";
assertEquals("bar", executeExpression(compileExpression(ex), map));
assertEquals("bar", MVEL.eval(ex, map));
}
public void testMapAssignmentNestedExpression2() {
Map map = new HashMap();
map.put("x", "bar");
map.put("map", new HashMap());
String ex = "map[x] = 'foo'; map['bar'];";
assertEquals("foo", executeExpression(compileExpression(ex), map));
assertEquals("foo", MVEL.eval(ex, map));
}
/**
* MVEL-103
*/
public static class MvelContext {
public boolean singleCalled;
public boolean arrayCalled;
public String[] regkeys;
public void methodForTest(String string) {
System.out.println("sigle param method called!");
singleCalled = true;
}
public void methodForTest(String[] strings) {
System.out.println("array param method called!");
arrayCalled = true;
}
public void setRegkeys(String[] regkeys) {
this.regkeys = regkeys;
}
public void setRegkeys(String regkey) {
this.regkeys = regkey.split(",");
}
}
public void testMethodResolutionOrder() {
MvelContext mvelContext = new MvelContext();
MVEL.eval("methodForTest({'1','2'})", mvelContext);
MVEL.eval("methodForTest('1')", mvelContext);
assertTrue(mvelContext.arrayCalled && mvelContext.singleCalled);
}
public void testOKQuoteComment() throws Exception {
// ' in comments outside of blocks seem OK
compileExpression("// ' this is OK!");
compileExpression("// ' this is OK!\n");
compileExpression("// ' this is OK!\nif(1==1) {};");
}
public void testOKDblQuoteComment() throws Exception {
// " in comments outside of blocks seem OK
compileExpression("// \" this is OK!");
compileExpression("// \" this is OK!\n");
compileExpression("// \" this is OK!\nif(1==1) {};");
}
public void testIfComment() throws Exception {
// No quote? OK!
compileExpression("if(1 == 1) {\n" +
" // Quote & Double-quote seem to break this expression\n" +
"}");
}
public void testIfQuoteCommentBug() throws Exception {
// Comments in an if seem to fail if they contain a '
compileExpression("if(1 == 1) {\n" +
" // ' seems to break this expression\n" +
"}");
}
public void testIfDblQuoteCommentBug() throws Exception {
// Comments in a foreach seem to fail if they contain a '
compileExpression("if(1 == 1) {\n" +
" // ' seems to break this expression\n" +
"}");
}
public void testForEachQuoteCommentBug() throws Exception {
// Comments in a foreach seem to fail if they contain a '
compileExpression("foreach ( item : 10 ) {\n" +
" // The ' character causes issues\n" +
"}");
}
public void testForEachDblQuoteCommentBug() throws Exception {
// Comments in a foreach seem to fail if they contain a '
compileExpression("foreach ( item : 10 ) {\n" +
" // The \" character causes issues\n" +
"}");
}
public void testForEachCommentOK() throws Exception {
// No quote? OK!
compileExpression("foreach ( item : 10 ) {\n" +
" // The quote & double quote characters cause issues\n" +
"}");
}
public void testElseIfCommentBugPreCompiled() throws Exception {
// Comments can't appear before else if() - compilation works, but evaluation fails
executeExpression(compileExpression("// This is never true\n" +
"if (1==0) {\n" +
" // Never reached\n" +
"}\n" +
"// This is always true...\n" +
"else if (1==1) {" +
" System.out.println('Got here!');" +
"}\n"));
}
public void testElseIfCommentBugEvaluated() throws Exception {
// Comments can't appear before else if()
MVEL.eval("// This is never true\n" +
"if (1==0) {\n" +
" // Never reached\n" +
"}\n" +
"// This is always true...\n" +
"else if (1==1) {" +
" System.out.println('Got here!');" +
"}\n");
}
public void testRegExpOK() throws Exception {
// This works OK intepreted
assertEquals(Boolean.TRUE, MVEL.eval("'Hello'.toUpperCase() ~= '[A-Z]{0,5}'"));
assertEquals(Boolean.TRUE, MVEL.eval("1 == 0 || ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')"));
// This works OK if toUpperCase() is avoided in pre-compiled
assertEquals(Boolean.TRUE, executeExpression(compileExpression("'Hello' ~= '[a-zA-Z]{0,5}'")));
}
public void testRegExpPreCompiledBug() throws Exception {
// If toUpperCase() is used in the expression then this fails; returns null not
// a boolean.
Object ser = compileExpression("'Hello'.toUpperCase() ~= '[a-zA-Z]{0,5}'");
assertEquals(Boolean.TRUE, executeExpression(ser));
}
public void testRegExpOrBug() throws Exception {
// This fails during execution due to returning null, I think...
assertEquals(Boolean.TRUE, executeExpression(compileExpression("1 == 0 || ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')")));
}
public void testRegExpAndBug() throws Exception {
// This also fails due to returning null, I think...
// Object ser = MVEL.compileExpression("1 == 1 && ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')");
assertEquals(Boolean.TRUE, executeExpression(compileExpression("1 == 1 && ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')")));
}
public void testLiteralUnionWithComparison() {
assertEquals(Boolean.TRUE, executeExpression(compileExpression("1 == 1 && ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')")));
}
public static final List<String> STRINGS = Arrays.asList("hi", "there");
public static class A {
public List<String> getStrings() {
return STRINGS;
}
}
public final void testDetermineEgressParametricType() {
final ParserContext parserContext = new ParserContext();
parserContext.setStrongTyping(true);
parserContext.addInput("strings", List.class, new Class[]{String.class});
final CompiledExpression expr = new ExpressionCompiler("strings").compile(parserContext);
assertTrue(STRINGS.equals(executeExpression(expr, new A())));
final Type[] typeParameters = expr.getParserContext().getLastTypeParameters();
assertTrue(typeParameters != null);
assertTrue(String.class.equals(typeParameters[0]));
}
public final void testDetermineEgressParametricType2() {
final ParserContext parserContext = new ParserContext();
parserContext.setStrongTyping(true);
parserContext.addInput("strings", List.class, new Class[]{String.class});
final CompiledExpression expr = new ExpressionCompiler("strings", parserContext)
.compile();
assertTrue(STRINGS.equals(executeExpression(expr, new A())));
final Type[] typeParameters = expr.getParserContext().getLastTypeParameters();
assertTrue(null != typeParameters);
assertTrue(String.class.equals(typeParameters[0]));
}
public void testCustomPropertyHandler() {
MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true;
PropertyHandlerFactory.registerPropertyHandler(SampleBean.class, new SampleBeanAccessor());
assertEquals("dog", test("foo.sampleBean.bar.name"));
PropertyHandlerFactory.unregisterPropertyHandler(SampleBean.class);
MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = false;
}
public void testSetAccessorOverloadedEqualsStrictMode() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("foo", Foo.class);
try {
CompiledExpression expr = new ExpressionCompiler("foo.bar = 0").compile(ctx);
}
catch (CompileException e) {
// should fail.
e.printStackTrace();
return;
}
assertTrue(false);
}
public void testSetAccessorOverloadedEqualsStrictMode2() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("foo", Foo.class);
try {
CompiledExpression expr = new ExpressionCompiler("foo.aValue = 'bar'").compile(ctx);
}
catch (CompileException e) {
assertTrue(false);
}
}
public void testAnalysisCompile() {
ParserContext pCtx = new ParserContext();
ExpressionCompiler e = new ExpressionCompiler("foo.aValue = 'bar'");
e.setVerifyOnly(true);
e.compile(pCtx);
assertTrue(pCtx.getInputs().keySet().contains("foo"));
assertEquals(1, pCtx.getInputs().size());
assertEquals(0, pCtx.getVariables().size());
}
public void testDataConverterStrictMode() throws Exception {
OptimizerFactory.setDefaultOptimizer("ASM");
DataConversion.addConversionHandler(Date.class, new MVELDateCoercion());
ParserContext ctx = new ParserContext();
ctx.addImport("Cheese", Cheese.class);
ctx.setStrongTyping(true);
ctx.setStrictTypeEnforcement(true);
Locale.setDefault(Locale.US);
Cheese expectedCheese = new Cheese();
expectedCheese.setUseBy(new SimpleDateFormat("dd-MMM-yyyy").parse("10-Jul-1974"));
ExpressionCompiler compiler = new ExpressionCompiler("c = new Cheese(); c.useBy = '10-Jul-1974'; return c");
Cheese actualCheese = (Cheese) executeExpression(compiler.compile(ctx), createTestMap());
assertEquals(expectedCheese.getUseBy(), actualCheese.getUseBy());
}
public static class MVELDateCoercion implements ConversionHandler {
public boolean canConvertFrom(Class cls) {
if (cls == String.class || cls.isAssignableFrom(Date.class)) {
return true;
}
else {
return false;
}
}
public Object convertFrom(Object o) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
if (o instanceof String) {
return sdf.parse((String) o);
}
else {
return o;
}
}
catch (Exception e) {
throw new RuntimeException("Exception was thrown", e);
}
}
}
private static final KnowledgeHelperFixer fixer = new KnowledgeHelperFixer();
public void testSingleLineCommentSlash() {
String result = fixer.fix(" //System.out.println( \"help\" );\r\n System.out.println( \"help\" ); \r\n list.add( $person );");
assertEquals(" //System.out.println( \"help\" );\r\n System.out.println( \"help\" ); \r\n list.add( $person );",
result);
}
public void testSingleLineCommentHash() {
String result = fixer.fix(" #System.out.println( \"help\" );\r\n System.out.println( \"help\" ); \r\n list.add( $person );");
assertEquals(" #System.out.println( \"help\" );\r\n System.out.println( \"help\" ); \r\n list.add( $person );",
result);
}
public void testMultiLineComment() {
String result = fixer.fix(" /*System.out.println( \"help\" );\r\n*/ System.out.println( \"help\" ); \r\n list.add( $person );");
assertEquals(" /*System.out.println( \"help\" );\r\n*/ System.out.println( \"help\" ); \r\n list.add( $person );",
result);
}
public void testAdd__Handle__Simple() {
String result = fixer.fix("update(myObject );");
assertEqualsIgnoreWhitespace("drools.update(myObject );",
result);
result = fixer.fix("update ( myObject );");
assertEqualsIgnoreWhitespace("drools.update( myObject );",
result);
}
public void testAdd__Handle__withNewLines() {
final String result = fixer.fix("\n\t\n\tupdate( myObject );");
assertEqualsIgnoreWhitespace("\n\t\n\tdrools.update( myObject );",
result);
}
public void testAdd__Handle__rComplex() {
String result = fixer.fix("something update( myObject); other");
assertEqualsIgnoreWhitespace("something drools.update( myObject); other",
result);
result = fixer.fix("something update ( myObject );");
assertEqualsIgnoreWhitespace("something drools.update( myObject );",
result);
result = fixer.fix(" update( myObject ); x");
assertEqualsIgnoreWhitespace(" drools.update( myObject ); x",
result);
//should not touch, as it is not a stand alone word
result = fixer.fix("xxupdate(myObject ) x");
assertEqualsIgnoreWhitespace("xxupdate(myObject ) x",
result);
}
public void testMultipleMatches() {
String result = fixer.fix("update(myObject); update(myObject );");
assertEqualsIgnoreWhitespace("drools.update(myObject); drools.update(myObject );",
result);
result = fixer.fix("xxx update(myObject ); update( myObject ); update( yourObject ); yyy");
assertEqualsIgnoreWhitespace("xxx drools.update(myObject ); drools.update( myObject ); drools.update( yourObject ); yyy",
result);
}
public void testAssert1() {
final String raw = "insert( foo );";
final String result = "drools.insert( foo );";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testAssert2() {
final String raw = "some code; insert( new String(\"foo\") );\n More();";
final String result = "some code; drools.insert( new String(\"foo\") );\n More();";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testAssertLogical() {
final String raw = "some code; insertLogical(new String(\"foo\"));\n More();";
final String result = "some code; drools.insertLogical(new String(\"foo\"));\n More();";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testModifyRetractModifyInsert() {
final String raw = "some code; insert( bar ); modifyRetract( foo );\n More(); retract( bar ); modifyInsert( foo );";
final String result = "some code; drools.insert( bar ); drools.modifyRetract( foo );\n More(); drools.retract( bar ); drools.modifyInsert( foo );";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testAllActionsMushedTogether() {
String result = fixer.fix("insert(myObject ); update(ourObject);\t retract(herObject);");
assertEqualsIgnoreWhitespace("drools.insert(myObject ); drools.update(ourObject);\t drools.retract(herObject);",
result);
result = fixer.fix("insert( myObject ); update(ourObject);\t retract(herObject );\ninsert( myObject ); update(ourObject);\t retract( herObject );");
assertEqualsIgnoreWhitespace("drools.insert( myObject ); drools.update(ourObject);\t drools.retract(herObject );\ndrools.insert( myObject ); drools.update(ourObject);\t drools.retract( herObject );",
result);
}
public void testLeaveLargeAlone() {
final String original = "yeah yeah yeah minsert( xxx ) this is a long() thing Person (name=='drools') modify a thing";
final String result = fixer.fix(original);
assertEqualsIgnoreWhitespace(original,
result);
}
public void testWithNull() {
final String original = null;
final String result = fixer.fix(original);
assertEqualsIgnoreWhitespace(original,
result);
}
public void testLeaveAssertAlone() {
final String original = "drools.insert(foo)";
assertEqualsIgnoreWhitespace(original,
fixer.fix(original));
}
public void testLeaveAssertLogicalAlone() {
final String original = "drools.insertLogical(foo)";
assertEqualsIgnoreWhitespace(original,
fixer.fix(original));
}
public void testWackyAssert() {
final String raw = "System.out.println($person1.getName() + \" and \" + $person2.getName() +\" are sisters\");\n" + "insert($person1.getName(\"foo\") + \" and \" + $person2.getName() +\" are sisters\"); yeah();";
final String expected = "System.out.println($person1.getName() + \" and \" + $person2.getName() +\" are sisters\");\n" + "drools.insert($person1.getName(\"foo\") + \" and \" + $person2.getName() +\" are sisters\"); yeah();";
assertEqualsIgnoreWhitespace(expected,
fixer.fix(raw));
}
public void testMoreAssertCraziness() {
final String raw = "foobar(); (insert(new String(\"blah\").get()); bangBangYudoHono();)";
assertEqualsIgnoreWhitespace("foobar(); (drools.insert(new String(\"blah\").get()); bangBangYudoHono();)",
fixer.fix(raw));
}
public void testRetract() {
final String raw = "System.out.println(\"some text\");retract(object);";
assertEqualsIgnoreWhitespace("System.out.println(\"some text\");drools.retract(object);",
fixer.fix(raw));
}
private void assertEqualsIgnoreWhitespace(final String expected, final String actual) {
if (expected == null || actual == null) {
assertEquals(expected, actual);
return;
}
final String cleanExpected = expected.replaceAll("\\s+", "");
final String cleanActual = actual.replaceAll("\\s+", "");
assertEquals(cleanExpected, cleanActual);
}
public void testReturnType1() {
assertEquals(Double.class, new ExpressionCompiler("100.5").compile().getKnownEgressType());
}
public void testReturnType2() {
assertEquals(Integer.class, new ExpressionCompiler("1").compile().getKnownEgressType());
}
public void testStrongTyping3() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
try {
new ExpressionCompiler("foo.toUC(100.5").compile(ctx);
}
catch (Exception e) {
// should fail.
return;
}
assertTrue(false);
}
public void testEgressType1() {
assertEquals(Boolean.class, new ExpressionCompiler("foo != null").compile().getKnownEgressType());
}
public void testIncrementInBooleanStatement() {
assertEquals(true, test("hour++ < 61 && hour == 61"));
}
public void testIncrementInBooleanStatement2() {
assertEquals(true, test("++hour == 61"));
}
public void testDeepNestedLoopsInFunction() {
assertEquals(10, test("def increment(i) { i + 1 }; def ff(i) { x = 0; while (i < 1) { " +
"x++; while (i < 10) { i = increment(i); } }; if (x == 1) return i; else -1; }; i = 0; ff(i);"));
}
public void testArrayDefinitionWithInitializer() {
String[] compareTo = new String[]{"foo", "bar"};
String[] results = (String[]) test("new String[] { 'foo', 'bar' }");
for (int i = 0; i < compareTo.length; i++) {
if (!compareTo[i].equals(results[i])) throw new AssertionError("arrays do not match.");
}
}
public void testStaticallyTypedItemInForEach() {
assertEquals("1234", test("StringBuffer sbuf = new StringBuffer(); foreach (int i : new int[] { 1,2,3,4 }) { sbuf.append(i); }; sbuf.toString()"));
}
public void testArrayDefinitionWithCoercion() {
Double[] d = (Double[]) test("new double[] { 1,2,3,4 }");
assertEquals(2d, d[1]);
}
public void testArrayDefinitionWithCoercion2() {
Float[] d = (Float[]) test("new float[] { 1,2,3,4 }");
assertEquals(2f, d[1]);
}
public void testStaticallyTypedLong() {
assertEquals(10l, test("10l"));
}
public void testCompileTimeCoercion() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("foo", Foo.class);
assertEquals(true, executeExpression(new ExpressionCompiler("foo.bar.woof == 'true'").compile(ctx), createTestMap()));
}
public void testHexCharacter() {
assertEquals(0x0A, MVEL.eval("0x0A"));
}
public void testOctalEscapes() {
assertEquals("\344", MVEL.eval("'\\344'"));
}
public void testOctalEscapes2() {
assertEquals("\7", MVEL.eval("'\\7'"));
}
public void testOctalEscapes3() {
assertEquals("\777", MVEL.eval("'\\777'"));
}
public void testUniHex1() {
assertEquals("\uFFFF::", MVEL.eval("'\\uFFFF::'"));
}
public void testNumLiterals() {
assertEquals(1e1f, MVEL.eval("1e1f"));
}
public void testNumLiterals2() {
assertEquals(2.f, MVEL.eval("2.f"));
}
public void testNumLiterals3() {
assertEquals(.3f, MVEL.eval(".3f"));
}
public void testNumLiterals4() {
assertEquals(3.14f, MVEL.eval("3.14f"));
}
public void testNumLiterals5() {
Object o = MVEL.eval("1e1");
assertEquals(1e1, MVEL.eval("1e1"));
}
public void testNumLiterals6() {
assertEquals(2., MVEL.eval("2."));
}
public void testNumLiterals7() {
assertEquals(.3, MVEL.eval(".3"));
}
public void testNumLiterals8() {
assertEquals(1e-9d, MVEL.eval("1e-9d"));
}
public void testNumLiterals9() {
assertEquals(0x400921FB54442D18L, MVEL.eval("0x400921FB54442D18L"));
}
public void testArrayCreation2() {
String[][] s = (String[][])
test("new String[][] {{\"2008-04-01\", \"2008-05-10\"}, {\"2007-03-01\", \"2007-02-12\"}}");
assertEquals("2007-03-01", s[1][0]);
}
public void testArrayCreation3() {
OptimizerFactory.setDefaultOptimizer("ASM");
Serializable ce =
compileExpression("new String[][] {{\"2008-04-01\", \"2008-05-10\"}, {\"2007-03-01\", \"2007-02-12\"}}");
String[][] s = (String[][])
executeExpression(ce);
assertEquals("2007-03-01", s[1][0]);
}
public void testArrayCreation4() {
String[][] s = (String[][])
test("new String[][]{{\"2008-04-01\", \"2008-05-10\"}, {\"2007-03-01\", \"2007-02-12\"}}");
assertEquals("2007-03-01", s[1][0]);
}
public void testNakedMethodCall() {
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
OptimizerFactory.setDefaultOptimizer("ASM");
Serializable c = compileExpression("tm = System.currentTimeMillis");
assertTrue(((Long) executeExpression(c, new HashMap())) > 0);
OptimizerFactory.setDefaultOptimizer("reflective");
assertTrue(((Long) executeExpression(c, new HashMap())) > 0);
Map map = new HashMap();
map.put("foo", new Foo());
c = compileExpression("foo.happy");
assertEquals("happyBar", executeExpression(c, map));
OptimizerFactory.setDefaultOptimizer("ASM");
c = compileExpression("foo.happy");
assertEquals("happyBar", executeExpression(c, map));
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = false;
}
public void testDecl() {
assertEquals((char) 100, test("char chr; chr = 100; chr"));
}
public void testInlineUnion() {
assertEquals("test", test("{'foo', 'test'}[1]"));
}
public static double minim(double[] tab) {
double min = Float.MAX_VALUE;
for (int i = 0; i < tab.length; i++) {
if (min > tab[i]) {
min = tab[i];
}
}
return min;
}
public void testJIRA113() {
assertEquals(true, test("org.mvel2.tests.core.CoreConfidenceTests.minim( new double[] {456.2, 2.3} ) == 2.3"));
}
public void testSetCoercion() {
Serializable s = compileSetExpression("name");
Foo foo = new Foo();
executeSetExpression(s, foo, 12);
assertEquals("12", foo.getName());
foo = new Foo();
setProperty(foo, "name", 12);
assertEquals("12", foo.getName());
}
public void testSetCoercion2() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("sampleBean", SampleBean.class);
Serializable s = compileSetExpression("sampleBean.map2['bleh']", ctx);
Foo foo = new Foo();
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue());
foo = new Foo();
executeSetExpression(s, foo, "13");
assertEquals(13, foo.getSampleBean().getMap2().get("bleh").intValue());
OptimizerFactory.setDefaultOptimizer("ASM");
ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("sampleBean", SampleBean.class);
s = compileSetExpression("sampleBean.map2['bleh']", ctx);
foo = new Foo();
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue());
executeSetExpression(s, foo, new Integer(12));
assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue());
}
public void testListCoercion() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
Serializable s = compileSetExpression("bar.testList[0]", ctx);
Foo foo = new Foo();
foo.getBar().getTestList().add(new Integer(-1));
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getBar().getTestList().get(0).intValue());
foo = new Foo();
foo.getBar().getTestList().add(new Integer(-1));
executeSetExpression(s, foo, "13");
assertEquals(13, foo.getBar().getTestList().get(0).intValue());
OptimizerFactory.setDefaultOptimizer("ASM");
ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
s = compileSetExpression("bar.testList[0]", ctx);
foo = new Foo();
foo.getBar().getTestList().add(new Integer(-1));
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getBar().getTestList().get(0).intValue());
executeSetExpression(s, foo, "13");
assertEquals(13, foo.getBar().getTestList().get(0).intValue());
}
public void testArrayCoercion1() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
Serializable s = compileSetExpression("bar.intarray[0]", ctx);
Foo foo = new Foo();
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getBar().getIntarray()[0].intValue());
foo = new Foo();
executeSetExpression(s, foo, "13");
assertEquals(13, foo.getBar().getIntarray()[0].intValue());
OptimizerFactory.setDefaultOptimizer("ASM");
ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
s = compileSetExpression("bar.intarray[0]", ctx);
foo = new Foo();
executeSetExpression(s, foo, "12");
assertEquals(12, foo.getBar().getIntarray()[0].intValue());
executeSetExpression(s, foo, "13");
assertEquals(13, foo.getBar().getIntarray()[0].intValue());
}
public void testFieldCoercion1() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
Serializable s = compileSetExpression("bar.assignTest", ctx);
Foo foo = new Foo();
executeSetExpression(s, foo, 12);
assertEquals("12", foo.getBar().getAssignTest());
foo = new Foo();
executeSetExpression(s, foo, 13);
assertEquals("13", foo.getBar().getAssignTest());
OptimizerFactory.setDefaultOptimizer("ASM");
ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("bar", Bar.class);
s = compileSetExpression("bar.assignTest", ctx);
foo = new Foo();
executeSetExpression(s, foo, 12);
assertEquals("12", foo.getBar().getAssignTest());
executeSetExpression(s, foo, 13);
assertEquals("13", foo.getBar().getAssignTest());
}
public void testJIRA115() {
String exp = "results = new java.util.ArrayList(); foreach (element : elements) { if( {1,32769,32767} contains element ) { results.add(element); } }; results";
Map map = new HashMap();
map.put("elements", new int[]{1, 32769, 32767});
ArrayList result = (ArrayList) MVEL.eval(exp, map);
assertEquals(3, result.size());
}
public void testStaticTyping2() {
String exp = "int x = 5; int y = 2; new int[] { x, y }";
Integer[] res = (Integer[]) MVEL.eval(exp, new HashMap());
assertEquals(5, res[0].intValue());
assertEquals(2, res[1].intValue());
}
public void testFunctions5() {
String exp = "def foo(a,b) { a + b }; foo(1.5,5.25)";
System.out.println(MVEL.eval(exp, new HashMap()));
}
public void testChainedMethodCallsWithParams() {
assertEquals(true, test("foo.toUC(\"abcd\").equals(\"ABCD\")"));
}
public void testIsUsedInIf() {
assertEquals(true, test("c = 'str'; if (c is String) { true; } else { false; } "));
}
public void testJIRA122() {
Serializable s = compileExpression("java.lang.Character.toLowerCase(name.charAt(0)) == 'a'");
OptimizerFactory.setDefaultOptimizer("ASM");
Map map = new HashMap();
map.put("name", "Adam");
assertEquals(true, executeExpression(s, map));
assertEquals(true, executeExpression(s, map));
}
public void testJIRA103() {
MvelContext mvelContext = new MvelContext();
MVEL.setProperty(mvelContext, "regkeys", "s");
}
public void testJIRA103b() {
MvelContext mvelContext = new MvelContext();
Map map = new HashMap();
map.put("ctx", mvelContext);
Serializable c = compileExpression("ctx.regkeys = 'foo'");
executeExpression(c, map);
executeExpression(c, map);
}
public void testNewUsingWith() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addImport(Foo.class);
ctx.addImport(Bar.class);
Serializable s = compileExpression("[ 'foo' : (with ( new Foo() ) { bar = with ( new Bar() ) { name = 'ziggy' } }) ]", ctx);
OptimizerFactory.setDefaultOptimizer("reflective");
assertEquals("ziggy", (((Foo) ((Map) executeExpression(s)).get("foo")).getBar().getName()));
}
private static Map<String, Boolean> JIRA124_CTX = Collections.singletonMap("testValue", true);
public void testJIRA124() throws Exception {
assertEquals("A", testTernary(1, "testValue == true ? 'A' : 'B' + 'C'"));
assertEquals("AB", testTernary(2, "testValue ? 'A' + 'B' : 'C'"));
assertEquals("A", testTernary(3, "(testValue ? 'A' : 'B' + 'C')"));
assertEquals("AB", testTernary(4, "(testValue ? 'A' + 'B' : 'C')"));
assertEquals("A", testTernary(5, "(testValue ? 'A' : ('B' + 'C'))"));
assertEquals("AB", testTernary(6, "(testValue ? ('A' + 'B') : 'C')"));
JIRA124_CTX = Collections.singletonMap("testValue", false);
assertEquals("BC", testTernary(1, "testValue ? 'A' : 'B' + 'C'"));
assertEquals("C", testTernary(2, "testValue ? 'A' + 'B' : 'C'"));
assertEquals("BC", testTernary(3, "(testValue ? 'A' : 'B' + 'C')"));
assertEquals("C", testTernary(4, "(testValue ? 'A' + 'B' : 'C')"));
assertEquals("BC", testTernary(5, "(testValue ? 'A' : ('B' + 'C'))"));
assertEquals("C", testTernary(6, "(testValue ? ('A' + 'B') : 'C')"));
}
private static Object testTernary(int i, String expression) throws Exception {
Object val;
Object val2;
try {
val = executeExpression(compileExpression(expression), JIRA124_CTX);
}
catch (Exception e) {
System.out.println("FailedCompiled[" + i + "]:" + expression);
throw e;
}
try {
val2 = MVEL.eval(expression, JIRA124_CTX);
}
catch (Exception e) {
System.out.println("FailedEval[" + i + "]:" + expression);
throw e;
}
if (((val == null || val2 == null) && val != val2) || (val != null && !val.equals(val2))) {
throw new AssertionError("results do not match (" + String.valueOf(val) + " != " + String.valueOf(val2) + ")");
}
return val;
}
public void testMethodCaching() {
MVEL.eval("for (pet: getPets()) pet.run();", new PetStore());
}
public static class PetStore {
public List getPets() {
List pets = new ArrayList();
pets.add(new Dog());
pets.add(new Cat());
return pets;
}
}
public static class Pet {
public void run() {
}
}
public static class Dog extends Pet {
@Override
public void run() {
System.out.println("dog is running");
}
}
public static class Cat extends Pet {
@Override
public void run() {
System.out.println("cat is running");
}
}
public void testSetExpressions2() {
Foo foo = new Foo();
Collection col = new ArrayList();
final Serializable fooExpr = compileSetExpression("collectionTest");
executeSetExpression(fooExpr, foo, col);
assertEquals(col, foo.getCollectionTest());
}
public class Fruit {
public class Apple {
}
}
public void testInnerClassReference() {
assertEquals(Fruit.Apple.class, test("import " + CoreConfidenceTests.class.getName() + "; CoreConfidenceTests.Fruit.Apple"));
}
public void testEdson() {
assertEquals("foo", test("list = new java.util.ArrayList(); list.add(new String('foo')); list[0]"));
}
public void testEnumSupport() {
MyInterface myInterface = new MyClass();
myInterface.setType(MyInterface.MY_ENUM.TWO, true);
boolean isType = MVEL.eval("isType(org.mvel2.tests.core.res.MyInterface$MY_ENUM.ONE)", myInterface, Boolean.class);
System.out.println(isType);
}
public void testOperatorPrecedenceOrder() {
Serializable compiled = compileExpression("bean1.successful && bean2.failed || bean1.failed && bean2.successful");
Map context = new HashMap();
BeanB bean1 = new BeanB(true);
BeanB bean2 = new BeanB(false);
context.put("bean1", bean1);
context.put("bean2", bean2);
System.out.println("interpreted: " +
MVEL.eval("bean1.successful && bean2.failed || bean1.failed && bean2.successful", context));
assertEquals(bean1.isSuccessful() && bean2.isFailed() || bean1.isFailed() && bean2.isSuccessful(),
(boolean) executeExpression(compiled, context, Boolean.class));
}
public static class BeanB {
private boolean successful;
public BeanB(boolean successful) {
this.successful = successful;
}
public boolean isSuccessful() {
return successful;
}
public boolean isFailed() {
return !successful;
}
}
public void testJIRA139() {
ParserContext ctx = new ParserContext();
ctx.addImport("ReflectionUtil", ReflectionUtil.class);
Serializable s = compileExpression("ReflectionUtil.getGetter('foo')", ctx);
assertEquals(ReflectionUtil.getGetter("foo"), executeExpression(s));
}
public void testJIRA140() {
ParserContext ctx = new ParserContext();
Serializable s = compileExpression(
"import org.mvel2.tests.core.res.*;" +
"cols = new Column[] { new Column('name', 20), new Column('age', 2) };" +
"grid = new Grid(new Model(cols));", ctx
);
Grid g = (Grid) executeExpression(s, new HashMap());
assertEquals(g.getModel().getColumns()[0].getName(), "name");
assertEquals(g.getModel().getColumns()[0].getLength(), 20);
assertEquals(g.getModel().getColumns()[1].getName(), "age");
assertEquals(g.getModel().getColumns()[1].getLength(), 2);
}
public void testVerifierWithIndexedProperties() {
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.addInput("base", Base.class);
Serializable s = compileExpression("base.fooMap['foo'].setName('coffee')", ctx);
Map vars = new HashMap();
vars.put("base", new Base());
executeExpression(s, vars);
assertEquals("coffee", ((Base) vars.get("base")).fooMap.get("foo").getName());
}
public void testPrimitiveTypes() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("base", Base.class);
Serializable s = compileExpression("int x = 5; x = x + base.intValue; x", ctx);
Map vars = new HashMap();
vars.put("base", new Base());
Number x = (Number) executeExpression(s, vars);
assertEquals(15, x.intValue());
}
public void testAutoBoxing() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
//ctx.addInput("base", Base.class);
Serializable s = compileExpression("(list = new java.util.ArrayList()).add( 5 ); list", ctx);
Map vars = new HashMap();
//vars.put("base", new Base());
List list = (List) executeExpression(s, vars);
assertEquals(1, list.size());
}
public void testAutoBoxing2() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("base", Base.class);
Serializable s = compileExpression("java.util.List list = new java.util.ArrayList(); list.add( base.intValue ); list", ctx);
Map vars = new HashMap();
vars.put("base", new Base());
List list = (List) executeExpression(s, vars);
assertEquals(1, list.size());
}
public void testTypeCoercion() {
OptimizerFactory.setDefaultOptimizer("ASM");
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("base", Base.class);
Serializable s = compileExpression("java.math.BigInteger x = new java.math.BigInteger( \"5\" ); x + base.intValue;", ctx);
Map vars = new HashMap();
vars.put("base", new Base());
Number x = (Number) executeExpression(s, vars);
assertEquals(15, x.intValue());
}
public void testTypeCoercion2() {
OptimizerFactory.setDefaultOptimizer("reflective");
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("base", Base.class);
Serializable s = compileExpression("java.math.BigInteger x = new java.math.BigInteger( \"5\" ); x + base.intValue;", ctx);
Map vars = new HashMap();
vars.put("base", new Base());
Number x = (Number) executeExpression(s, vars);
assertEquals(15, x.intValue());
}
public void testEmpty() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
Serializable s = compileExpression("list = new java.util.ArrayList(); list == empty", ctx);
Map vars = new HashMap();
Boolean x = (Boolean) executeExpression(s, vars);
assertNotNull(x);
assertTrue(x.booleanValue());
}
public void testMapsAndLists() {
OptimizerFactory.setDefaultOptimizer("ASM");
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addImport(HashMap.class);
ctx.addImport(ArrayList.class);
ctx.addInput("list", List.class);
String expression = "m = new HashMap();\n" +
"l = new ArrayList();\n" +
"l.add(\"first\");\n" +
"m.put(\"content\", l);\n" +
"list.add(((ArrayList)m[\"content\"])[0]);";
Serializable s = compileExpression(expression, ctx);
Map vars = new HashMap();
List list = new ArrayList();
vars.put("list", list);
Boolean result = (Boolean) executeExpression(s, vars);
assertNotNull(result);
assertTrue(result);
assertEquals(1, list.size());
assertEquals("first", list.get(0));
}
public void testMapsAndLists2() {
OptimizerFactory.setDefaultOptimizer("reflective");
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addImport(HashMap.class);
ctx.addImport(ArrayList.class);
ctx.addInput("list", List.class);
String expression = "m = new HashMap();\n" +
"l = new ArrayList();\n" +
"l.add(\"first\");\n" +
"m.put(\"content\", l);\n" +
"list.add(((ArrayList)m[\"content\"])[0]);";
Serializable s = compileExpression(expression, ctx);
Map vars = new HashMap();
List list = new ArrayList();
vars.put("list", list);
Boolean result = (Boolean) executeExpression(s, vars);
assertNotNull(result);
assertTrue(result);
assertEquals(1, list.size());
assertEquals("first", list.get(0));
}
public void testReturnBoolean() {
String ex = "list = new java.util.ArrayList(); return list != null";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
Serializable s = compileExpression(ex, ctx);
assertEquals(true, executeExpression(s, new HashMap()));
}
public void testInlineListSensitivenessToSpaces() {
String ex = "([\"a\",\"b\", \"c\"])";
ParserContext ctx = new ParserContext();
Serializable s = compileExpression(ex, ctx);
List result = (List) executeExpression(s, new HashMap());
assertNotNull(result);
assertEquals("a", result.get(0));
assertEquals("b", result.get(1));
assertEquals("c", result.get(2));
}
public void testComaProblemStrikesBack() {
String ex = "a.explanation = \"There is a coma, in here\"";
ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler(ex);
Serializable s = compiler.compile(ctx);
Base a = new Base();
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("a", a);
executeExpression(s, variables);
assertEquals("There is a coma, in here", a.data);
}
public void testMultiVarDeclr() {
String ex = "var a, b, c";
ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.setVerifyOnly(true);
compiler.compile(ctx);
assertEquals(3, ctx.getVariables().size());
}
public void testVarDeclr() {
String ex = "var a";
ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.setVerifyOnly(true);
compiler.compile(ctx);
assertEquals(1, ctx.getVariables().size());
}
public void testMultiTypeVarDeclr() {
String ex = "String a, b, c";
ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.compile(ctx);
assertNotNull(ctx.getVariables());
assertEquals(3, ctx.getVariables().entrySet().size());
for (Map.Entry<String, Class> entry : ctx.getVariables().entrySet()) {
assertEquals(String.class, entry.getValue());
}
}
public void testMultiTypeVarDeclr2() {
String ex = "String a = 'foo', b = 'baz', c = 'bar'";
ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.compile(ctx);
assertNotNull(ctx.getVariables());
assertEquals(3, ctx.getVariables().entrySet().size());
for (Map.Entry<String, Class> entry : ctx.getVariables().entrySet()) {
assertEquals(String.class, entry.getValue());
}
}
public void testMultiTypeVarDeclr3() {
String ex = "int a = 52 * 3, b = 8, c = 16;";
ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler(ex);
Serializable s = compiler.compile(ctx);
assertNotNull(ctx.getVariables());
assertEquals(3, ctx.getVariables().entrySet().size());
for (Map.Entry<String, Class> entry : ctx.getVariables().entrySet()) {
assertEquals(Integer.class, entry.getValue());
}
Map vars = new HashMap();
executeExpression(s, vars);
assertEquals(52 * 3, vars.get("a"));
assertEquals(8, vars.get("b"));
assertEquals(16, vars.get("c"));
}
public void testTypeVarDeclr() {
String ex = "String a;";
ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.compile(ctx);
assertNotNull(ctx.getVariables());
assertEquals(1, ctx.getVariables().entrySet().size());
for (Map.Entry<String, Class> entry : ctx.getVariables().entrySet()) {
assertEquals(String.class, entry.getValue());
}
}
public static interface Services {
public final static String A_CONST = "Hello World";
public void log(String text);
}
public void testStringConcatenation() {
// debugging MVEL code, it seems that MVEL 'thinks' that the result of the expression:
// "Drop +5%: "+$sb+" avg: $"+$av+" price: $"+$pr
// is a double, and as so, he looks for a method:
// Services.log( double );
// but finds only:
// Services.log( String );
// raising the error.
String ex = "services.log( \"Drop +5%: \"+$sb+\" avg: $\"+$av+\" price: $\"+$pr );";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("$sb", String.class);
ctx.addInput("$av", double.class);
ctx.addInput("$pr", double.class);
ctx.addInput("services", Services.class);
try {
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.compile(ctx);
}
catch (Throwable e) {
e.printStackTrace();
fail("Should not raise exception: " + e.getMessage());
}
}
public void testStringConcatenation2() {
String ex = "services.log( $cheese + \" some string \" );";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("$cheese", Cheese.class);
ctx.addInput("services", Services.class);
try {
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.compile(ctx);
}
catch (Throwable e) {
e.printStackTrace();
fail("Should not raise exception: " + e.getMessage());
}
}
public void testMapsWithVariableAsKey() {
String ex = "aMap[aKey] == 'aValue'";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(false);
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.setVerifyOnly(true);
compiler.compile(ctx);
Set<String> requiredInputs = compiler.getParserContextState().getInputs().keySet();
assertTrue(requiredInputs.contains("aMap"));
assertTrue(requiredInputs.contains("aKey"));
}
public void testImperativeCode() {
String ex = "if (cheese.price == 10) { cheese.price = 5; }";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("cheese", Cheese.class);
// following line is causing an infinite loop when compiling the code
// NOTE: drools expects the code to compile, even in the presence of the
// "if" statement, but in case the application tries to execute the code,
// drools expects mvel to raise the exception, since control flow statements
// are disabled
AbstractParser.setLanguageLevel(AbstractParser.LEVEL_4_ASSIGNMENT);
try {
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.compile(ctx);
}
catch (Exception e) {
return;
}
finally {
AbstractParser.setLanguageLevel(AbstractParser.LEVEL_5_CONTROL_FLOW);
}
fail("Should have thrown exception");
}
public static void testProjectionUsingThis() {
Set records = new HashSet();
for (int i = 0; i < 53; i++) {
Bean2 record = new Bean2(i);
records.add(record);
}
Object result = MVEL.eval("(_prop in this)", records);
System.out.println("result: " + result);
}
public static final class Bean2 {
public final int _prop;
public Bean2(int prop_) {
_prop = prop_;
}
public int getProp() {
return _prop;
}
public String toString() {
return Integer.toString(_prop);
}
}
public void testUnaryOpNegation1() {
assertEquals(false, test("!new Boolean(true)"));
}
public void testUnaryOpNegation2() {
assertEquals(true, test("!isdef _foozy_"));
}
public class Az {
public void foo(String s) {
}
}
public class Bz extends Az {
}
public void testJIRA151() {
OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE);
Bz b = new Bz();
ParserContext context = new ParserContext();
Object expression = MVEL.compileExpression("a.foo(value)", context);
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("a", b);
variables.put("value", 123);
for (int i = 0; i < 100; i++) {
System.out.println("i: " + i);
System.out.flush();
MVEL.executeExpression(expression, variables);
}
}
public void testJIRA151b() {
OptimizerFactory.setDefaultOptimizer("ASM");
Bz b = new Bz();
ParserContext context = new ParserContext();
Object expression = MVEL.compileExpression("a.foo(value)", context);
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("a", b);
variables.put("value", 123);
for (int i = 0; i < 100; i++) {
System.out.println("i: " + i);
System.out.flush();
MVEL.executeExpression(expression, variables);
}
}
public void testJIRA153() {
assertEquals(false, MVEL.eval("!(true)"));
assertEquals(false, MVEL.executeExpression(MVEL.compileExpression("!(true)")));
}
public void testJIRA154() {
Map m = createTestMap();
m.put("returnTrue", MVEL.getStaticMethod(CoreConfidenceTests.class, "returnTrue", new Class[0]));
assertEquals(false, MVEL.eval("!returnTrue()", m));
}
public void testJIRA154b() {
ParserContext pctx = new ParserContext();
pctx.addImport("returnTrue", MVEL.getStaticMethod(CoreConfidenceTests.class, "returnTrue", new Class[0]));
assertEquals(false, MVEL.executeExpression(MVEL.compileExpression("!(returnTrue())", pctx)));
}
public void testJIRA155() {
ParserContext pctx = new ParserContext();
pctx.addImport("returnTrue", MVEL.getStaticMethod(CoreConfidenceTests.class, "returnTrue", new Class[0]));
assertEquals(true, MVEL.executeExpression(MVEL.compileExpression("!true || returnTrue()", pctx)));
}
public void testJIRA155b() {
ParserContext pctx = new ParserContext();
pctx.addImport("returnTrue", MVEL.getStaticMethod(CoreConfidenceTests.class, "returnTrue", new Class[0]));
assertEquals(true, MVEL.executeExpression(MVEL.compileExpression("!(!true || !returnTrue())", pctx)));
}
public static boolean returnTrue() {
return true;
}
}
|
package org.mvel2.tests.core;
import junit.framework.TestCase;
import org.mvel2.*;
import org.mvel2.ast.ASTNode;
import org.mvel2.compiler.CompiledExpression;
import org.mvel2.compiler.ExecutableStatement;
import org.mvel2.compiler.ExpressionCompiler;
import org.mvel2.integration.Interceptor;
import org.mvel2.integration.PropertyHandlerFactory;
import org.mvel2.integration.ResolverTools;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.ClassImportResolverFactory;
import org.mvel2.integration.impl.DefaultLocalVariableResolverFactory;
import org.mvel2.integration.impl.MapVariableResolverFactory;
import org.mvel2.optimizers.OptimizerFactory;
import org.mvel2.tests.core.res.*;
import org.mvel2.tests.core.res.res2.ClassProvider;
import org.mvel2.tests.core.res.res2.Outer;
import org.mvel2.tests.core.res.res2.PublicClass;
import org.mvel2.util.ReflectionUtil;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.List;
import static java.util.Collections.unmodifiableCollection;
import static org.mvel2.MVEL.*;
import static org.mvel2.util.ParseTools.loadFromFile;
@SuppressWarnings({"ALL"})
public class CoreConfidenceTests extends AbstractTest {
public void testWhileUsingImports() {
Map<String, Object> imports = new HashMap<String, Object>();
imports.put("ArrayList",
java.util.ArrayList.class);
imports.put("List",
java.util.List.class);
ParserContext context = new ParserContext(imports, null, "testfile");
ExpressionCompiler compiler = new ExpressionCompiler("List list = new ArrayList(); return (list == empty)");
assertTrue((Boolean) executeExpression(compiler.compile(context),
new DefaultLocalVariableResolverFactory()));
}
public void testBooleanModeOnly2() {
assertEquals(false, (Object) DataConversion.convert(test("BWAH"), Boolean.class));
}
public void testBooleanModeOnly4() {
assertEquals(true, test("hour == (hour + 0)"));
}
// interpreted
public void testThisReferenceMapVirtualObjects() {
Map<String, String> map = new HashMap<String, String>();
map.put("foo",
"bar");
VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap<String, Object>());
factory.createVariable("this", map);
assertEquals(true,
eval("this.foo == 'bar'", map, factory));
}
// compiled - reflective
public void testThisReferenceMapVirtualObjects1() {
// Create our root Map object
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap<String, Object>());
factory.createVariable("this", map);
OptimizerFactory.setDefaultOptimizer("reflective");
// Run test
assertEquals(true,
executeExpression(compileExpression("this.foo == 'bar'"),
map,
factory));
}
// compiled - asm
public void testThisReferenceMapVirtualObjects2() {
// Create our root Map object
Map<String, String> map = new HashMap<String, String>();
map.put("foo",
"bar");
VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap<String, Object>());
factory.createVariable("this",
map);
// I think we can all figure this one out.
if (!Boolean.getBoolean("mvel2.disable.jit")) OptimizerFactory.setDefaultOptimizer("ASM");
// Run test
assertEquals(true,
executeExpression(compileExpression("this.foo == 'bar'"),
map,
factory));
}
public void testEvalToBoolean() {
assertEquals(true,
(boolean) evalToBoolean("true ",
"true"));
assertEquals(true,
(boolean) evalToBoolean("true ",
"true"));
}
public void testImport() {
assertEquals(HashMap.class,
test("import java.util.HashMap; HashMap;"));
}
public void testImport2() {
HashMap[] maps = (HashMap[]) MVEL.eval("import java.util.*; HashMap[] maps = new HashMap[10]; maps",
new HashMap());
// HashMap[] maps = (HashMap[]) test("import java.util.*; HashMap[] maps = new HashMap[10]; maps");
assertEquals(10,
maps.length);
}
public void testStaticImport() {
assertEquals(2.0,
test("import_static java.lang.Math.sqrt; sqrt(4)"));
}
/**
* Start collections framework based compliance tests
*/
public void testCreationOfSet() {
assertEquals("foo bar foo bar",
test("set = new java.util.LinkedHashSet(); "
+ "set.add('foo');" + "set.add('bar');"
+ "output = '';" + "foreach (item : set) {"
+ "output = output + item + ' ';"
+ "} "
+ "foreach (item : set) {"
+ "output = output + item + ' ';"
+ "} " + "output = output.trim();"
+ "if (set.size() == 2) { return output; }"));
}
public void testCreationOfList() {
assertEquals(5,
test("l = new java.util.LinkedList(); l.add('fun'); l.add('happy'); l.add('fun'); l.add('slide');"
+ "l.add('crap'); poo = new java.util.ArrayList(l); poo.size();"));
}
public void testMapOperations() {
assertEquals("poo5",
test("l = new java.util.ArrayList(); l.add('plop'); l.add('poo'); m = new java.util.HashMap();"
+ "m.put('foo', l); m.put('cah', 'mah'); m.put('bar', 'foo'); m.put('sarah', 'mike');"
+ "m.put('edgar', 'poe'); if (m.edgar == 'poe') { return m.foo[1] + m.size(); }"));
}
public void testStackOperations() {
assertEquals(10,
test("stk = new java.util.Stack();" + "stk.push(5);" + "stk.push(5);" + "stk.pop() + stk.pop();"));
}
public void testSystemOutPrint() {
test("a = 0;\r\nSystem.out.println('This is a test');");
}
// public void testClassImportViaFactory() {
// MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
// ClassImportResolverFactory classes = new ClassImportResolverFactory();
// classes.addClass(HashMap.class);
// ResolverTools.appendFactory(mvf, classes);
// assertTrue(executeExpression(compileExpression("HashMap map = new HashMap()",
// classes.getImportedClasses()),
// mvf) instanceof HashMap);
// public void testSataticClassImportViaFactory() {
// MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
// ClassImportResolverFactory classes = new ClassImportResolverFactory();
// classes.addClass(Person.class);
// ResolverTools.appendFactory(mvf,
// classes);
// assertEquals("tom",
// executeExpression(compileExpression("p = new Person('tom'); return p.name;",
// classes.getImportedClasses()),
// mvf));
public void testCheeseConstructor() {
MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap());
ClassImportResolverFactory classes = new ClassImportResolverFactory();
classes.addClass(Cheese.class);
ResolverTools.appendFactory(mvf,
classes);
assertTrue(executeExpression(compileExpression("cheese = new Cheese(\"cheddar\", 15);",
classes.getImportedClasses()),
mvf) instanceof Cheese);
}
public void testInterceptors() {
Interceptor testInterceptor = new Interceptor() {
public int doBefore(ASTNode node,
VariableResolverFactory factory) {
System.out.println("BEFORE Node: " + node.getName());
return 0;
}
public int doAfter(Object val,
ASTNode node,
VariableResolverFactory factory) {
System.out.println("AFTER Node: " + node.getName());
return 0;
}
};
Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
interceptors.put("test",
testInterceptor);
executeExpression(compileExpression("@test System.out.println('MIDDLE');",
null,
interceptors));
}
public void testSubtractNoSpace1() {
assertEquals(59,
test("hour-1"));
}
public void testStrictTypingCompilation() {
// OptimizerFactory.setDefaultOptimizer(OptimizerFactory.DYNAMIC);
ExpressionCompiler compiler = new ExpressionCompiler("a.foo;\nb.foo;\n x = 5");
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
try {
compiler.compile(ctx);
}
catch (CompileException e) {
e.printStackTrace();
return;
}
assertTrue(false);
// OptimizerFactory.setDefaultOptimizer(OptimizerFactory.DYNAMIC);
}
public void testEqualityRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("price == (new Integer( 5 ) + 5 ) ");
compiler.compile();
}
public void testEvaluationRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("(p.age * 2)");
compiler.compile();
assertTrue(compiler.getParserContextState().getInputs().containsKey("p"));
}
public void testIncrementAndAssignWithInputs() {
ExpressionCompiler compiler = new ExpressionCompiler("total += cheese");
compiler.compile();
assertTrue(compiler.getParserContextState().getInputs().containsKey("total"));
assertTrue(compiler.getParserContextState().getInputs().containsKey("cheese"));
}
public void testAssignmentRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("total = total + $cheese.price");
compiler.compile();
}
public void testTypeRegression() {
ExpressionCompiler compiler = new ExpressionCompiler("total = 0");
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
compiler.compile(ctx);
assertEquals(Integer.class,
compiler.getParserContextState().getVarOrInputType("total"));
}
public void testTestIntToLong() {
String s = "1+(long)a";
ParserContext pc = new ParserContext();
pc.addInput("a", Integer.class);
ExpressionCompiler compiler = new ExpressionCompiler(s, pc);
CompiledExpression expr = compiler.compile();
Map vars = new HashMap();
vars.put("a", 1);
Object r = ((ExecutableStatement) expr).getValue(null, new MapVariableResolverFactory(vars));
assertEquals(new Long(2), r);
}
public void testMapPropertyCreateCondensed() {
assertEquals("foo",
test("map = new java.util.HashMap(); map['test'] = 'foo'; map['test'];"));
}
public void testDeepMethod() {
assertEquals(false,
test("foo.bar.testList.add(new String()); foo.bar.testList == empty"));
}
public void testListAccessorAssign() {
String ex = "a = new java.util.ArrayList(); a.add('foo'); a.add('BAR'); a[1] = 'bar'; a[1]";
OptimizerFactory.setDefaultOptimizer("ASM");
Serializable s = MVEL.compileExpression(ex);
assertEquals("bar", MVEL.executeExpression(s, new HashMap()));
OptimizerFactory.setDefaultOptimizer(OptimizerFactory.DYNAMIC);
assertEquals("bar",
test("a = new java.util.ArrayList(); a.add('foo'); a.add('BAR'); a[1] = 'bar'; a[1]"));
}
public void testBracketInString() {
test("System.out.println('1)your guess was:');");
}
public void testNesting() {
assertEquals("foo",
test("new String(new String(new String(\"foo\")));"));
}
public void testTypeCast() {
assertEquals("10",
test("(String) 10"));
}
public void testTypeCast2() {
String ex = "map = new java.util.HashMap(); map.put('doggie', new java.util.ArrayList());" +
" ((java.util.ArrayList) map['doggie']).size()";
Map map = createTestMap();
assertEquals(0, MVEL.eval(ex, map));
assertEquals(0,
test(ex));
}
public void testMapAccessSemantics() {
Map<String, Object> outermap = new HashMap<String, Object>();
Map<String, Object> innermap = new HashMap<String, Object>();
innermap.put("test",
"foo");
outermap.put("innermap",
innermap);
assertEquals("foo",
testCompiledSimple("innermap['test']",
outermap,
null));
}
public void testMapBindingSemantics() {
Map<String, Object> outermap = new HashMap<String, Object>();
Map<String, Object> innermap = new HashMap<String, Object>();
innermap.put("test",
"foo");
outermap.put("innermap",
innermap);
setProperty(outermap,
"innermap['test']",
"bar");
assertEquals("bar",
testCompiledSimple("innermap['test']",
outermap,
null));
}
public void testMapNestedInsideList() {
ParserContext ctx = new ParserContext();
ctx.addImport("User",
User.class);
ExpressionCompiler compiler =
new ExpressionCompiler("users = [ 'darth' : new User('Darth', 'Vadar')," +
"\n'bobba' : new User('Bobba', 'Feta') ]; [ users.get('darth'), users.get('bobba') ]");
// Serializable s = compiler.compileShared(ctx);
List list = (List) executeExpression(compiler.compile(ctx),
new HashMap());
User user = (User) list.get(0);
assertEquals("Darth",
user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba",
user.getFirstName());
compiler =
new ExpressionCompiler("users = [ 'darth' : new User('Darth', 'Vadar')," +
"\n'bobba' : new User('Bobba', 'Feta') ]; [ users['darth'], users['bobba'] ]");
list = (List) executeExpression(compiler.compile(ctx),
new HashMap());
user = (User) list.get(0);
assertEquals("Darth",
user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba",
user.getFirstName());
}
public void testListNestedInsideList() {
ParserContext ctx = new ParserContext();
ctx.addImport("User",
User.class);
ExpressionCompiler compiler =
new ExpressionCompiler("users = [ new User('Darth', 'Vadar'), " +
"new User('Bobba', 'Feta') ]; [ users.get( 0 ), users.get( 1 ) ]");
List list = (List) executeExpression(compiler.compile(ctx),
new HashMap());
User user = (User) list.get(0);
assertEquals("Darth",
user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba",
user.getFirstName());
compiler = new ExpressionCompiler("users = [ new User('Darth', 'Vadar'), " +
"new User('Bobba', 'Feta') ]; [ users[0], users[1] ]");
list = (List) executeExpression(compiler.compile(ctx),
new HashMap());
user = (User) list.get(0);
assertEquals("Darth",
user.getFirstName());
user = (User) list.get(1);
assertEquals("Bobba",
user.getFirstName());
}
public void testSetSemantics() {
Bar bar = new Bar();
Foo foo = new Foo();
assertEquals("dog",
MVEL.getProperty("name",
bar));
assertEquals("dog",
MVEL.getProperty("name",
foo));
}
public void testMapBindingSemantics2() {
OptimizerFactory.setDefaultOptimizer("ASM");
Map<String, Object> outermap = new HashMap<String, Object>();
Map<String, Object> innermap = new HashMap<String, Object>();
innermap.put("test",
"foo");
outermap.put("innermap",
innermap);
executeSetExpression(compileSetExpression("innermap['test']"),
outermap,
"bar");
assertEquals("bar",
testCompiledSimple("innermap['test']",
outermap,
null));
}
public void testDynamicImports() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("java.util");
ExpressionCompiler compiler = new ExpressionCompiler("HashMap");
Serializable s = compiler.compile(ctx);
assertEquals(HashMap.class,
executeExpression(s));
compiler = new ExpressionCompiler("map = new HashMap(); map.size()");
s = compiler.compile(ctx);
assertEquals(0,
executeExpression(s,
new DefaultLocalVariableResolverFactory()));
}
public void testDynamicImports3() {
String expression = "import java.util.*; HashMap map = new HashMap(); map.size()";
ExpressionCompiler compiler = new ExpressionCompiler(expression);
Serializable s = compiler.compile();
assertEquals(0,
executeExpression(s,
new DefaultLocalVariableResolverFactory()));
assertEquals(0,
MVEL.eval(expression,
new HashMap()));
}
public void testDynamicImportsInList() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("[ new User('Bobba', 'Feta') ]");
List list = (List) executeExpression(compiler.compile(ctx));
User user = (User) list.get(0);
assertEquals("Bobba",
user.getFirstName());
}
public void testDynamicImportsInMap() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("[ 'bobba' : new User('Bobba', 'Feta') ]");
Map map = (Map) executeExpression(compiler.compile(ctx));
User user = (User) map.get("bobba");
assertEquals("Bobba",
user.getFirstName());
}
public void testDynamicImportsOnNestedExpressions() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("new Cheesery(\"bobbo\", new Cheese(\"cheddar\", 15))");
Cheesery p1 = new Cheesery("bobbo",
new Cheese("cheddar",
15));
Cheesery p2 = (Cheesery) executeExpression(compiler.compile(ctx),
new DefaultLocalVariableResolverFactory());
assertEquals(p1,
p2);
}
public void testDynamicImportsWithNullConstructorParam() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ExpressionCompiler compiler = new ExpressionCompiler("new Cheesery(\"bobbo\", null)");
Cheesery p1 = new Cheesery("bobbo",
null);
Cheesery p2 = (Cheesery) executeExpression(compiler.compile(ctx),
new DefaultLocalVariableResolverFactory());
assertEquals(p1,
p2);
}
public void testDynamicImportsWithIdentifierSameAsClassWithDiffCase() {
ParserContext ctx = new ParserContext();
ctx.addPackageImport("org.mvel2.tests.core.res");
ctx.setStrictTypeEnforcement(false);
ExpressionCompiler compiler = new ExpressionCompiler("bar.add(\"hello\")");
compiler.compile(ctx);
}
public void testTypedAssignment() {
assertEquals("foobar",
test("java.util.Map map = new java.util.HashMap(); map.put('conan', 'foobar'); map['conan'];"));
}
public void testFQCNwithStaticInList() {
assertEquals(Integer.MIN_VALUE,
test("list = [java.lang.Integer.MIN_VALUE]; list[0]"));
}
public void testPrecedenceOrder() {
assertTrue((Boolean) test("5 > 6 && 2 < 1 || 10 > 9"));
}
@SuppressWarnings({"unchecked"})
public void testDifferentImplSameCompile() {
Serializable compiled = compileExpression("a.funMap.hello");
Map testMap = new HashMap();
for (int i = 0; i < 100; i++) {
Base b = new Base();
b.funMap.put("hello",
"dog");
testMap.put("a",
b);
assertEquals("dog",
executeExpression(compiled,
testMap));
b = new Base();
b.funMap.put("hello",
"cat");
testMap.put("a",
b);
assertEquals("cat",
executeExpression(compiled,
testMap));
}
}
@SuppressWarnings({"unchecked"})
public void testInterfaceMethodCallWithSpace() {
Map map = new HashMap();
DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper();
map.put("drools",
helper);
Cheese cheese = new Cheese("stilton",
15);
map.put("cheese",
cheese);
executeExpression(compileExpression("drools.retract (cheese)"),
map);
assertSame(cheese,
helper.retracted.get(0));
}
@SuppressWarnings({"unchecked"})
public void testInterfaceMethodCallWithMacro() {
Map macros = new HashMap(1);
macros.put("retract",
new Macro() {
public String doMacro() {
return "drools.retract";
}
});
Map map = new HashMap();
DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper();
map.put("drools",
helper);
Cheese cheese = new Cheese("stilton",
15);
map.put("cheese",
cheese);
executeExpression(compileExpression(parseMacros("retract(cheese)",
macros)),
map);
assertSame(cheese,
helper.retracted.get(0));
}
public void testParsingStability1() {
assertEquals(true,
test("( order.number == 1 || order.number == ( 1+1) || order.number == $id )"));
}
public void testParsingStability2() {
ExpressionCompiler compiler =
new ExpressionCompiler("( dim.height == 1 || dim.height == ( 1+1) || dim.height == x )");
Map<String, Object> imports = new HashMap<String, Object>();
imports.put("java.awt.Dimension",
Dimension.class);
final ParserContext parserContext = new ParserContext(imports,
null,
"sourceFile");
parserContext.setStrictTypeEnforcement(false);
compiler.compile(parserContext);
}
public void testConcatWithLineBreaks() {
ExpressionCompiler parser = new ExpressionCompiler("\"foo\"+\n\"bar\"");
ParserContext ctx = new ParserContext();
ctx.setDebugSymbols(true);
ctx.setSourceFile("source.mv");
assertEquals("foobar",
executeExpression(parser.compile(ctx)));
}
/**
* Provided by: Alex Roytman
*/
public void testMethodResolutionWithNullParameter() {
Context ctx = new Context();
ctx.setBean(new Bean());
Map<String, Object> vars = new HashMap<String, Object>();
System.out.println("bean.today: " + eval("bean.today",
ctx,
vars));
System.out.println("formatDate(bean.today): " + eval("formatDate(bean.today)",
ctx,
vars));
//calling method with string param with null parameter works
System.out.println("formatString(bean.nullString): " + eval("formatString(bean.nullString)",
ctx,
vars));
System.out.println("bean.myDate = bean.nullDate: " + eval("bean.myDate = bean.nullDate; return bean.nullDate;",
ctx,
vars));
//calling method with Date param with null parameter fails
System.out.println("formatDate(bean.myDate): " + eval("formatDate(bean.myDate)",
ctx,
vars));
//same here
System.out.println(eval("formatDate(bean.nullDate)",
ctx,
vars));
}
/**
* Provided by: Phillipe Ombredanne
*/
public void testCompileParserContextShouldNotLoopIndefinitelyOnValidJavaExpression() {
String expr = " System.out.println( message );\n" +
"m.setMessage( \"Goodbye cruel world\" );\n" +
"System.out.println(m.getStatus());\n" +
"m.setStatus( Message.GOODBYE );\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Message",
Message.class);
context.addInput("System",
void.class);
context.addInput("message",
Object.class);
context.addInput("m",
Object.class);
compiler.compile(context);
}
public void testStaticNested() {
assertEquals(1,
eval("org.mvel2.tests.core.AbstractTest$Message.GOODBYE",
new HashMap()));
}
public void testStaticNestedWithImport() {
String expr = "Message.GOODBYE;\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Message",
Message.class);
assertEquals(1,
executeExpression(compiler.compile(context)));
}
public void testStaticNestedWithMethodCall() {
String expr = "item = new Item( \"Some Item\"); $msg.addItem( item ); return $msg";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Message",
Message.class);
context.addImport("Item",
Item.class);
// Serializable compiledExpression = compiler.compileShared(context);
Map vars = new HashMap();
vars.put("$msg",
new Message());
Message msg = (Message) executeExpression(compiler.compile(context),
vars);
Item item = (Item) msg.getItems().get(0);
assertEquals("Some Item",
item.getName());
}
public void testsequentialAccessorsThenMethodCall() {
String expr = "System.out.println(drools.workingMemory); " +
"drools.workingMemory.ruleBase.removeRule(\"org.drools.examples\", \"some rule\"); ";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(true);
context.addInput("drools",
KnowledgeHelper.class);
RuleBase ruleBase = new RuleBaseImpl();
WorkingMemory wm = new WorkingMemoryImpl(ruleBase);
KnowledgeHelper drools = new DefaultKnowledgeHelper(wm);
Map vars = new HashMap();
vars.put("drools",
drools);
executeExpression(compiler.compile(context),
vars);
}
/**
* Provided by: Aadi Deshpande
*/
public void testPropertyVerfierShoudldNotLoopIndefinately() {
String expr = "\t\tmodel.latestHeadlines = $list;\n"
+ "model.latestHeadlines.add( 0, (model.latestHeadlines[2]) );";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
compiler.setVerifying(true);
ParserContext pCtx = new ParserContext();
pCtx.addInput("$list",
List.class);
pCtx.addInput("model",
Model.class);
compiler.compile(pCtx);
}
public void testCompileWithNewInsideMethodCall() {
String expr = " p.name = \"goober\";\n" + " System.out.println(p.name);\n"
+ " drools.insert(new Address(\"Latona\"));\n";
ExpressionCompiler compiler = new ExpressionCompiler(expr);
ParserContext context = new ParserContext();
context.setStrictTypeEnforcement(false);
context.addImport("Person",
Person.class);
context.addImport("Address",
Address.class);
context.addInput("p",
Person.class);
context.addInput("drools",
Drools.class);
compiler.compile(context);
}
/**
* Submitted by: cleverpig
*/
public void testBug4() {
ClassA A = new ClassA();
ClassB B = new ClassB();
System.out.println(MVEL.getProperty("date",
A));
System.out.println(MVEL.getProperty("date",
B));
}
public void testIndexer() {
assertEquals("foobar",
testCompiledSimple("import java.util.LinkedHashMap; LinkedHashMap map = new LinkedHashMap();"
+ " map.put('a', 'foo'); map.put('b', 'bar'); s = ''; " +
"foreach (key : map.keySet()) { System.out.println(map[key]); s += map[key]; }; return s;",
createTestMap()));
}
public void testLateResolveOfClass() {
ExpressionCompiler compiler = new ExpressionCompiler("System.out.println(new Foo());");
ParserContext ctx = new ParserContext();
ctx.addImport(Foo.class);
compiler.removeParserContext();
System.out.println(executeExpression(compiler.compile(ctx)));
}
public void testClassAliasing() {
assertEquals("foobar",
test("Foo244 = String; new Foo244('foobar')"));
}
public void testRandomExpression1() {
assertEquals("HelloWorld",
test("if ((x15 = foo.bar) == foo.bar && x15 == foo.bar) { return 'HelloWorld'; } " +
"else { return 'GoodbyeWorld' } "));
}
public void testRandomExpression4() {
assertEquals(true,
test("result = org.mvel2.MVEL.eval('10 * 3'); result == (10 * 3);"));
}
public void testRandomExpression5() {
assertEquals(true,
test("FooClassRef = foo.getClass(); fooInst = new FooClassRef();" +
" name = org.mvel2.MVEL.eval('name', fooInst); return name == 'dog'"));
}
public void testRandomExpression6() {
assertEquals(500,
test("exprString = '250' + ' ' + '*' + ' ' + '2'; " +
"compiledExpr = org.mvel2.MVEL.compileExpression(exprString);"
+ " return org.mvel2.MVEL.executeExpression(compiledExpr);"));
}
public void testRandomExpression7() {
assertEquals("FOOBAR",
test("'foobar'.toUpperCase();"));
}
public void testRandomExpression8() {
assertEquals(true,
test("'someString'.intern(); 'someString'.hashCode() == 'someString'.hashCode();"));
}
public void testRandomExpression9() {
assertEquals(false,
test("_abc = 'someString'.hashCode(); _xyz = _abc + 1; _abc == _xyz"));
}
public void testRandomExpression10() {
assertEquals(false,
test("(_abc = (_xyz = 'someString'.hashCode()) + 1); _abc == _xyz"));
}
/**
* Submitted by: Guerry Semones
*/
private Map<Object, Object> outerMap;
private Map<Object, Object> innerMap;
public void testAddIntToMapWithMapSyntax() throws Throwable {
outerMap = new HashMap<Object, Object>();
innerMap = new HashMap<Object, Object>();
outerMap.put("innerMap",
innerMap);
// fails because mvel2 checks for 'tak' in the outerMap,
// rather than inside innerMap in outerMap
PropertyAccessor.set(outerMap,
"innerMap['foo']",
42);
// instead of here
assertEquals(42,
innerMap.get("foo"));
}
public void testUpdateIntInMapWithMapSyntax() throws Throwable {
outerMap = new HashMap<Object, Object>();
innerMap = new HashMap<Object, Object>();
outerMap.put("innerMap",
innerMap);
// fails because mvel2 checks for 'tak' in the outerMap,
// rather than inside innerMap in outerMap
innerMap.put("foo",
21);
PropertyAccessor.set(outerMap,
"innerMap['foo']",
42);
// instead of updating it here
assertEquals(42,
innerMap.get("foo"));
}
private HashMap<String, Object> context = new HashMap<String, Object>();
public void before() {
HashMap<String, Object> map = new HashMap<String, Object>();
MyBean bean = new MyBean();
bean.setVar(4);
map.put("bean",
bean);
context.put("map",
map);
}
public void testDeepProperty() {
before();
Object obj = executeExpression(compileExpression("map.bean.var"),
context);
assertEquals(4,
obj);
}
public void testDeepProperty2() {
before();
Object obj = executeExpression(compileExpression("map.bean.getVar()"),
context);
assertEquals(4,
obj);
}
public class MyBean {
int var;
public int getVar() {
return var;
}
public void setVar(int var) {
this.var = var;
}
}
public void testBooleanEvaluation() {
assertEquals(true,
test("true||false||false"));
}
public void testBooleanEvaluation2() {
assertEquals(true,
test("equalityCheck(1,1)||fun||ackbar"));
}
public void testStaticWithExplicitParam() {
PojoStatic pojo = new PojoStatic("10");
eval("org.mvel2.tests.core.res.AStatic.Process('10')",
pojo,
new HashMap());
}
public void testSimpleExpression() {
PojoStatic pojo = new PojoStatic("10");
eval("value!= null",
pojo,
new HashMap());
}
public void testStaticWithExpressionParam() {
PojoStatic pojo = new PojoStatic("10");
assertEquals("java.lang.String",
eval("org.mvel2.tests.core.res.AStatic.Process(value.getClass().getName().toString())",
pojo));
}
public void testStringIndex() {
assertEquals(true,
test("a = 'foobar'; a[4] == 'a'"));
}
public void testAssertKeyword() {
ExpressionCompiler compiler = new ExpressionCompiler("assert 1 == 2;");
Serializable s = compiler.compile();
try {
executeExpression(s);
}
catch (AssertionError e) {
return;
}
assertTrue(false);
}
public void testNullSafe() {
Foo foo = new Foo();
Map map = new HashMap();
map.put("foo",
foo);
String expression = "foo.?bar.name == null";
Serializable compiled = compileExpression(expression);
OptimizerFactory.setDefaultOptimizer("reflective");
assertEquals(false,
executeExpression(compiled,
map));
foo.setBar(null);
assertEquals(true,
executeExpression(compiled,
map)); // execute a second time (to search for optimizer problems)
OptimizerFactory.setDefaultOptimizer("ASM");
compiled = compileExpression(expression);
foo.setBar(new Bar());
assertEquals(false,
executeExpression(compiled,
map));
foo.setBar(null);
assertEquals(true,
executeExpression(compiled,
map)); // execute a second time (to search for optimizer problems)
assertEquals(true,
eval(expression,
map));
}
public void testMethodInvocationWithCollectionElement() {
context = new HashMap();
context.put("pojo",
new POJO());
context.put("number",
"1192800637980");
Object result = MVEL.eval("pojo.function(pojo.dates[0].time)",
context);
assertEquals(String.valueOf(((POJO) context.get("pojo")).getDates().iterator().next().getTime()),
result);
}
public class POJO {
private Set<Date> dates = new HashSet<Date>();
public POJO() {
dates.add(new Date());
}
public Set<Date> getDates() {
return dates;
}
public void setDates(Set<Date> dates) {
this.dates = dates;
}
public String function(long num) {
return String.valueOf(num);
}
}
public void testNestedMethod1() {
Vector vectorA = new Vector();
Vector vectorB = new Vector();
vectorA.add("Foo244");
Map map = new HashMap();
map.put("vecA",
vectorA);
map.put("vecB",
vectorB);
testCompiledSimple("vecB.add(vecA.remove(0)); vecA.add('Foo244');",
null,
map);
assertEquals("Foo244",
vectorB.get(0));
}
public void testDynamicImports2() {
assertEquals(BufferedReader.class,
test("import java.io.*; BufferedReader"));
}
public void testUseOfVarKeyword() {
assertEquals("FOO_BAR",
test("var barfoo = 'FOO_BAR'; return barfoo;"));
}
public void testAssignment5() {
assertEquals(15,
test("x = (10) + (5); x"));
}
public void testSetExpressions1() {
Map<String, Object> myMap = new HashMap<String, Object>();
final Serializable fooExpr = compileSetExpression("foo");
executeSetExpression(fooExpr,
myMap,
"blah");
assertEquals("blah",
myMap.get("foo"));
executeSetExpression(fooExpr,
myMap,
"baz");
assertEquals("baz",
myMap.get("foo"));
}
public void testDuplicateVariableDeclaration() {
ExpressionCompiler compiler = new ExpressionCompiler("String x = \"abc\"; Integer x = new Integer( 10 );");
ParserContext context = new ParserContext();
try {
compiler.compile(context);
fail("Compilation must fail with duplicate variable declaration exception.");
}
catch (RuntimeException ce) {
// success
}
}
public void testFullyQualifiedTypeAndCast() {
assertEquals(1,
test("java.lang.Integer number = (java.lang.Integer) '1';"));
}
public void testThreadSafetyInterpreter1() {
//First evaluation
System.out.println("First evaluation: " + MVEL.eval("true"));
new Thread(new Runnable() {
public void run() {
// Second evaluation - this succeeds only if the first evaluation is not commented out
System.out.println("Second evaluation: " + MVEL.eval("true"));
}
}).start();
}
public void testArrayList() throws SecurityException,
NoSuchMethodException {
Collection<String> collection = new ArrayList<String>();
collection.add("I CAN HAS CHEEZBURGER");
assertEquals(collection.size(),
MVEL.eval("size()",
collection));
}
public void testUnmodifiableCollection() throws SecurityException,
NoSuchMethodException {
Collection<String> collection = new ArrayList<String>();
collection.add("I CAN HAS CHEEZBURGER");
collection = unmodifiableCollection(collection);
assertEquals(collection.size(),
MVEL.eval("size()",
collection));
}
public void testSingleton() throws SecurityException,
NoSuchMethodException {
Collection<String> collection = Collections.singleton("I CAN HAS CHEEZBURGER");
assertEquals(collection.size(),
MVEL.eval("size()",
collection));
}
public static class TestClass2 {
public void addEqualAuthorizationConstraint(Foo leg,
Bar ctrlClass,
Integer authorization) {
}
}
public void testJIRA93() {
Map testMap = createTestMap();
testMap.put("testClass2",
new TestClass2());
Serializable s = compileExpression("testClass2.addEqualAuthorizationConstraint(foo, foo.bar, 5)");
for (int i = 0; i < 5; i++) {
executeExpression(s,
testMap);
}
}
public void testJIRA96() {
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.addInput("fooString",
String[].class);
ExpressionCompiler compiler = new ExpressionCompiler("fooString[0].toUpperCase()");
compiler.compile(ctx);
}
public void testStringToArrayCast() {
Object o = test("(char[]) 'abcd'");
assertTrue(o instanceof char[]);
}
public void testStringToArrayCast2() {
assertTrue((Boolean) test("_xyxy = (char[]) 'abcd'; _xyxy[0] == 'a'"));
}
public void testStaticallyTypedArrayVar() {
String ex = "char[] _c___ = new char[10]; _c___ instanceof char[]";
assertTrue((Boolean) test(ex));
}
public void testParserErrorHandling() {
final ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler("a[");
try {
compiler.compile(ctx);
}
catch (Exception e) {
return;
}
assertTrue(false);
}
public void testJIRA100() {
assertEquals(new BigDecimal(20),
test("java.math.BigDecimal axx = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal bxx = " +
"new java.math.BigDecimal( 10.0 ); java.math.BigDecimal cxx = axx + bxx; return cxx; "));
}
public void testJIRA100b() {
Serializable s = MVEL.compileExpression("java.math.BigDecimal axx = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal bxx = " +
"new java.math.BigDecimal( 10.0 ); java.math.BigDecimal cxx = axx + bxx; return cxx; ");
assertEquals(new BigDecimal(20), executeExpression(s, new HashMap()));
}
public void testAssignToBean() {
Person person = new Person();
MVEL.eval("this.name = 'foo'",
person);
assertEquals("foo",
person.getName());
executeExpression(compileExpression("this.name = 'bar'"),
person);
assertEquals("bar",
person.getName());
}
public void testMapAssignmentNestedExpression() {
Map map = new HashMap();
map.put("map",
new HashMap());
String ex = "map[java.lang.Integer.MAX_VALUE] = 'bar'; map[java.lang.Integer.MAX_VALUE];";
assertEquals("bar",
executeExpression(compileExpression(ex),
map));
assertEquals("bar",
MVEL.eval(ex,
map));
}
public void testMapAssignmentNestedExpression2() {
Map map = new HashMap();
map.put("x",
"bar");
map.put("map",
new HashMap());
String ex = "map[x] = 'foo'; map['bar'];";
assertEquals("foo",
executeExpression(compileExpression(ex),
map));
assertEquals("foo",
MVEL.eval(ex,
map));
}
/**
* MVEL-103
*/
public static class MvelContext {
public boolean singleCalled;
public boolean arrayCalled;
public String[] regkeys;
public void methodForTest(String string) {
System.out.println("sigle param method called!");
singleCalled = true;
}
public void methodForTest(String[] strings) {
System.out.println("array param method called!");
arrayCalled = true;
}
public void setRegkeys(String[] regkeys) {
this.regkeys = regkeys;
}
public void setRegkeys(String regkey) {
this.regkeys = regkey.split(",");
}
}
public void testMethodResolutionOrder() {
MvelContext mvelContext = new MvelContext();
MVEL.eval("methodForTest({'1','2'})",
mvelContext);
MVEL.eval("methodForTest('1')",
mvelContext);
assertTrue(mvelContext.arrayCalled && mvelContext.singleCalled);
}
public void testCustomPropertyHandler() {
MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true;
PropertyHandlerFactory.registerPropertyHandler(SampleBean.class,
new SampleBeanAccessor());
assertEquals("dog",
test("foo.sampleBean.bar.name"));
PropertyHandlerFactory.unregisterPropertyHandler(SampleBean.class);
MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = false;
}
public void testSetAccessorOverloadedEqualsStrictMode() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("foo",
Foo.class);
try {
CompiledExpression expr = new ExpressionCompiler("foo.bar = 0").compile(ctx);
}
catch (CompileException e) {
// should fail.
e.printStackTrace();
return;
}
assertTrue(false);
}
private static final KnowledgeHelperFixer fixer = new KnowledgeHelperFixer();
public void testAdd__Handle__Simple() {
String result = fixer.fix("update(myObject );");
assertEqualsIgnoreWhitespace("drools.update(myObject );",
result);
result = fixer.fix("update ( myObject );");
assertEqualsIgnoreWhitespace("drools.update( myObject );",
result);
}
public void testAdd__Handle__withNewLines() {
final String result = fixer.fix("\n\t\n\tupdate( myObject );");
assertEqualsIgnoreWhitespace("\n\t\n\tdrools.update( myObject );",
result);
}
public void testAdd__Handle__rComplex() {
String result = fixer.fix("something update( myObject); other");
assertEqualsIgnoreWhitespace("something drools.update( myObject); other",
result);
result = fixer.fix("something update ( myObject );");
assertEqualsIgnoreWhitespace("something drools.update( myObject );",
result);
result = fixer.fix(" update( myObject ); x");
assertEqualsIgnoreWhitespace(" drools.update( myObject ); x",
result);
//should not touch, as it is not a stand alone word
result = fixer.fix("xxupdate(myObject ) x");
assertEqualsIgnoreWhitespace("xxupdate(myObject ) x",
result);
}
public void testMultipleMatches() {
String result = fixer.fix("update(myObject); update(myObject );");
assertEqualsIgnoreWhitespace("drools.update(myObject); drools.update(myObject );",
result);
result = fixer.fix("xxx update(myObject ); update( myObject ); update( yourObject ); yyy");
assertEqualsIgnoreWhitespace("xxx drools.update(myObject ); " +
"drools.update( myObject ); drools.update( yourObject ); yyy",
result);
}
public void testAssert1() {
final String raw = "insert( foo );";
final String result = "drools.insert( foo );";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testAssert2() {
final String raw = "some code; insert( new String(\"foo\") );\n More();";
final String result = "some code; drools.insert( new String(\"foo\") );\n More();";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testAssertLogical() {
final String raw = "some code; insertLogical(new String(\"foo\"));\n More();";
final String result = "some code; drools.insertLogical(new String(\"foo\"));\n More();";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testModifyRetractModifyInsert() {
final String raw = "some code; insert( bar ); modifyRetract( foo );\n More();" +
" retract( bar ); modifyInsert( foo );";
final String result = "some code; drools.insert( bar ); drools.modifyRetract( foo );\n More();" +
" drools.retract( bar ); drools.modifyInsert( foo );";
assertEqualsIgnoreWhitespace(result,
fixer.fix(raw));
}
public void testAllActionsMushedTogether() {
String result = fixer.fix("insert(myObject ); update(ourObject);\t retract(herObject);");
assertEqualsIgnoreWhitespace("drools.insert(myObject ); drools.update(ourObject);\t drools.retract(herObject);",
result);
result = fixer.fix("insert( myObject ); update(ourObject);\t retract(herObject );\n" +
"insert( myObject ); update(ourObject);\t retract( herObject );");
assertEqualsIgnoreWhitespace("drools.insert( myObject ); drools.update(ourObject);\t " +
"drools.retract(herObject );\ndrools.insert( myObject ); drools.update(ourObject);\t" +
" drools.retract( herObject );",
result);
}
public void testLeaveLargeAlone() {
final String original = "yeah yeah yeah minsert( xxx ) this is a long() thing Person" +
" (name=='drools') modify a thing";
final String result = fixer.fix(original);
assertEqualsIgnoreWhitespace(original,
result);
}
public void testWithNull() {
final String original = null;
final String result = fixer.fix(original);
assertEqualsIgnoreWhitespace(original,
result);
}
public void testLeaveAssertAlone() {
final String original = "drools.insert(foo)";
assertEqualsIgnoreWhitespace(original,
fixer.fix(original));
}
public void testLeaveAssertLogicalAlone() {
final String original = "drools.insertLogical(foo)";
assertEqualsIgnoreWhitespace(original,
fixer.fix(original));
}
public void testWackyAssert() {
final String raw = "System.out.println($person1.getName() + \" and \" + $person2.getName() " +
"+\" are sisters\");\n" + "insert($person1.getName(\"foo\") + \" and \" + $person2.getName() " +
"+\" are sisters\"); yeah();";
final String expected = "System.out.println($person1.getName() + \" and \" + $person2.getName()" +
" +\" are sisters\");\n" + "drools.insert($person1.getName(\"foo\") + \" and \" + $person2.getName() " +
"+\" are sisters\"); yeah();";
assertEqualsIgnoreWhitespace(expected,
fixer.fix(raw));
}
public void testMoreAssertCraziness() {
final String raw = "foobar(); (insert(new String(\"blah\").get()); bangBangYudoHono();)";
assertEqualsIgnoreWhitespace("foobar(); (drools.insert(new String(\"blah\").get()); bangBangYudoHono();)",
fixer.fix(raw));
}
public void testRetract() {
final String raw = "System.out.println(\"some text\");retract(object);";
assertEqualsIgnoreWhitespace("System.out.println(\"some text\");drools.retract(object);",
fixer.fix(raw));
}
private void assertEqualsIgnoreWhitespace(final String expected,
final String actual) {
if (expected == null || actual == null) {
assertEquals(expected,
actual);
return;
}
final String cleanExpected = expected.replaceAll("\\s+",
"");
final String cleanActual = actual.replaceAll("\\s+",
"");
assertEquals(cleanExpected,
cleanActual);
}
public void testIncrementInBooleanStatement() {
assertEquals(true,
test("hour++ < 61 && hour == 61"));
}
public void testIncrementInBooleanStatement2() {
assertEquals(true,
test("++hour == 61"));
}
public void testStaticallyTypedLong() {
assertEquals(10l,
test("10l"));
}
public void testNakedMethodCall() {
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
OptimizerFactory.setDefaultOptimizer("ASM");
Serializable c = compileExpression("tm = System.currentTimeMillis");
assertTrue(((Long) executeExpression(c,
new HashMap())) > 0);
OptimizerFactory.setDefaultOptimizer("reflective");
assertTrue(((Long) executeExpression(c,
new HashMap())) > 0);
Map map = new HashMap();
map.put("foo",
new Foo());
c = compileExpression("foo.happy");
assertEquals("happyBar",
executeExpression(c,
map));
OptimizerFactory.setDefaultOptimizer("ASM");
c = compileExpression("foo.happy");
assertEquals("happyBar",
executeExpression(c,
map));
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = false;
}
public void testDecl() {
assertEquals((char) 100,
test("char chr; chr = 100; chr"));
}
public void testInlineUnion() {
assertEquals("test",
test("{'foo', 'test'}[1]"));
}
public static double minim(double[] tab) {
double min = Float.MAX_VALUE;
for (int i = 0; i < tab.length; i++) {
if (min > tab[i]) {
min = tab[i];
}
}
return min;
}
public void testJIRA113() {
assertEquals(true,
test("org.mvel2.tests.core.CoreConfidenceTests.minim( new double[] {456.2, 2.3} ) == 2.3"));
}
public void testChainedMethodCallsWithParams() {
assertEquals(true,
test("foo.toUC(\"abcd\").equals(\"ABCD\")"));
}
public void testIsUsedInIf() {
assertEquals(true,
test("c = 'str'; if (c is String) { true; } else { false; } "));
}
public void testJIRA122() {
Serializable s = compileExpression("System.out.println('>'+java.lang.Character.toLowerCase(name.charAt(0))); java.lang.Character.toLowerCase(name.charAt(0)) == 'a'");
OptimizerFactory.setDefaultOptimizer("ASM");
Map map = new HashMap();
map.put("name",
"Adam");
assertEquals(true,
executeExpression(s,
map));
assertEquals(true,
executeExpression(s,
map));
}
public void testJIRA122b() {
Serializable s = compileExpression("System.out.println('>'+java.lang.Character.toLowerCase(name.charAt(0))); java.lang.Character.toLowerCase(name.charAt(0)) == 'a'");
OptimizerFactory.setDefaultOptimizer("reflective");
Map map = new HashMap();
map.put("name",
"Adam");
assertEquals(true,
executeExpression(s,
map));
assertEquals(true,
executeExpression(s,
map));
}
public void testJIRA103() {
MvelContext mvelContext = new MvelContext();
MVEL.setProperty(mvelContext,
"regkeys",
"s");
}
public void testJIRA103b() {
MvelContext mvelContext = new MvelContext();
Map map = new HashMap();
map.put("ctx",
mvelContext);
Serializable c = compileExpression("ctx.regkeys = 'foo'");
executeExpression(c,
map);
executeExpression(c,
map);
}
public void testMethodCaching() {
MVEL.eval("for (pet: getPets()) pet.run();",
new PetStore());
}
public static class PetStore {
public List getPets() {
List pets = new ArrayList();
pets.add(new Dog());
pets.add(new Cat());
return pets;
}
}
public static class Pet {
public void run() {
}
}
public static class Dog extends Pet {
@Override
public void run() {
System.out.println("dog is running");
}
}
public static class Cat extends Pet {
@Override
public void run() {
System.out.println("cat is running");
}
}
public void testSetExpressions2() {
Foo foo = new Foo();
Collection col = new ArrayList();
final Serializable fooExpr = compileSetExpression("collectionTest");
executeSetExpression(fooExpr,
foo,
col);
assertEquals(col,
foo.getCollectionTest());
}
public class Fruit {
public class Apple {
}
}
public void testInnerClassReference() {
assertEquals(Fruit.Apple.class,
test("import " + CoreConfidenceTests.class.getName() + "; CoreConfidenceTests.Fruit.Apple"));
}
public void testEdson() {
assertEquals("foo",
test("list = new java.util.ArrayList(); list.add(new String('foo')); list[0]"));
}
public void testEnumSupport() {
MyInterface myInterface = new MyClass();
myInterface.setType(MyInterface.MY_ENUM.TWO,
true);
boolean isType = MVEL.eval("isType(org.mvel2.tests.core.res.MyInterface$MY_ENUM.ONE)",
myInterface,
Boolean.class);
System.out.println(isType);
}
public void testOperatorPrecedenceOrder() {
Serializable compiled =
compileExpression("bean1.successful && bean2.failed || bean1.failed && bean2.successful");
Map context = new HashMap();
BeanB bean1 = new BeanB(true);
BeanB bean2 = new BeanB(false);
context.put("bean1",
bean1);
context.put("bean2",
bean2);
System.out.println("interpreted: "
+ MVEL.eval("bean1.successful && bean2.failed || bean1.failed && bean2.successful",
context));
assertEquals(bean1.isSuccessful() && bean2.isFailed() || bean1.isFailed() && bean2.isSuccessful(),
(boolean) executeExpression(compiled,
context,
Boolean.class));
}
public static class BeanB {
private boolean successful;
public BeanB(boolean successful) {
this.successful = successful;
}
public boolean isSuccessful() {
return successful;
}
public boolean isFailed() {
return !successful;
}
}
public void testJIRA139() {
ParserContext ctx = new ParserContext();
ctx.addImport("ReflectionUtil",
ReflectionUtil.class);
Serializable s = compileExpression("ReflectionUtil.getGetter('foo')",
ctx);
assertEquals(ReflectionUtil.getGetter("foo"),
executeExpression(s));
}
public void testJIRA140() {
ParserContext ctx = new ParserContext();
Serializable s = compileExpression("import org.mvel2.tests.core.res.*;"
+ "cols = new Column[] { new Column('name', 20), new Column('age', 2) };"
+ "grid = new Grid(new Model(cols));",
ctx);
Grid g = (Grid) executeExpression(s,
new HashMap());
assertEquals(g.getModel().getColumns()[0].getName(),
"name");
assertEquals(g.getModel().getColumns()[0].getLength(),
20);
assertEquals(g.getModel().getColumns()[1].getName(),
"age");
assertEquals(g.getModel().getColumns()[1].getLength(),
2);
}
public void testVerifierWithIndexedProperties() {
ParserContext ctx = new ParserContext();
ctx.setStrictTypeEnforcement(true);
ctx.addInput("base",
Base.class);
Serializable s = compileExpression("base.fooMap['foo'].setName('coffee')",
ctx);
Map vars = new HashMap();
vars.put("base",
new Base());
executeExpression(s,
vars);
assertEquals("coffee",
((Base) vars.get("base")).fooMap.get("foo").getName());
}
public void testEmpty() {
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
Serializable s = compileExpression("list = new java.util.ArrayList(); list == empty",
ctx);
Map vars = new HashMap();
Boolean x = (Boolean) executeExpression(s,
vars);
assertNotNull(x);
assertTrue(x.booleanValue());
}
public void testMapsAndLists() {
OptimizerFactory.setDefaultOptimizer("ASM");
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addImport(HashMap.class);
ctx.addImport(ArrayList.class);
ctx.addInput("list",
List.class);
String expression = "m = new HashMap();\n" + "l = new ArrayList();\n" + "l.add(\"first\");\n" +
"m.put(\"content\", l);\n" + "list.add(((ArrayList)m[\"content\"])[0]);";
Serializable s = compileExpression(expression,
ctx);
Map vars = new HashMap();
List list = new ArrayList();
vars.put("list",
list);
Boolean result = (Boolean) executeExpression(s,
vars);
assertNotNull(result);
assertTrue(result);
assertEquals(1,
list.size());
assertEquals("first",
list.get(0));
}
public void testMapsAndLists2() {
OptimizerFactory.setDefaultOptimizer("reflective");
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addImport(HashMap.class);
ctx.addImport(ArrayList.class);
ctx.addInput("list",
List.class);
String expression = "m = new HashMap();\n" + "l = new ArrayList();\n" + "l.add(\"first\");\n" +
"m.put(\"content\", l);\n" + "list.add(((ArrayList)m[\"content\"])[0]);";
Serializable s = compileExpression(expression,
ctx);
Map vars = new HashMap();
List list = new ArrayList();
vars.put("list",
list);
Boolean result = (Boolean) executeExpression(s,
vars);
assertNotNull(result);
assertTrue(result);
assertEquals(1,
list.size());
assertEquals("first",
list.get(0));
}
public void testReturnBoolean() {
String ex = "list = new java.util.ArrayList(); return list != null";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
Serializable s = compileExpression(ex,
ctx);
assertEquals(true,
executeExpression(s,
new HashMap()));
}
public void testComaProblemStrikesBack() {
String ex = "a.explanation = \"There is a coma, in here\"";
ParserContext ctx = new ParserContext();
ExpressionCompiler compiler = new ExpressionCompiler(ex);
Serializable s = compiler.compile(ctx);
Base a = new Base();
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("a",
a);
executeExpression(s,
variables);
assertEquals("There is a coma, in here",
a.data);
}
public static interface Services {
public final static String A_CONST = "Hello World";
public void log(String text);
}
public void testStringConcatenation() {
// debugging MVEL code, it seems that MVEL 'thinks' that the result of the expression:
// "Drop +5%: "+$sb+" avg: $"+$av+" price: $"+$pr
// is a double, and as so, he looks for a method:
// Services.log( double );
// but finds only:
// Services.log( String );
// raising the error.
String ex = "services.log((String) \"Drop +5%: \"+$sb+\" avg: $\"+$av+\" price: $\"+$pr );";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("$sb",
String.class);
ctx.addInput("$av",
double.class);
ctx.addInput("$pr",
double.class);
ctx.addInput("services",
Services.class);
try {
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.compile(ctx);
}
catch (Throwable e) {
e.printStackTrace();
fail("Should not raise exception: " + e.getMessage());
}
}
public void testStringConcatenation2() {
String ex = "services.log( $cheese + \" some string \" );";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("$cheese",
Cheese.class);
ctx.addInput("services",
Services.class);
try {
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.compile(ctx);
}
catch (Throwable e) {
e.printStackTrace();
fail("Should not raise exception: " + e.getMessage());
}
}
public void testStringConcatenation3() {
// BUG: return type of the string concatenation is inferred as double instead of String
String ex = "services.log($av + \"Drop +5%: \"+$sb+\" avg: $\"+percent($av)+\" price: $\"+$pr );";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.setStrictTypeEnforcement(true);
ctx.addInput("$sb",
String.class);
ctx.addInput("$av",
double.class);
ctx.addInput("$pr",
double.class);
ctx.addInput("services",
Services.class);
ctx.addImport("percent", MVEL.getStaticMethod(String.class, "valueOf", new Class[]{double.class}));
try {
Serializable compiledExpression = MVEL.compileExpression(ex, ctx);
Services services = new Services() {
public void log(String text) {
}
};
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("services", services);
vars.put("$sb", "RHT");
vars.put("$av", 15.0);
vars.put("$pr", 10.0);
MVEL.executeExpression(compiledExpression, vars);
}
catch (Throwable e) {
e.printStackTrace();
fail("Should not raise exception: " + e.getMessage());
}
}
public void testMapsWithVariableAsKey() {
String ex = "aMap[aKey] == 'aValue'";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(false);
ExpressionCompiler compiler = new ExpressionCompiler(ex);
compiler.setVerifyOnly(true);
compiler.compile(ctx);
Set<String> requiredInputs = compiler.getParserContextState().getInputs().keySet();
assertTrue(requiredInputs.contains("aMap"));
assertTrue(requiredInputs.contains("aKey"));
}
public static void testProjectionUsingThis() {
Set records = new HashSet();
for (int i = 0; i < 53; i++) {
Bean2 record = new Bean2(i);
records.add(record);
}
Object result = MVEL.eval("(_prop in this)",
records);
System.out.println("result: " + result);
}
public static final class Bean2 {
public final int _prop;
public Bean2(int prop_) {
_prop = prop_;
}
public int getProp() {
return _prop;
}
public String toString() {
return Integer.toString(_prop);
}
}
public void testUnaryOpNegation1() {
assertEquals(false,
test("!new Boolean(true)"));
}
public void testUnaryOpNegation2() {
assertEquals(true,
test("!isdef _foozy_"));
}
public class Az {
public void foo(String s) {
}
}
public class Bz extends Az {
}
public void testJIRA151() {
OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE);
Bz b = new Bz();
ParserContext context = new ParserContext();
Object expression = MVEL.compileExpression("a.foo(value)",
context);
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("a",
b);
variables.put("value",
123);
for (int i = 0; i < 100; i++) {
System.out.println("i: " + i);
System.out.flush();
executeExpression(expression,
variables);
}
}
public void testJIRA151b() {
OptimizerFactory.setDefaultOptimizer("ASM");
Bz b = new Bz();
ParserContext context = new ParserContext();
Object expression = MVEL.compileExpression("a.foo(value)",
context);
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("a",
b);
variables.put("value",
123);
for (int i = 0; i < 100; i++) {
System.out.println("i: " + i);
System.out.flush();
executeExpression(expression,
variables);
}
}
public void testJIRA153() {
assertEquals(false,
MVEL.eval("!(true)"));
assertEquals(false,
executeExpression(MVEL.compileExpression("!(true)")));
}
public void testJIRA154() {
Map m = createTestMap();
m.put("returnTrue",
MVEL.getStaticMethod(CoreConfidenceTests.class,
"returnTrue",
new Class[0]));
assertEquals(false,
MVEL.eval("!returnTrue()",
m));
}
public void testJIRA154b() {
ParserContext pctx = new ParserContext();
pctx.addImport("returnTrue",
MVEL.getStaticMethod(CoreConfidenceTests.class,
"returnTrue",
new Class[0]));
assertEquals(false,
executeExpression(MVEL.compileExpression("!(returnTrue())",
pctx)));
}
public void testJIRA155() {
ParserContext pctx = new ParserContext();
pctx.addImport("returnTrue",
MVEL.getStaticMethod(CoreConfidenceTests.class,
"returnTrue",
new Class[0]));
assertEquals(true,
executeExpression(MVEL.compileExpression("!true || returnTrue()",
pctx)));
}
public void testJIRA155b() {
ParserContext pctx = new ParserContext();
pctx.addImport("returnTrue",
MVEL.getStaticMethod(CoreConfidenceTests.class,
"returnTrue",
new Class[0]));
assertEquals(true,
executeExpression(MVEL.compileExpression("!(!true || !returnTrue())",
pctx)));
}
public void testJIRA156() throws Throwable {
ClassProvider provider = new ClassProvider();
provider.getPrivate().foo();
PublicClass.class.getMethod("foo").invoke(provider.getPrivate());
String script = "provider.getPrivate().foo()";
HashMap<String, Object> vars = new HashMap<String, Object>();
vars.put("provider",
provider);
MVEL.eval(script,
vars);
}
public void testJIRA156b() throws Throwable {
ClassProvider provider = new ClassProvider();
provider.getPrivate().foo();
PublicClass.class.getMethod("foo").invoke(provider.getPrivate());
String script = "provider.getPrivate().foo()";
Serializable s = MVEL.compileExpression(script);
HashMap<String, Object> vars = new HashMap<String, Object>();
vars.put("provider",
provider);
OptimizerFactory.setDefaultOptimizer("reflective");
executeExpression(s,
vars);
OptimizerFactory.setDefaultOptimizer("ASM");
executeExpression(s,
vars);
}
public void testJIRA156c() throws Throwable {
ClassProvider provider = new ClassProvider();
provider.getPublic().foo();
PublicClass.class.getMethod("foo").invoke(provider.getPublic());
String script = "provider.getPublic().foo()";
Serializable s = MVEL.compileExpression(script);
HashMap<String, Object> vars = new HashMap<String, Object>();
vars.put("provider",
provider);
MVEL.eval(script,
vars);
OptimizerFactory.setDefaultOptimizer("reflective");
executeExpression(s,
vars);
OptimizerFactory.setDefaultOptimizer("ASM");
executeExpression(s,
vars);
}
public static boolean returnTrue() {
return true;
}
public static class TestHelper {
public static void method(int id,
Object[] arr) {
System.out.println(id + " -> " + arr.length);
}
public static void method(Object obj1, Object obj2) {
System.out.println(obj1 + "-> " + obj2);
}
public static Calendar minDate() {
return Calendar.getInstance();
}
public static Calendar maxDate() {
return Calendar.getInstance();
}
}
public static class Fooz {
public Fooz(String id) {
}
}
public void testArray() {
String ex = " TestHelper.method(1, new String[]{\"a\", \"b\"});\n"
+ " TestHelper.method(2, new String[]{new String(\"a\"), new String(\"b\")});\n"
+ " TestHelper.method(3, new Fooz[]{new Fooz(\"a\"), new Fooz(\"b\")});";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addImport(TestHelper.class);
ctx.addImport(Fooz.class);
ExpressionCompiler compiler = new ExpressionCompiler(ex);
OptimizerFactory.setDefaultOptimizer("ASM");
CompiledExpression expr = compiler.compile(ctx);
executeExpression(expr);
OptimizerFactory.setDefaultOptimizer("reflective");
expr = compiler.compile(ctx);
executeExpression(expr);
}
public void testArray2() {
String ex = " TestHelper.method(1, {\"a\", \"b\"});\n"
+ " TestHelper.method(2, {new String(\"a\"), new String(\"b\")});\n"
+ " TestHelper.method(3, {new Fooz(\"a\"), new Fooz(\"b\")});";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addImport(TestHelper.class);
ctx.addImport(Fooz.class);
ExpressionCompiler compiler = new ExpressionCompiler(ex);
OptimizerFactory.setDefaultOptimizer("ASM");
CompiledExpression expr = compiler.compile(ctx);
executeExpression(expr);
OptimizerFactory.setDefaultOptimizer("reflective");
expr = compiler.compile(ctx);
executeExpression(expr);
}
public void testJIRA166() {
Object v = MVEL.eval("import java.util.regex.Matcher; import java.util.regex.Pattern;"
+ " if (Pattern.compile(\"hoge\").matcher(\"hogehogehoge\").find()) { 'foo' } else { 'bar' }",
new HashMap());
assertEquals("foo",
v);
}
public static class Beano {
public String getProperty1() {
return null;
}
public boolean isProperty2() {
return true;
}
public boolean isProperty3() {
return false;
}
}
public void testJIRA167() {
Map context = new HashMap();
context.put("bean",
new Beano());
MVEL.eval("bean.property1==null?bean.isProperty2():bean.isProperty3()",
context);
}
public void testJIRA168() {
boolean before = MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL;
try {
Map<String, Object> st = new HashMap<String, Object>();
st.put("__fact__", new ArrayList());
st.put("__expected__", 0);
String expressionNaked = "__fact__.size == __expected__";
String expressionNonNaked = "__fact__.size() == __expected__";
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
// the following works fine
ParserContext ctx = new ParserContext();
for (Map.Entry<String, Object> entry : st.entrySet()) {
ctx.addInput(entry.getKey(),
entry.getValue().getClass());
}
CompiledExpression expr = new ExpressionCompiler(expressionNaked).compile(ctx);
Boolean result = (Boolean) executeExpression(expr,
st);
assertTrue(result);
// the following works fine
result = (Boolean) MVEL.eval(expressionNonNaked, st);
assertTrue(result);
// the following fails
result = (Boolean) MVEL.eval(expressionNaked, st);
assertTrue(result);
}
finally {
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = before;
}
}
public void testJIRA170() {
OptimizerFactory.setDefaultOptimizer("reflective");
List<Integer> staticDispatch = Arrays.asList(2, 1, 0);
List<Integer> multimethodDispatch = Arrays.asList(3, 2, 1);
// invokeJIRA170("Dynamic", ctxJIRA170(false, false), varsJIRA170(), multimethodDispatch);
// invokeJIRA170("Strict", ctxJIRA170(true, false), varsJIRA170(), multimethodDispatch);
invokeJIRA170("Strong", ctxJIRA170(false, true), varsJIRA170(), staticDispatch);
}
public void testJIRA170b() {
OptimizerFactory.setDefaultOptimizer("ASM");
List<Integer> staticDispatch = Arrays.asList(2, 1, 0);
List<Integer> multimethodDispatch = Arrays.asList(3, 2, 1);
// invokeJIRA170("Dynamic", ctxJIRA170(false, false), varsJIRA170(), multimethodDispatch);
// invokeJIRA170("Strict", ctxJIRA170(true, false), varsJIRA170(), multimethodDispatch);
invokeJIRA170("Strong", ctxJIRA170(false, true), varsJIRA170(), staticDispatch);
}
public void invokeJIRA170(String name, ParserContext pctx, Map<String, ?> vars, Collection<Integer> expected) {
Serializable expression = MVEL.compileExpression("x.remove((Object) y); x ", pctx);
Object result = executeExpression(expression, vars);
assertTrue(String.format("%s Expected %s, Got %s", name, expected, result), expected.equals(result));
result = executeExpression(expression, vars);
assertTrue(String.format("%s Expected %s, Got %s", name, expected, result), expected.equals(result));
}
private Map<String, ?> varsJIRA170() {
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("x", new ArrayList<Integer>(Arrays.asList(3, 2, 1, 0)));
vars.put("y", 3);
return vars;
}
private ParserContext ctxJIRA170(boolean strictTypeEnforcement, boolean strongTyping) {
ParserContext ctx = new ParserContext();
// ctx.setStrictTypeEnforcement(strictTypeEnforcement);
ctx.setStrongTyping(strongTyping);
ctx.addInput("x", Collection.class, new Class[]{Integer.class});
ctx.addInput("y", Integer.class);
return ctx;
}
public static class JIRA167Step {
public String getParent() {
return null;
}
}
public static class JIRA167Node {
public boolean isServer() {
return true;
}
}
public void testJIRA167b() {
Map context = new HashMap();
context.put("current", new JIRA167Step());
context.put("node", new JIRA167Node());
MVEL.eval("current.parent==null?node.isServer():(node==current.parent.node)", context);
}
public void testJIRA167c() {
MVEL.eval("true?true:(false)");
}
public void testJIRA176() {
Map innerMap = new HashMap();
innerMap.put("testKey[MyValue=newValue]", "test");
Map vars = new HashMap();
vars.put("mappo", innerMap);
assertEquals("test", MVEL.eval("mappo['testKey[MyValue=newValue]']", vars));
}
public void testJIRA176b() {
Map innerMap = new HashMap();
innerMap.put("testKey[MyValue=newValue]", "test");
Map vars = new HashMap();
vars.put("mappo", innerMap);
Serializable s = MVEL.compileExpression("mappo['testKey[MyValue=newValue]']");
OptimizerFactory.setDefaultOptimizer("reflective");
assertEquals("test", executeExpression(s, vars));
s = MVEL.compileExpression("mappo['testKey[MyValue=newValue]']");
OptimizerFactory.setDefaultOptimizer("ASM");
assertEquals("test", executeExpression(s, vars));
}
public void testRandomSomething() {
Foo foo = new Foo();
foo.setName("foo1");
Foo foo2 = new Foo();
foo2.setName("foo2");
MVEL.setProperty(foo, "name", 5);
Serializable s = MVEL.compileExpression("name.toUpperCase()", ParserContext.create().stronglyTyped().withInput("name", String.class));
Object _return = executeExpression(s, foo);
System.out.println("returned value: " + String.valueOf(_return));
_return = executeExpression(s, foo2);
System.out.println("returned value: " + String.valueOf(_return));
}
public static class ProcessManager {
public void startProcess(String name, Map<String, Object> variables) {
System.out.println("Process started");
}
}
public static class KnowledgeRuntimeHelper {
public ProcessManager getProcessManager() {
return new ProcessManager();
}
}
public void testDeepMethodNameResolution() {
String expression = "variables = [ \"symbol\" : \"RHT\" ]; \n" +
"drools.getProcessManager().startProcess(\"id\", variables );";
// third pass
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("drools", KnowledgeRuntimeHelper.class);
Map vars = new HashMap();
vars.put("drools", new KnowledgeRuntimeHelper());
Serializable expr = MVEL.compileExpression(expression, ctx);
executeExpression(expr, vars);
}
public void testJIRA183() {
String exp1 = "int end = 'attribute'.indexOf('@'); if(end == -1)" +
" { end = 'attribute'.length()} 'attribute'.substring(0, end);";
Object val1 = MVEL.eval(exp1, new HashMap<String, Object>());
String exp2 = "int end = 'attribute'.indexOf('@'); if(end == -1)" +
" { end = 'attribute'.length() } 'attribute'.substring(0, end);";
Object val2 = MVEL.eval(exp2, new HashMap<String, Object>());
}
public void testContextAssignments() {
Foo foo = new Foo();
MVEL.eval("this.name = 'bar'", foo);
assertEquals("bar", foo.getName());
}
public void testMVEL187() {
ParserContext context = new ParserContext();
context.addPackageImport("test");
context.addInput("outer", Outer.class);
Object compiled = MVEL.compileExpression(
"outer.getInner().getValue()", context);
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("outer", new Outer());
VariableResolverFactory varsResolver = new MapVariableResolverFactory(vars);
assertEquals(2, executeExpression(compiled, varsResolver));
}
public void testMVEL190() {
ParserContext context = new ParserContext();
context.addImport(Ship.class);
context.addImport(MapObject.class);
context.addInput("obj", MapObject.class);
Object compiled = MVEL.compileExpression(
"((Ship) obj).getName()", context);
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("obj", new Ship());
VariableResolverFactory varsResolver
= new MapVariableResolverFactory(vars);
System.out.println(
executeExpression(compiled, varsResolver));
}
public void testMethodScoring() {
OptimizerFactory.setDefaultOptimizer("ASM");
ParserConfiguration pconf = new ParserConfiguration();
for (Method m : StaticMethods.class.getMethods()) {
if (Modifier.isStatic(m.getModifiers())) {
pconf.addImport(m.getName(), m);
}
}
pconf.addImport("TestCase", TestCase.class);
ParserContext pctx = new ParserContext(pconf);
Map<String, Object> vars = new HashMap<String, Object>();
// this is successful
TestCase.assertTrue(StaticMethods.is(StaticMethods.getList(java.util.Formatter.class)));
// this also should be fine
Serializable expr = MVEL.compileExpression("TestCase.assertTrue( is( getList( java.util.Formatter ) ) )", pctx);
executeExpression(expr, vars);
}
public static class StaticMethods {
public static <T> boolean is(List<T> arg) {
return true;
}
public static boolean is(Collection arg) {
throw new RuntimeException("Wrong method called");
}
public static List<Object> getList(Class<?> arg) {
ArrayList<Object> result = new ArrayList<Object>();
result.add(arg);
return result;
}
public static String throwException() {
throw new RuntimeException("this should throw an exception");
}
}
public void testSetterViaDotNotation() {
TestClass tc = new TestClass();
tc.getExtra().put("test", "value");
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
String expression = "extra.test";
Serializable compiled = MVEL.compileSetExpression(expression, ctx);
MVEL.executeSetExpression(compiled, tc, "value2");
assertEquals("value2", tc.getExtra().get("test"));
}
public void testSetterViaMapNotation() {
TestClass tc = new TestClass();
tc.getExtra().put("test", "value");
ParserContext ctx = new ParserContext();
ctx.withInput("this", TestClass.class);
ctx.setStrongTyping(true);
String expression = "extra[\"test\"]";
Serializable compiled = MVEL.compileSetExpression(expression, tc.getClass(), ctx);
MVEL.executeSetExpression(compiled, tc, "value3");
assertEquals("value3", tc.getExtra().get("test"));
}
public void testGetterViaDotNotation() {
TestClass tc = new TestClass();
tc.getExtra().put("test", "value");
Map vars = new HashMap();
vars.put("tc", tc);
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("tc", tc.getClass());
String expression = "tc.extra.test";
Serializable compiled = MVEL.compileExpression(expression, ctx);
String val = (String) executeExpression(compiled, vars);
assertEquals("value", val);
}
public void testGetterViaMapNotation() {
TestClass tc = new TestClass();
tc.getExtra().put("test", "value");
Map vars = new HashMap();
vars.put("tc", tc);
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("tc", tc.getClass());
String expression = "tc.extra[\"test\"]";
Serializable compiled = MVEL.compileExpression(expression, ctx);
String val = (String) executeExpression(compiled, vars);
assertEquals("value", val);
}
public void testGetterViaMapGetter() {
TestClass tc = new TestClass();
tc.getExtra().put("test", "value");
Map vars = new HashMap();
vars.put("tc", tc);
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addInput("tc", tc.getClass());
String expression = "tc.extra.get(\"test\")";
Serializable compiled = MVEL.compileExpression(expression, ctx);
String val = (String) executeExpression(compiled, vars);
assertEquals("value", val);
}
public void testJIRA209() {
Map vars = new LinkedHashMap();
vars.put("bal", new BigDecimal("999.99"));
String[] testCases = {
// "bal < 100 or bal > 200",
// "bal < 100 || bal > 200",
"bal > 200 or bal < 100",
"bal > 200 || bal < 100",
"bal < 100 and bal > 200",
"bal < 100 && bal > 200",
"bal > 200 and bal < 100",
"bal > 200 && bal < 100"
};
Object val1, val2;
for (String expr : testCases) {
System.out.println("Evaluating '" + expr + "': ......");
val1 = MVEL.eval(expr, vars);
assertNotNull(val1);
Serializable compiled = MVEL.compileExpression(expr);
val2 = executeExpression(compiled, vars);
assertNotNull(val2);
assertEquals("expression did not evaluate correctly: " + expr, val1, val2);
}
}
public void testConstructor() {
String ex = " TestHelper.method(new Person('bob', 30), new Person('mark', 40, 999, 55, 10));\n";
ParserContext ctx = new ParserContext();
ctx.setStrongTyping(true);
ctx.addImport(TestHelper.class);
ctx.addImport(Person.class);
// un-comment the following line to see how MVEL is converting the int argument 40 into a
// string and then executing the wrong constructor on the Person class
try {
MVEL.compileExpression(ex, ctx);
fail("Constructor should not have been found.");
}
catch (CompileException e) {
// yay.
}
// fail( "The Person constructor used in the expression does not exist, so an error should have been raised during compilation." );
}
public void testAmbiguousGetName() {
Map<String, Object> vars = createTestMap();
vars.put("Foo244", Foo.class);
Serializable s = MVEL.compileExpression("foo.getClass().getName()");
System.out.println(MVEL.executeExpression(s, vars));
s = MVEL.compileExpression("Foo244.getName()");
System.out.println(MVEL.executeExpression(s, vars));
}
public void testBindingNullToPrimitiveTypes() {
Map<String, Object> vars = createTestMap();
((Foo) vars.get("foo")).setCountTest(10);
OptimizerFactory.setDefaultOptimizer("reflective");
Serializable s = MVEL.compileSetExpression("foo.countTest");
MVEL.executeSetExpression(s, vars, null);
assertEquals(((Foo) vars.get("foo")).getCountTest(), 0);
OptimizerFactory.setDefaultOptimizer("ASM");
s = MVEL.compileSetExpression("foo.countTest");
MVEL.executeSetExpression(s, vars, null);
assertEquals(((Foo) vars.get("foo")).getCountTest(), 0);
MVEL.executeSetExpression(s, vars, null);
assertEquals(((Foo) vars.get("foo")).getCountTest(), 0);
}
public void testBindingNullToPrimitiveTypes2() {
Map<String, Object> vars = createTestMap();
((Foo) vars.get("foo")).setCountTest(10);
OptimizerFactory.setDefaultOptimizer("reflective");
Serializable s = MVEL.compileSetExpression("foo.boolTest");
MVEL.executeSetExpression(s, vars, null);
assertFalse(((Foo) vars.get("foo")).isBoolTest());
OptimizerFactory.setDefaultOptimizer("ASM");
s = MVEL.compileSetExpression("foo.boolTest");
MVEL.executeSetExpression(s, vars, null);
assertFalse(((Foo) vars.get("foo")).isBoolTest());
MVEL.executeSetExpression(s, vars, null);
assertFalse(((Foo) vars.get("foo")).isBoolTest());
}
public void testBindingNullToPrimitiveTypes3() {
Map<String, Object> vars = createTestMap();
((Foo) vars.get("foo")).setCharTest('a');
OptimizerFactory.setDefaultOptimizer("reflective");
Serializable s = MVEL.compileSetExpression("foo.charTest");
MVEL.executeSetExpression(s, vars, null);
assertEquals(((Foo) vars.get("foo")).getCharTest(), 0);
OptimizerFactory.setDefaultOptimizer("ASM");
s = MVEL.compileSetExpression("foo.charTest");
MVEL.executeSetExpression(s, vars, null);
assertEquals(((Foo) vars.get("foo")).getCharTest(), 0);
MVEL.executeSetExpression(s, vars, null);
assertEquals(((Foo) vars.get("foo")).getCharTest(), 0);
}
public void testBindingNullToPrimitiveTypes4() {
Map<String, Object> vars = createTestMap();
((Foo) vars.get("foo")).charTestFld = 'a';
OptimizerFactory.setDefaultOptimizer("reflective");
Serializable s = MVEL.compileSetExpression("foo.charTestFld");
MVEL.executeSetExpression(s, vars, null);
assertEquals(((Foo) vars.get("foo")).charTestFld, 0);
OptimizerFactory.setDefaultOptimizer("ASM");
s = MVEL.compileSetExpression("foo.charTestFld");
MVEL.executeSetExpression(s, vars, null);
assertEquals(((Foo) vars.get("foo")).charTestFld, 0);
MVEL.executeSetExpression(s, vars, null);
assertEquals(((Foo) vars.get("foo")).charTestFld, 0);
}
public void testBindListToArray() {
Map<String, Object> vars = createTestMap();
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
OptimizerFactory.setDefaultOptimizer("reflective");
Serializable s = MVEL.compileSetExpression("foo.charArray");
MVEL.executeSetExpression(s, vars, list);
assertEquals(((Foo) vars.get("foo")).getCharArray().length, 3);
}
public void testBindListToMultiArray() {
Map<String, Object> vars = createTestMap();
ArrayList<List<String>> list = new ArrayList<List<String>>();
List<String> l1 = new ArrayList<String>();
l1.add("a");
l1.add("b");
l1.add("c");
List<String> l2 = new ArrayList<String>();
l2.add("d");
l2.add("e");
l2.add("f");
List<String> l3 = new ArrayList<String>();
l3.add("g");
l3.add("h");
l3.add("i");
list.add(l1);
list.add(l2);
list.add(l3);
OptimizerFactory.setDefaultOptimizer("reflective");
Serializable s = MVEL.compileSetExpression("foo.charArrayMulti");
MVEL.executeSetExpression(s, vars, list);
Foo foo = (Foo) vars.get("foo");
assertEquals(foo.getCharArrayMulti().length, 3);
assertEquals(foo.getCharArrayMulti()[2][2], 'i');
}
public void testMVEL224() {
ParserContext ctx = new ParserContext();
MVEL.compileExpression("(pin == 1)", ctx);
}
public static class A221 {
public B221 b;
}
public static class B221 {
public String c = "something";
}
public void testMVEL221() {
A221 a1 = new A221();
a1.b = new B221();
A221 a2 = new A221();
OptimizerFactory.setDefaultOptimizer("ASM");
String expression = "this.?b.c";
Serializable compiledExpression = MVEL.compileExpression(expression);
assertEquals(null, MVEL.executeExpression(compiledExpression, a2, String.class));
assertEquals("something", MVEL.executeExpression(compiledExpression, a1, String.class));
OptimizerFactory.setDefaultOptimizer("reflective");
compiledExpression = MVEL.compileExpression(expression);
assertEquals(null, MVEL.executeExpression(compiledExpression, a2, String.class));
assertEquals("something", MVEL.executeExpression(compiledExpression, a1, String.class));
}
public void testMVEL222() throws IOException {
String script = "for (int i= 0; i < 10; i++ ){ values[i] = 1.0; }";
Map<String, Object> scriptVars = new HashMap<String, Object>();
double[] values = new double[10];
scriptVars.put("values", values);
Serializable expression = MVEL.compileExpression(script);
for (int i = 0; i < 6; i++) {
scriptVars.put("values", values);
MVEL.executeExpression(expression, scriptVars);
}
}
public void testMVEL238() throws IOException {
String expr = new String(loadFromFile(new File("src/test/java/org/mvel2/tests/MVEL238.mvel")));
Serializable s = MVEL.compileExpression(expr);
System.out.println(MVEL.executeExpression(s, new HashMap()));
System.out.println(MVEL.executeExpression(s, new HashMap()));
}
public void testParsingRegression() {
String expr = "if (false) {System.out.println(\" foo\")} else {System.out.println(\" bar\")}";
MVEL.eval(expr);
}
public static class StaticClassWithStaticMethod {
public static String getString() {
return "hello";
}
}
// public void testStaticImportWithWildcard() {
// // this isn't supported yet
// assertEquals("hello",
// test("import_static " + getClass().getName() + ".StaticClassWithStaticMethod.*; getString()"));
public void testArrayLength() {
ParserContext context = new ParserContext();
context.setStrongTyping(true);
context.addInput("x",
String[].class);
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression("x.length", context);
}
public void testEmptyConstructorWithSpace() throws Exception {
ParserConfiguration pconf = new ParserConfiguration();
pconf.addImport("getString", StaticClassWithStaticMethod.class.getMethod("getString", null));
String text = "getString( )";
ParserContext pctx = new ParserContext(pconf);
pctx.setStrongTyping(true);
pctx.setStrictTypeEnforcement(true);
MVEL.compileExpression(text, pctx);
}
public void testJavaLangImport() throws Exception {
String s = "Exception e = null;";
ParserConfiguration pconf = new ParserConfiguration();
ParserContext pctx = new ParserContext(pconf);
MVEL.compileExpression(s, pctx);
}
public void testContextFieldNotFound() {
String str = "'stilton'.equals( type );";
ParserConfiguration pconf = new ParserConfiguration();
ParserContext pctx = new ParserContext(pconf);
pctx.addInput("this", Cheese.class);
pctx.setStrictTypeEnforcement(true);
pctx.setStrongTyping(true);
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
MVEL.executeExpression(stmt, new Cheese(), new HashMap());
}
public void testVarArgs() throws Exception {
ParserContext parserContext = new ParserContext();
parserContext.setStrictTypeEnforcement(true);
parserContext.setStrongTyping(true);
MVEL.analyze("String.format(\"\");", parserContext);
}
public void testOperatorPrecedence() throws IOException {
String script = "list = [1, 2, 3]; x = 10; list contains x || x == 20";
Serializable expression = MVEL.compileExpression(script);
Object result = MVEL.executeExpression(expression, new HashMap());
assertEquals(Boolean.FALSE, result);
}
public void testNestedEnum() throws Exception {
// assertEquals(Triangle.Foo.class, MVEL.analyze("import " + Triangle.class.getCanonicalName() +"; Triangle.Foo.OBTUSE" , ParserContext.create()));
// Serializable o = MVEL.compileExpression( "import " + Triangle.class.getCanonicalName() +"; Triangle.Foo.OBTUSE" );
// assertEquals( Triangle.Foo.OBTUSE, MVEL.executeExpression(o, new HashMap()) );
MVEL.eval("import " + Triangle.class.getCanonicalName() + "; Triangle.Foo.OBTUSE", new HashMap());
}
public void testNestedNumInMapKey() {
String str = "objectKeyMaptributes[Triangle.Foo.OBTUSE]";
ParserConfiguration pconf = new ParserConfiguration();
pconf.addImport("Triangle", Triangle.class);
ParserContext pctx = new ParserContext(pconf);
pctx.addInput("this", Person.class);
pctx.setStrongTyping(true);
Foo foo = new Foo();
Person p = new Person();
Map<Object, Foo> map = new HashMap<Object, Foo>();
map.put(Triangle.Foo.OBTUSE, foo);
p.setObjectKeyMaptributes(map);
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
Object o = MVEL.executeExpression(stmt, p, new HashMap());
}
public void testNestedClassWithNestedGenericsOnNakedMethod() {
String str = "deliveries.size";
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
ParserConfiguration pconf = new ParserConfiguration();
ParserContext pctx = new ParserContext(pconf);
pctx.addInput("this", Triangle.class);
pctx.setStrongTyping(true);
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
assertEquals(Integer.valueOf(0), (Integer) MVEL.executeExpression(stmt, new Triangle(), new HashMap()));
str = "deliveries.size == 0";
stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
assertTrue((Boolean) MVEL.executeExpression(stmt, new Triangle(), new HashMap()));
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = false;
}
public static class Triangle {
public static enum Foo {
INCOMPLETE, UNCLASSIFIED,
EQUILATERAL, ISOSCELES, RECTANGLED, ISOSCELES_RECTANGLED, ACUTE, OBTUSE;
}
private List<Map<String, Object>> deliveries = new ArrayList<Map<String, Object>>();
public List<Map<String, Object>> getDeliveries() {
return deliveries;
}
private Object objLabel = "Triangle";
private String strLabel = "Triangle";
private Double doubleVal = 29.0;
public Object getObjLabel() {
return objLabel;
}
public void setObjLabel(Object objLabel) {
this.objLabel = objLabel;
}
public String getStrLabel() {
return strLabel;
}
public void setStrLabel(String strLabel) {
this.strLabel = strLabel;
}
public Double getDoubleVal() {
return doubleVal;
}
public void setDoubleVal(Double doubleVal) {
this.doubleVal = doubleVal;
}
}
public void testStrictModeAddAll() {
String str = "list.addAll( o );";
ParserConfiguration pconf = new ParserConfiguration();
ParserContext pctx = new ParserContext(pconf);
pctx.setStrongTyping(true);
pctx.addInput("o", Object.class);
pctx.addInput("list", ArrayList.class);
try {
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
fail("This should not compileShared, as o is not of a type Collection");
}
catch (Exception e) {
}
}
public void testNestedEnumFromJar() throws ClassNotFoundException,
SecurityException,
NoSuchFieldException {
String expr = "EventRequest.Status.ACTIVE";
// creating a classloader for the jar
URL resource = getClass().getResource("/eventing-example.jar");
assertNotNull(resource);
URLClassLoader loader = new URLClassLoader(new URL[]{resource},
getClass().getClassLoader());
// loading the class to prove it works
Class<?> er = loader.loadClass("org.drools.examples.eventing.EventRequest");
assertNotNull(er);
assertEquals("org.drools.examples.eventing.EventRequest",
er.getCanonicalName());
// getting the value of the enum to prove it works:
Class<?> st = er.getDeclaredClasses()[0];
assertNotNull(st);
Field active = st.getField("ACTIVE");
assertNotNull(active);
// now, trying with MVEL
ParserConfiguration pconf = new ParserConfiguration();
pconf.setClassLoader(loader);
pconf.addImport(er);
ParserContext pctx = new ParserContext(pconf);
pctx.setStrongTyping(true);
Serializable compiled = MVEL.compileExpression(expr, pctx);
Object result = MVEL.executeExpression(compiled);
assertNotNull(result);
}
public void testContextObjMethodCall() {
String str = "getName() == \"bob\"";
ParserConfiguration pconf = new ParserConfiguration();
ParserContext pctx = new ParserContext(pconf);
pctx.setStrongTyping(true);
pctx.addInput("this", Bar.class);
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
Bar ctx = new Bar();
ctx.setName("bob");
Boolean result = (Boolean) MVEL.executeExpression(stmt, ctx);
assertTrue(result);
}
public void testStrTriangleEqualsEquals() {
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
try {
ParserConfiguration pconf = new ParserConfiguration();
ParserContext pctx = new ParserContext(pconf);
pctx.addInput("this", Triangle.class);
pctx.setStrongTyping(true);
String str = "this.strLabel == this";
try {
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
fail("should have failed");
}
catch (CompileException e) {
System.out.println();
return;
}
}
finally {
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = false;
}
}
public void testStrDoubleEqualsEquals() {
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
try {
ParserConfiguration pconf = new ParserConfiguration();
ParserContext pctx = new ParserContext(pconf);
pctx.addInput("this", Triangle.class);
pctx.setStrongTyping(true);
String str = "strLabel == doubleVal";
try {
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
}
catch (CompileException e) {
fail("should have failed");
}
}
finally {
MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = false;
}
}
public void testNarrowToWideCompare() {
Serializable s = MVEL.compileExpression("new String('foo') == new Object()",
ParserContext.create().stronglyTyped());
assertFalse((Boolean) MVEL.executeExpression(s));
}
public static class A {
private Map<String,String> map;
/**
* @return the map
*/
public Map<String, String> getMap() {
return map;
}
/**
* @param map the map to set
*/
public void setMap( Map<String, String> map ) {
this.map = map;
}
}
public void testGenericMethods() {
String str = "Integer.parseInt( a.getMap().get(\"x\") )";
ParserConfiguration pconf = new ParserConfiguration();
ParserContext pctx = new ParserContext(pconf);
pctx.setStrongTyping(true);
pctx.addInput( "a", A.class );
ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
A a = new A();
a.setMap( new HashMap<String,String>() );
a.getMap().put( "x", "10" );
Map<String,Object> variables = new HashMap<String, Object>();
variables.put( "a", a );
Number result = (Number) MVEL.executeExpression( stmt, null, variables );
assertEquals( 10, result.intValue() );
}
}
|
package org.neo4j.gis.spatial.pipes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.NoSuchElementException;
import org.geotools.data.neo4j.Neo4jFeatureBuilder;
import org.geotools.data.neo4j.StyledImageExporter;
import org.geotools.feature.FeatureCollection;
import org.geotools.filter.text.cql2.CQLException;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.crs.DefaultEngineeringCRS;
import org.geotools.styling.Style;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.neo4j.collections.rtree.filter.SearchAll;
import org.neo4j.collections.rtree.filter.SearchFilter;
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.examples.AbstractJavaDocTestbase;
import org.neo4j.gis.spatial.Constants;
import org.neo4j.gis.spatial.EditableLayerImpl;
import org.neo4j.gis.spatial.Layer;
import org.neo4j.gis.spatial.SpatialDatabaseService;
import org.neo4j.gis.spatial.filter.SearchIntersectWindow;
import org.neo4j.gis.spatial.osm.OSMImporter;
import org.neo4j.gis.spatial.pipes.filtering.FilterCQL;
import org.neo4j.gis.spatial.pipes.osm.OSMGeoPipeline;
import org.neo4j.graphdb.Transaction;
import org.neo4j.kernel.impl.annotations.Documented;
import org.neo4j.test.ImpermanentGraphDatabase;
import org.neo4j.test.TestData.Title;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.util.AffineTransformation;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
public class GeoPipesTest extends AbstractJavaDocTestbase
{
private static Layer osmLayer;
private static EditableLayerImpl boxesLayer;
private static EditableLayerImpl concaveLayer;
private static EditableLayerImpl intersectionLayer;
private static EditableLayerImpl equalLayer;
private static EditableLayerImpl linesLayer;
@Test
public void find_all()
{
int count = 0;
for ( GeoPipeFlow flow : GeoPipeline.start( osmLayer ).createWellKnownText() )
{
count++;
assertEquals( 1, flow.getProperties().size() );
String wkt = (String) flow.getProperties().get( "WellKnownText" );
assertTrue( wkt.indexOf( "LINESTRING" ) == 0 );
}
assertEquals( 2, count );
}
@Test
public void filter_by_osm_attribute()
{
GeoPipeline pipeline = OSMGeoPipeline.startOsm( osmLayer )
.osmAttributeFilter( "name", "Storgatan" )
.copyDatabaseRecordProperties();
GeoPipeFlow flow = pipeline.next();
assertFalse( pipeline.hasNext() );
assertEquals( "Storgatan", flow.getProperties().get( "name" ) );
}
@Test
public void filter_by_property()
{
GeoPipeline pipeline = GeoPipeline.start( osmLayer )
.copyDatabaseRecordProperties( "name" )
.propertyFilter( "name", "Storgatan" );
GeoPipeFlow flow = pipeline.next();
assertFalse( pipeline.hasNext() );
assertEquals( "Storgatan", flow.getProperties().get( "name" ) );
}
@Test
public void filter_by_window_intersection()
{
assertEquals(
1,
GeoPipeline.start( osmLayer ).windowIntersectionFilter( 10, 40, 20,
56.0583531 ).count() );
}
/**
* This pipe is filtering according
* to a CQL Bounding Box description
*
* Example:
*
* @@s_filter_by_cql_using_bbox
*/
@Documented
@Test
public void filter_by_cql_using_bbox() throws CQLException
{
// START SNIPPET: s_filter_by_cql_using_bbox
GeoPipeline cqlFilter = GeoPipeline.start( osmLayer ).cqlFilter(
"BBOX(the_geom, 10, 40, 20, 56.0583531)" );
// END SNIPPET: s_filter_by_cql_using_bbox
assertEquals(
1,
cqlFilter.count() );
}
/**
* This pipe performs a search within a
* geometry in this example, both OSM street
* geometries should be found in when searching with
* an enclosing rectangle Envelope.
*
* Example:
*
* @@s_search_within_geometry
*/
@Test
@Documented
public void search_within_geometry() throws CQLException
{
// START SNIPPET: s_search_within_geometry
GeoPipeline pipeline = GeoPipeline
.startWithinSearch(osmLayer, osmLayer.getGeometryFactory().toGeometry(new Envelope(10, 20, 50, 60)));
// END SNIPPET: s_search_within_geometry
assertEquals(
2,
pipeline.count() );
}
@Test
public void filter_by_cql_using_property() throws CQLException
{
GeoPipeline pipeline = GeoPipeline.start( osmLayer ).cqlFilter(
"name = 'Storgatan'" ).copyDatabaseRecordProperties();
GeoPipeFlow flow = pipeline.next();
assertFalse( pipeline.hasNext() );
assertEquals( "Storgatan", flow.getProperties().get( "name" ) );
}
/**
* This filter will apply the
* provided CQL expression to the different geometries and only
* let the matching ones pass.
*
* Example:
*
* @@s_filter_by_cql_using_complex_cql
*/
@Documented
@Test
public void filter_by_cql_using_complex_cql() throws CQLException
{
// START SNIPPET: s_filter_by_cql_using_complex_cql
long counter = GeoPipeline.start( osmLayer ).cqlFilter(
"highway is not null and geometryType(the_geom) = 'LineString'" ).count();
// END SNIPPET: s_filter_by_cql_using_complex_cql
FilterCQL filter = new FilterCQL(osmLayer,"highway is not null and geometryType(the_geom) = 'LineString'" );
filter.setStarts( GeoPipeline.start( osmLayer ));
assertTrue( filter.hasNext() );
while(filter.hasNext())
{
filter.next();
counter
}
assertEquals( 0, counter );
}
/**
* Affine Transformation
*
* The ApplyAffineTransformation pipe applies an affine transformation to every geometry.
*
* Example:
*
* @@s_affine_transformation
*
* Output:
*
* @@affine_transformation
*/
@Documented
@Test
public void traslate_geometries()
{
// START SNIPPET: s_affine_transformation
GeoPipeline pipeline = GeoPipeline.start( boxesLayer )
.applyAffineTransform(AffineTransformation.translationInstance( 2, 3 ));
// END SNIPPET: s_affine_transformation
addImageSnippet(boxesLayer, pipeline, getTitle());
GeoPipeline original = GeoPipeline.start( osmLayer ).copyDatabaseRecordProperties().sort(
"name" );
GeoPipeline translated = GeoPipeline.start( osmLayer ).applyAffineTransform(
AffineTransformation.translationInstance( 10, 25 ) ).copyDatabaseRecordProperties().sort(
"name" );
for ( int k = 0; k < 2; k++ )
{
Coordinate[] coords = original.next().getGeometry().getCoordinates();
Coordinate[] newCoords = translated.next().getGeometry().getCoordinates();
assertEquals( coords.length, newCoords.length );
for ( int i = 0; i < coords.length; i++ )
{
assertEquals( coords[i].x + 10, newCoords[i].x, 0 );
assertEquals( coords[i].y + 25, newCoords[i].y, 0 );
}
}
}
@Test
public void calculate_area()
{
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).calculateArea().sort(
"Area" );
assertEquals( (Double) pipeline.next().getProperties().get( "Area" ),
1.0, 0 );
assertEquals( (Double) pipeline.next().getProperties().get( "Area" ),
8.0, 0 );
}
@Test
public void calculate_length()
{
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).calculateLength().sort(
"Length" );
assertEquals( (Double) pipeline.next().getProperties().get( "Length" ),
4.0, 0 );
assertEquals( (Double) pipeline.next().getProperties().get( "Length" ),
12.0, 0 );
}
@Test
public void get_boundary_length()
{
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).toBoundary().createWellKnownText().calculateLength().sort(
"Length" );
GeoPipeFlow first = pipeline.next();
GeoPipeFlow second = pipeline.next();
assertEquals( "LINEARRING (12 26, 12 27, 13 27, 13 26, 12 26)",
first.getProperties().get( "WellKnownText" ) );
assertEquals( "LINEARRING (2 3, 2 5, 6 5, 6 3, 2 3)",
second.getProperties().get( "WellKnownText" ) );
assertEquals( (Double) first.getProperties().get( "Length" ), 4.0, 0 );
assertEquals( (Double) second.getProperties().get( "Length" ), 12.0, 0 );
}
/**
* Buffer
*
* The Buffer pipe applies a buffer to geometries.
*
* Example:
*
* @@s_buffer
*
* Output:
*
* @@buffer
*/
@Documented
@Test
public void get_buffer()
{
// START SNIPPET: s_buffer
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).toBuffer( 0.5 );
// END SNIPPET: s_buffer
addImageSnippet(boxesLayer, pipeline, getTitle());
pipeline = GeoPipeline.start( boxesLayer ).toBuffer( 0.1 ).createWellKnownText().calculateArea().sort(
"Area" );
assertTrue( ( (Double) pipeline.next().getProperties().get( "Area" ) ) > 1 );
assertTrue( ( (Double) pipeline.next().getProperties().get( "Area" ) ) > 8 );
}
/**
* Centroid
*
* The Centroid pipe calculates geometry centroid.
*
* Example:
*
* @@s_centroid
*
* Output:
*
* @@centroid
*/
@Documented
@Test
public void get_centroid()
{
// START SNIPPET: s_centroid
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).toCentroid();
// END SNIPPET: s_centroid
addImageSnippet(boxesLayer, pipeline, getTitle(), Constants.GTYPE_POINT);
pipeline = GeoPipeline.start( boxesLayer ).toCentroid().createWellKnownText().copyDatabaseRecordProperties().sort(
"name" );
assertEquals( "POINT (12.5 26.5)",
pipeline.next().getProperties().get( "WellKnownText" ) );
assertEquals( "POINT (4 4)",
pipeline.next().getProperties().get( "WellKnownText" ) );
}
@Documented
@Test
public void export_to_GML()
{
// START SNIPPET: s_export_to_gml
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).createGML();
for ( GeoPipeFlow flow : pipeline ) {
System.out.println(flow.getProperties().get( "GML" ));
}
// END SNIPPET: s_export_to_gml
String result = "";
for ( GeoPipeFlow flow : GeoPipeline.start( boxesLayer ).createGML() ) {
result = result + flow.getProperties().get( "GML" );
}
gen.get().addSnippet( "exportgml", "[source,xml]\n
}
/**
* Convex Hull
*
* The ConvexHull pipe calculates geometry convex hull.
*
* Example:
*
* @@s_convex_hull
*
* Output:
*
* @@convex_hull
*/
@Documented
@Test
public void get_convex_hull()
{
// START SNIPPET: s_convex_hull
GeoPipeline pipeline = GeoPipeline.start( concaveLayer ).toConvexHull();
// END SNIPPET: s_convex_hull
addImageSnippet(concaveLayer, pipeline, getTitle());
pipeline = GeoPipeline.start( concaveLayer ).toConvexHull().createWellKnownText();
assertEquals( "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))",
pipeline.next().getProperties().get( "WellKnownText" ) );
}
/**
* Densify
*
* The Densify pipe inserts extra vertices along the line segments in the geometry.
* The densified geometry contains no line segment which is longer than the given distance tolerance.
*
* Example:
*
* @@s_densify
*
* Output:
*
* @@densify
*/
@Documented
@Test
public void densify()
{
// START SNIPPET: s_densify
GeoPipeline pipeline = GeoPipeline.start( concaveLayer ).densify( 5 ).extractPoints();
// END SNIPPET: s_densify
addImageSnippet(concaveLayer, pipeline, getTitle(), Constants.GTYPE_POINT);
pipeline = GeoPipeline.start( concaveLayer ).toConvexHull().densify( 10 ).createWellKnownText();
assertEquals(
"POLYGON ((0 0, 0 5, 0 10, 5 10, 10 10, 10 5, 10 0, 5 0, 0 0))",
pipeline.next().getProperties().get( "WellKnownText" ) );
}
@Test
public void json()
{
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).createJson().copyDatabaseRecordProperties().sort(
"name" );
assertEquals(
"{\"type\":\"Polygon\",\"coordinates\":[[[12,26],[12,27],[13,27],[13,26],[12,26]]]}",
pipeline.next().getProperties().get( "GeoJSON" ) );
assertEquals(
"{\"type\":\"Polygon\",\"coordinates\":[[[2,3],[2,5],[6,5],[6,3],[2,3]]]}",
pipeline.next().getProperties().get( "GeoJSON" ) );
}
/**
* Max
*
* The Max pipe computes the maximum value of the specified property and
* discard items with a value less than the maximum.
*
* Example:
*
* @@s_max
*
* Output:
*
* @@max
*/
@Documented
@Test
public void get_max_area()
{
// START SNIPPET: s_max
GeoPipeline pipeline = GeoPipeline.start( boxesLayer )
.calculateArea()
.getMax( "Area" );
// END SNIPPET: s_max
addImageSnippet( boxesLayer, pipeline, getTitle() );
pipeline = GeoPipeline.start( boxesLayer ).calculateArea().getMax(
"Area" );
assertEquals( (Double) pipeline.next().getProperties().get( "Area" ),
8.0, 0 );
}
/**
* The
* boundary pipe calculates boundary of every geometry in the pipeline.
*
* Example:
*
* @@s_boundary
*
* Output:
*
* @@boundary
*/
@Documented
@Test
public void boundary()
{
// START SNIPPET: s_boundary
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).toBoundary();
// END SNIPPET: s_boundary
addImageSnippet( boxesLayer, pipeline, getTitle(), Constants.GTYPE_LINESTRING );
// TODO test?
}
/**
* Difference
*
* The Difference pipe computes a geometry representing
* the points making up item geometry that do not make up the given geometry.
*
* Example:
*
* @@s_difference
*
* Output:
*
* @@difference
*/
@Documented
@Test
public void difference() throws Exception
{
// START SNIPPET: s_difference
WKTReader reader = new WKTReader( intersectionLayer.getGeometryFactory() );
Geometry geometry = reader.read( "POLYGON ((3 3, 3 5, 7 7, 7 3, 3 3))" );
GeoPipeline pipeline = GeoPipeline.start( intersectionLayer ).difference( geometry );
// END SNIPPET: s_difference
addImageSnippet( intersectionLayer, pipeline, getTitle() );
// TODO test?
}
/**
* Intersection
*
* The Intersection pipe computes a geometry representing the intersection between item geometry and the given geometry.
*
* Example:
*
* @@s_intersection
*
* Output:
*
* @@intersection
*/
@Documented
@Test
public void intersection() throws Exception
{
// START SNIPPET: s_intersection
WKTReader reader = new WKTReader( intersectionLayer.getGeometryFactory() );
Geometry geometry = reader.read( "POLYGON ((3 3, 3 5, 7 7, 7 3, 3 3))" );
GeoPipeline pipeline = GeoPipeline.start( intersectionLayer ).intersect( geometry );
// END SNIPPET: s_intersection
addImageSnippet( intersectionLayer, pipeline, getTitle() );
// TODO test?
}
/**
* Union
*
* The Union pipe unites item geometry with a given geometry.
*
* Example:
*
* @@s_union
*
* Output:
*
* @@union
*/
@Documented
@Test
public void union() throws Exception
{
// START SNIPPET: s_union
WKTReader reader = new WKTReader( intersectionLayer.getGeometryFactory() );
Geometry geometry = reader.read( "POLYGON ((3 3, 3 5, 7 7, 7 3, 3 3))" );
SearchFilter filter = new SearchIntersectWindow( intersectionLayer, new Envelope( 7, 10, 7, 10 ) );
GeoPipeline pipeline = GeoPipeline.start( intersectionLayer, filter ).union( geometry );
// END SNIPPET: s_union
addImageSnippet( intersectionLayer, pipeline, getTitle() );
// TODO test?
}
/**
* Min
*
* The Min pipe computes the minimum value of the specified property and
* discard items with a value greater than the minimum.
*
* Example:
*
* @@s_min
*
* Output:
*
* @@min
*/
@Documented
@Test
public void get_min_area()
{
// START SNIPPET: s_min
GeoPipeline pipeline = GeoPipeline.start( boxesLayer )
.calculateArea()
.getMin( "Area" );
// END SNIPPET: s_min
addImageSnippet( boxesLayer, pipeline, getTitle() );
pipeline = GeoPipeline.start( boxesLayer ).calculateArea().getMin(
"Area" );
assertEquals( (Double) pipeline.next().getProperties().get( "Area" ),
1.0, 0 );
}
@Test
public void extract_osm_points()
{
int count = 0;
GeoPipeline pipeline = OSMGeoPipeline.startOsm( osmLayer ).extractOsmPoints().createWellKnownText();
for ( GeoPipeFlow flow : pipeline )
{
count++;
assertEquals( 1, flow.getProperties().size() );
String wkt = (String) flow.getProperties().get( "WellKnownText" );
assertTrue( wkt.indexOf( "POINT" ) == 0 );
}
assertEquals( 24, count );
}
/**
* A more complex Open Street Map example.
*
* This example demostrates the some pipes chained together to make a full
* geoprocessing pipeline.
*
* Example:
*
* @@s_break_up_all_geometries_into_points_and_make_density_islands
*
* _Step1_
*
* @@step1_break_up_all_geometries_into_points_and_make_density_islands
*
* _Step2_
*
* @@step2_break_up_all_geometries_into_points_and_make_density_islands
*
* _Step3_
*
* @@step3_break_up_all_geometries_into_points_and_make_density_islands
*
* _Step4_
*
* @@step4_break_up_all_geometries_into_points_and_make_density_islands
*
* _Step5_
*
* @@step5_break_up_all_geometries_into_points_and_make_density_islands
*/
@Documented
@Title("break_up_all_geometries_into_points_and_make_density_islands")
@Test
public void break_up_all_geometries_into_points_and_make_density_islands_and_get_the_outer_linear_ring_of_the_density_islands_and_buffer_the_geometry_and_count_them()
{
// START SNIPPET: s_break_up_all_geometries_into_points_and_make_density_islands
//step1
GeoPipeline pipeline = OSMGeoPipeline.startOsm( osmLayer )
//step2
.extractOsmPoints()
//step3
.groupByDensityIslands( 0.0005 )
//step4
.toConvexHull()
//step5
.toBuffer( 0.0004 );
// END SNIPPET: s_break_up_all_geometries_into_points_and_make_density_islands
assertEquals( 9, pipeline.count() );
addOsmImageSnippet( osmLayer, OSMGeoPipeline.startOsm( osmLayer ), "step1_"+getTitle(), Constants.GTYPE_LINESTRING );
addOsmImageSnippet( osmLayer, OSMGeoPipeline.startOsm( osmLayer ).extractOsmPoints(), "step2_"+getTitle(), Constants.GTYPE_POINT );
addOsmImageSnippet( osmLayer, OSMGeoPipeline.startOsm( osmLayer ).extractOsmPoints().groupByDensityIslands( 0.0005 ), "step3_"+getTitle(), Constants.GTYPE_POLYGON );
addOsmImageSnippet( osmLayer, OSMGeoPipeline.startOsm( osmLayer ).extractOsmPoints().groupByDensityIslands( 0.0005 ).toConvexHull(), "step4_"+getTitle(), Constants.GTYPE_POLYGON );
addOsmImageSnippet( osmLayer, OSMGeoPipeline.startOsm( osmLayer ).extractOsmPoints().groupByDensityIslands( 0.0005 ).toConvexHull().toBuffer( 0.0004 ), "step5_"+getTitle(), Constants.GTYPE_POLYGON );
}
/**
* Extract Points
*
* The Extract Points pipe extracts every point from a geometry.
*
* Example:
*
* @@s_extract_points
*
* Output:
*
* @@extract_points
*/
@Documented
@Test
public void extract_points()
{
// START SNIPPET: s_extract_points
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).extractPoints();
// END SNIPPET: s_extract_points
addImageSnippet(boxesLayer, pipeline, getTitle(), Constants.GTYPE_POINT);
int count = 0;
for ( GeoPipeFlow flow : GeoPipeline.start( boxesLayer ).extractPoints().createWellKnownText() )
{
count++;
assertEquals( 1, flow.getProperties().size() );
String wkt = (String) flow.getProperties().get( "WellKnownText" );
assertTrue( wkt.indexOf( "POINT" ) == 0 );
}
// every rectangle has 5 points, the last point is in the same position of the first
assertEquals( 10, count );
}
@Test
public void filter_by_null_property()
{
assertEquals(
2,
GeoPipeline.start( boxesLayer ).copyDatabaseRecordProperties().propertyNullFilter(
"address" ).count() );
assertEquals(
0,
GeoPipeline.start( boxesLayer ).copyDatabaseRecordProperties().propertyNullFilter(
"name" ).count() );
}
@Test
public void filter_by_not_null_property()
{
assertEquals(
0,
GeoPipeline.start( boxesLayer ).copyDatabaseRecordProperties().propertyNotNullFilter(
"address" ).count() );
assertEquals(
2,
GeoPipeline.start( boxesLayer ).copyDatabaseRecordProperties().propertyNotNullFilter(
"name" ).count() );
}
@Test
public void compute_distance() throws ParseException
{
WKTReader reader = new WKTReader( boxesLayer.getGeometryFactory() );
GeoPipeline pipeline = GeoPipeline.start( boxesLayer ).calculateDistance(
reader.read( "POINT (0 0)" ) ).sort( "Distance" );
assertEquals(
4, Math.round( (Double) pipeline.next().getProperty( "Distance" ) ) );
assertEquals(
29, Math.round( (Double) pipeline.next().getProperty( "Distance" ) ) );
}
/**
* Unite All
*
* The Union All pipe unites geometries of every item contained in the pipeline.
* This pipe groups every item in the pipeline in a single item containing the geometry output
* of the union.
*
* Example:
*
* @@s_unite_all
*
* Output:
*
* @@unite_all
*/
@Documented
@Test
public void unite_all()
{
// START SNIPPET: s_unite_all
GeoPipeline pipeline = GeoPipeline.start( intersectionLayer ).unionAll();
// END SNIPPET: s_unite_all
addImageSnippet( intersectionLayer, pipeline, getTitle() );
pipeline = GeoPipeline.start( intersectionLayer )
.unionAll()
.createWellKnownText();
assertEquals(
"POLYGON ((0 0, 0 5, 2 5, 2 6, 4 6, 4 10, 10 10, 10 4, 6 4, 6 2, 5 2, 5 0, 0 0))",
pipeline.next().getProperty( "WellKnownText" ) );
try
{
pipeline.next();
fail();
}
catch ( NoSuchElementException e )
{
}
}
/**
* Intersect All
*
* The IntersectAll pipe intersects geometries of every item contained in the pipeline.
* It groups every item in the pipeline in a single item containing the geometry output
* of the intersection.
*
* Example:
*
* @@s_intersect_all
*
* Output:
*
* @@intersect_all
*/
@Documented
@Test
public void intersect_all()
{
// START SNIPPET: s_intersect_all
GeoPipeline pipeline = GeoPipeline.start( intersectionLayer ).intersectAll();
// END SNIPPET: s_intersect_all
addImageSnippet( intersectionLayer, pipeline, getTitle() );
pipeline = GeoPipeline.start( intersectionLayer )
.intersectAll()
.createWellKnownText();
assertEquals( "POLYGON ((4 5, 5 5, 5 4, 4 4, 4 5))",
pipeline.next().getProperty( "WellKnownText" ) );
try
{
pipeline.next();
fail();
}
catch ( NoSuchElementException e )
{
}
}
/**
* Intersecting windows
*
* The FilterIntersectWindow pipe finds geometries that intersects a given rectangle.
* This pipeline:
*
* @@s_intersecting_windows
*
* will output:
*
* @@intersecting_windows
*/
@Documented
@Test
public void intersecting_windows()
{
// START SNIPPET: s_intersecting_windows
GeoPipeline pipeline = GeoPipeline
.start( boxesLayer )
.windowIntersectionFilter(new Envelope( 0, 10, 0, 10 ) );
// END SNIPPET: s_intersecting_windows
addImageSnippet( boxesLayer, pipeline, getTitle() );
// TODO test?
}
/**
* Start Point
*
* The StartPoint pipe finds the starting point of item geometry.
* Example:
*
* @@s_start_point
*
* Output:
*
* @@start_point
*/
@Documented
@Test
public void start_point()
{
// START SNIPPET: s_start_point
GeoPipeline pipeline = GeoPipeline
.start( linesLayer )
.toStartPoint();
// END SNIPPET: s_start_point
addImageSnippet( linesLayer, pipeline, getTitle(), Constants.GTYPE_POINT );
pipeline = GeoPipeline
.start( linesLayer )
.toStartPoint()
.createWellKnownText();
assertEquals("POINT (12 26)", pipeline.next().getProperty("WellKnownText"));
}
/**
* End Point
*
* The EndPoint pipe finds the ending point of item geometry.
* Example:
*
* @@s_end_point
*
* Output:
*
* @@end_point
*/
@Documented
@Test
public void end_point()
{
// START SNIPPET: s_end_point
GeoPipeline pipeline = GeoPipeline
.start( linesLayer )
.toEndPoint();
// END SNIPPET: s_end_point
addImageSnippet( linesLayer, pipeline, getTitle(), Constants.GTYPE_POINT );
pipeline = GeoPipeline
.start( linesLayer )
.toEndPoint()
.createWellKnownText();
assertEquals("POINT (23 34)", pipeline.next().getProperty("WellKnownText"));
}
/**
* Envelope
*
* The Envelope pipe computes the minimum bounding box of item geometry.
* Example:
*
* @@s_envelope
*
* Output:
*
* @@envelope
*/
@Documented
@Test
public void envelope()
{
// START SNIPPET: s_envelope
GeoPipeline pipeline = GeoPipeline
.start( linesLayer )
.toEnvelope();
// END SNIPPET: s_envelope
addImageSnippet( linesLayer, pipeline, getTitle(), Constants.GTYPE_POLYGON );
// TODO test
}
@Test
public void test_equality() throws Exception
{
WKTReader reader = new WKTReader( equalLayer.getGeometryFactory() );
Geometry geom = reader.read( "POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))" );
GeoPipeline pipeline = GeoPipeline.startEqualExactSearch( equalLayer,
geom, 0 ).copyDatabaseRecordProperties();
assertEquals( "equal", pipeline.next().getProperty( "name" ) );
assertFalse( pipeline.hasNext() );
pipeline = GeoPipeline.startEqualExactSearch( equalLayer, geom, 0.1 ).copyDatabaseRecordProperties().sort(
"id" );
assertEquals( "equal", pipeline.next().getProperty( "name" ) );
assertEquals( "tolerance", pipeline.next().getProperty( "name" ) );
assertFalse( pipeline.hasNext() );
pipeline = GeoPipeline.startIntersectWindowSearch( equalLayer,
geom.getEnvelopeInternal() ).equalNormFilter( geom, 0.1 ).copyDatabaseRecordProperties().sort(
"id" );
assertEquals( "equal", pipeline.next().getProperty( "name" ) );
assertEquals( "tolerance", pipeline.next().getProperty( "name" ) );
assertEquals( "different order", pipeline.next().getProperty( "name" ) );
assertFalse( pipeline.hasNext() );
pipeline = GeoPipeline.startIntersectWindowSearch( equalLayer,
geom.getEnvelopeInternal() ).equalTopoFilter( geom ).copyDatabaseRecordProperties().sort(
"id" );
assertEquals( "equal", pipeline.next().getProperty( "name" ) );
assertEquals( "different order", pipeline.next().getProperty( "name" ) );
assertEquals( "topo equal", pipeline.next().getProperty( "name" ) );
assertFalse( pipeline.hasNext() );
}
private String getTitle()
{
return gen.get().getTitle().replace( " ", "_" ).toLowerCase();
}
private void addImageSnippet(
Layer layer,
GeoPipeline pipeline,
String imgName )
{
addImageSnippet( layer, pipeline, imgName, null );
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void addOsmImageSnippet(
Layer layer,
GeoPipeline pipeline,
String imgName,
Integer geomType )
{
addImageSnippet( layer, pipeline, imgName, geomType, 0.002 );
}
private void addImageSnippet(
Layer layer,
GeoPipeline pipeline,
String imgName,
Integer geomType )
{
addImageSnippet( layer, pipeline, imgName, geomType, 1 );
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void addImageSnippet(
Layer layer,
GeoPipeline pipeline,
String imgName,
Integer geomType,
double boundsDelta )
{
gen.get().addSnippet( imgName, "\nimage::" + imgName + ".png[scaledwidth=\"75%\"]\n" );
try
{
FeatureCollection layerCollection = GeoPipeline.start(layer, new SearchAll()).toFeatureCollection();
FeatureCollection pipelineCollection;
if (geomType == null) {
pipelineCollection = pipeline.toFeatureCollection();
} else {
pipelineCollection = pipeline.toFeatureCollection(
Neo4jFeatureBuilder.getType(layer.getName(), geomType, layer.getCoordinateReferenceSystem(), layer.getExtraPropertyNames()));
}
ReferencedEnvelope bounds = layerCollection.getBounds();
bounds.expandToInclude(pipelineCollection.getBounds());
bounds.expandBy(boundsDelta, boundsDelta);
StyledImageExporter exporter = new StyledImageExporter( db );
exporter.setExportDir( "target/docs/images/" );
exporter.saveImage(
new FeatureCollection[] {
layerCollection,
pipelineCollection,
},
new Style[] {
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN),
StyledImageExporter.createDefaultStyle(Color.RED, Color.ORANGE)
},
new File( imgName + ".png" ),
bounds);
}
catch ( IOException e )
{
e.printStackTrace();
}
}
private static void load() throws Exception
{
SpatialDatabaseService spatialService = new SpatialDatabaseService( db );
loadTestOsmData( "two-street.osm", 100 );
osmLayer = spatialService.getLayer( "two-street.osm" );
Transaction tx = db.beginTx();
try {
boxesLayer = (EditableLayerImpl) spatialService.getOrCreateEditableLayer( "boxes" );
boxesLayer.setExtraPropertyNames( new String[] { "name" } );
boxesLayer.setCoordinateReferenceSystem(DefaultEngineeringCRS.GENERIC_2D);
WKTReader reader = new WKTReader( boxesLayer.getGeometryFactory() );
boxesLayer.add(
reader.read( "POLYGON ((12 26, 12 27, 13 27, 13 26, 12 26))" ),
new String[] { "name" }, new Object[] { "A" } );
boxesLayer.add( reader.read( "POLYGON ((2 3, 2 5, 6 5, 6 3, 2 3))" ),
new String[] { "name" }, new Object[] { "B" } );
concaveLayer = (EditableLayerImpl) spatialService.getOrCreateEditableLayer( "concave" );
concaveLayer.setCoordinateReferenceSystem(DefaultEngineeringCRS.GENERIC_2D);
reader = new WKTReader( concaveLayer.getGeometryFactory() );
concaveLayer.add( reader.read( "POLYGON ((0 0, 2 5, 0 10, 10 10, 10 0, 0 0))" ) );
intersectionLayer = (EditableLayerImpl) spatialService.getOrCreateEditableLayer( "intersection" );
intersectionLayer.setCoordinateReferenceSystem(DefaultEngineeringCRS.GENERIC_2D);
reader = new WKTReader( intersectionLayer.getGeometryFactory() );
intersectionLayer.add( reader.read( "POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))" ) );
intersectionLayer.add( reader.read( "POLYGON ((4 4, 4 10, 10 10, 10 4, 4 4))" ) );
intersectionLayer.add( reader.read( "POLYGON ((2 2, 2 6, 6 6, 6 2, 2 2))" ) );
equalLayer = (EditableLayerImpl) spatialService.getOrCreateEditableLayer( "equal" );
equalLayer.setExtraPropertyNames( new String[] { "id", "name" } );
equalLayer.setCoordinateReferenceSystem(DefaultEngineeringCRS.GENERIC_2D);
reader = new WKTReader( intersectionLayer.getGeometryFactory() );
equalLayer.add( reader.read( "POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))" ),
new String[] { "id", "name" }, new Object[] { 1, "equal" } );
equalLayer.add( reader.read( "POLYGON ((0 0, 0.1 5, 5 5, 5 0, 0 0))" ),
new String[] { "id", "name" }, new Object[] { 2, "tolerance" } );
equalLayer.add( reader.read( "POLYGON ((0 5, 5 5, 5 0, 0 0, 0 5))" ),
new String[] { "id", "name" }, new Object[] { 3,
"different order" } );
equalLayer.add(
reader.read( "POLYGON ((0 0, 0 2, 0 4, 0 5, 5 5, 5 3, 5 2, 5 0, 0 0))" ),
new String[] { "id", "name" }, new Object[] { 4, "topo equal" } );
linesLayer = (EditableLayerImpl) spatialService.getOrCreateEditableLayer( "lines" );
linesLayer.setCoordinateReferenceSystem(DefaultEngineeringCRS.GENERIC_2D);
reader = new WKTReader( intersectionLayer.getGeometryFactory() );
linesLayer.add( reader.read( "LINESTRING (12 26, 15 27, 18 32, 20 38, 23 34)" ) );
tx.success();
} finally {
tx.finish();
}
}
private static void loadTestOsmData( String layerName, int commitInterval )
throws Exception
{
String osmPath = "./" + layerName;
System.out.println( "\n=== Loading layer " + layerName + " from "
+ osmPath + " ===" );
OSMImporter importer = new OSMImporter( layerName );
importer.setCharset( Charset.forName( "UTF-8" ) );
importer.importFile( db, osmPath );
importer.reIndex( db, commitInterval );
}
@Before
public void setUp()
{
gen.get().setGraph( db );
engine = new ExecutionEngine( db );
try
{
StyledImageExporter exporter = new StyledImageExporter( db );
exporter.setExportDir( "target/docs/images/" );
exporter.saveImage( GeoPipeline.start( intersectionLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"intersectionLayer.png" ) );
exporter.saveImage( GeoPipeline.start( boxesLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"boxesLayer.png" ) );
exporter.saveImage( GeoPipeline.start( concaveLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"concaveLayer.png" ) );
exporter.saveImage( GeoPipeline.start( equalLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"equalLayer.png" ) );
exporter.saveImage( GeoPipeline.start( linesLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"linesLayer.png" ) );
exporter.saveImage( GeoPipeline.start( osmLayer ).toFeatureCollection(),
StyledImageExporter.createDefaultStyle(Color.BLUE, Color.CYAN), new File(
"osmLayer.png" ) );
}
catch ( IOException e )
{
e.printStackTrace();
}
}
@After
public void doc()
{
// gen.get().addSnippet( "graph", AsciidocHelper.createGraphViz( imgName , graphdb(), "graph"+getTitle() ) );
gen.get().addTestSourceSnippets( GeoPipesTest.class, "s_"+getTitle().toLowerCase() );
gen.get().document( "target/docs", "examples" );
}
@BeforeClass
public static void init()
{
db = new ImpermanentGraphDatabase( );
((ImpermanentGraphDatabase)db).cleanContent( true );
try
{
load();
}
catch ( Exception e )
{
e.printStackTrace();
}
StyledImageExporter exporter = new StyledImageExporter( db );
exporter.setExportDir( "target/docs/images/" );
}
private GeoPipeFlow print( GeoPipeFlow pipeFlow )
{
System.out.println( "GeoPipeFlow:" );
for ( String key : pipeFlow.getProperties().keySet() )
{
System.out.println( key + "=" + pipeFlow.getProperties().get( key ) );
}
System.out.println( "-" );
return pipeFlow;
}
}
|
package pl.datamatica.traccar.model;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
*
* @author Jan Usarek
*/
public class PositionTest {
@Test
public void testNullValidStatus() throws Exception {
Position position = new Position();
assertTrue(position.hasProperValidStatus());
}
@Test
public void testProperValidStatus() throws Exception {
Position position = new Position();
position.setValidStatus(Position.VALID_STATUS_CORRECT_POSITION);
assertTrue(position.hasProperValidStatus());
}
@Test
public void testAlarmValidStatus() throws Exception {
Position position = new Position();
position.setValidStatus(Position.VALID_STATUS_ALARM);
assertFalse(position.hasProperValidStatus());
}
@Test
public void testSpeedUnitConversion() throws Exception {
Position position = new Position();
position.setSpeed(1000.00);
assertEquals(1852, position.getSpeedInKmh().intValue());
}
}
|
package com.sap.openui5;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.tools.shell.Global;
/**
* The class <code>LessFilter</code> is used to compile CSS for Less files
* on the fly - once they are requested by the application.
*
* @author Peter Muessig, Matthias Osswald
*/
public class LessFilter implements Filter{
/** default prefix for the classpath */
private static final String CLASSPATH_PREFIX = "META-INF";
/** pattern to identify a theme request */
private static final Pattern PATTERN_THEME_REQUEST = Pattern.compile("(.*)/(library\\.css|/library-RTL\\.css|/library-parameters\\.json)$");
/** pattern to identify a theme request */
private static final Pattern PATTERN_THEME_REQUEST_PARTS = Pattern.compile("(/resources/(.*)/themes/)([^/]*)/.*");
/** base path for the less JS sources*/
private static final String LESS_PATH = CLASSPATH_PREFIX + "/less/";
/** array of scripts for the rhino less instance */
private static final String[] LESS_JS = {
"less-env.js", "less.js", "less-rtl-plugin.js", "less-api.js"
};
/** keeps the scope of the rhino */
private Scriptable scope;
/** function to parse the less input */
private Function parse;
/** filter configuration */
private FilterConfig config;
/** map for the lastModified timestamps for up-to-date check (library.source.less path --> max timestamp of all less files) */
private Map<String, Long> lastModified = new HashMap<String, Long>();
/** cache for the generated resources (resource path --> content) */
private Map<String, String> cache = new HashMap<String, String>();
/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// keep the filter configuration
this.config = filterConfig;
// initialize the Less Compiler in the Rhino container
try {
// create a new JS execution context
Context context = Context.enter();
context.setOptimizationLevel(9);
context.setLanguageVersion(Context.VERSION_1_7);
// initialize the global context sharing object
Global global = new Global();
global.init(context);
// create the scope
this.scope = context.initStandardObjects(global);
// load the scripts and evaluate them in the Rhino context
ClassLoader loader = LessFilter.class.getClassLoader();
for (String script : LESS_JS) {
URL url = loader.getResource(LESS_PATH + script);
Reader reader = new InputStreamReader(url.openStream(), "UTF-8");
context.evaluateReader(this.scope, reader, script, 1, null);
}
// get environment object and set the resource loader used in less (see less-api.js)
Scriptable env = (Scriptable) this.scope.get("__env", this.scope);
env.put("resourceLoader", env, Context.javaToJS(new ResourceLoader(), this.scope));
// keep the reference to the JS less API
this.parse = (Function) this.scope.get("parse", this.scope);
// exit the context
Context.exit();
} catch (Exception ex) {
String message = "Failed to initialize LESS compiler!";
throw new ServletException(message, ex);
}
} // method: init
/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
@Override
public void destroy() {
this.parse = null;
this.scope = null;
this.config = null;
} // method: destroy
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// make sure that the request/response are http request/response
if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
// determine the path of the request
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getServletPath() + httpRequest.getPathInfo();
// compile the less if required (up-to-date check happens in the compile function)
Matcher m = PATTERN_THEME_REQUEST.matcher(path);
if (m.matches()) {
String prefixPath = m.group(1);
String sourcePath = prefixPath + "/library.source.less";
this.compile(sourcePath, false, false);
}
// return the cached CSS or JSON file and set it as overlay for the resource servlet
if (this.cache.containsKey(path)) {
request.setAttribute("OVERLAY", this.cache.get(path));
}
}
// proceed in the filter chain
chain.doFilter(request, response);
} // method: doFilter
/**
* logs the message prepended by the filter name (copy of {@link GenericServlet#log(String)})
* @param msg the message
*/
private void log(String msg) {
this.config.getServletContext().log(this.config.getFilterName() + ": "+ msg);
} // method: log
/**
* logs the message and <code>Throwable</code> prepended by the filter name (copy of {@link GenericServlet#log(String, Throwable)})
* @param msg the message
* @param t the <code>Throwable</code>
*/
private void log(String msg, Throwable t) {
this.config.getServletContext().log(this.config.getFilterName() + ": "+ msg, t);
} // method: log
/**
* finds the resource for the given path
* @param path path of the resource
* @return URL to the resource or null
* @throws MalformedURLException
*/
private URL findResource(String path) throws MalformedURLException {
// normalize the path (JarURLConnection cannot resolve non-normalized paths)
String normalizedPath = URI.create(path).normalize().toString();
// define the classpath for the classloader lookup
String classPath = CLASSPATH_PREFIX + normalizedPath;
// first lookup the resource in the web context path
URL url = this.config.getServletContext().getResource(normalizedPath);
// lookup the resource in the current threads classloaders
if (url == null) {
url = Thread.currentThread().getContextClassLoader().getResource(classPath);
}
// lookup the resource in the local classloader
if (url == null) {
url = ResourceServlet.class.getClassLoader().getResource(classPath);
}
return url;
} // method: findResource
/**
* determines the max last modified timestamp for the given paths
* @param paths array of paths
* @return max last modified timestamp
*/
private long getMaxLastModified(String[] paths) {
long lastModified = -1;
try {
for (String path : paths) {
URL url = this.findResource(path);
if (url != null) {
URLConnection c = url.openConnection();
c.connect();
lastModified = Math.max(lastModified, c.getLastModified());
}
}
} catch (Exception ex) {
this.log("Failed to determine max last modified timestamp.", ex);
}
return lastModified;
} // method: getMaxLastModified
/**
* compiles the CSS, RTL-CSS and theme parameters as JSON
* @param sourcePath source path
* @param compressCSS true, if CSS should be compressed
* @param compressJSON true if JSON should be compressed
*/
private void compile(String sourcePath, boolean compressCSS, boolean compressJSON) {
try {
Matcher m = PATTERN_THEME_REQUEST_PARTS.matcher(sourcePath);
if (m.matches()) {
// extract the relevant parts from the request path
String prefixPath = m.group(1);
String library = m.group(2);
String libraryName = library.replace('/', '.');
String theme = m.group(3);
String path = prefixPath + theme + "/";
// some info
this.log("Compiling CSS/JSON of library " + libraryName + " for theme " + theme);
URL url = this.findResource(sourcePath);
if (url != null) {
// read the library.source.less
URLConnection conn = url.openConnection();
conn.connect();
// up-to-date check
String resources = this.cache.get(path + "resources");
long lastModified = resources != null ? this.getMaxLastModified(resources.split(";")) : -1;
if (!this.lastModified.containsKey(sourcePath) || this.lastModified.get(sourcePath) < lastModified) {
// read the content
InputStream is = conn.getInputStream();
String input = IOUtils.toString(is, "UTF-8");
IOUtils.closeQuietly(is);
// time measurement begin
long millis = System.currentTimeMillis();
// compile the CSS/JSON
Object result = Context.call(null, this.parse, this.scope, this.scope, new Object[] { input, path, compressCSS, compressJSON, libraryName });
// cache the result
String css = Context.toString(ScriptableObject.getProperty((Scriptable) result, "css"));
this.cache.put(path + "library.css", css);
String rtlCss = Context.toString(ScriptableObject.getProperty((Scriptable) result, "cssRtl"));
this.cache.put(path + "library-RTL.css", rtlCss);
String json = Context.toString(ScriptableObject.getProperty((Scriptable) result, "json"));
this.cache.put(path + "library-parameters.json", json);
resources = Context.toString(ScriptableObject.getProperty((Scriptable) result, "resources"));
this.cache.put(path + "resources", resources);
// log the compile duration
this.log(" => took " + (System.currentTimeMillis() - millis) + "ms");
// store when the resource has been compiled
this.lastModified.put(sourcePath, this.getMaxLastModified(resources.split(";")));
}
} else {
this.log("The less source file cannot be found: " + sourcePath);
}
}
} catch (Exception ex) {
this.log("Failed to compile CSS for " + sourcePath, ex);
}
} // method: compile
/**
* The <code>ResourceLoader</code> is used to load dedicated resources
* requested by Rhino out of the classpath.
*/
public class ResourceLoader {
/**
* loads a resource for the specified path
* @param path path of the resource
*/
public String load(String path) throws IOException {
String content = null;
URL resource = LessFilter.this.findResource(path);
if (resource != null) {
InputStream is = resource.openStream();
content = IOUtils.toString(is, "UTF-8");
IOUtils.closeQuietly(is);
}
return content;
} // method: load
} // inner class: ResourceLoader
} // class: LessFilter
|
package algorithms.dp;
public class EggDroppingProblem {
public int minAttemptsRecursive(int floors, int eggs) {
if (floors == 0 || eggs == 1 || eggs > floors) {
return floors;
} else {
int min = Integer.MAX_VALUE;
for (int i = 1; i <= floors; i++) {
min = Math.min(min, Math.max(1 + minAttemptsRecursive(i - 1, eggs - 1),
1 + minAttemptsRecursive(floors - i, eggs)));
}
return min;
}
}
public int minAttemptsDP(int floors, int eggs) {
int[][] results = new int[eggs + 1][floors + 1];
for (int i = 1; i < results[0].length; i++) {
results[1][i] = i;
}
for (int i = 2; i < (eggs + 1); i++) {
for (int j = 1; j < (floors + 1); j++) {
if (i > j) {
results[i][j] = j;
} else {
int min = Integer.MAX_VALUE;
for (int k = 1; k <= j; k++) {
min = Math.min(min, Math.max((1 + results[i - 1][k - 1]), (1 + results[i][j - k])));
}
results[i][j] = min;
}
}
}
return results[eggs][floors];
}
}
|
package com.sometrik.framework;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class FWImageView extends ImageView implements NativeCommandHandler {
FrameWork frame;
public FWImageView(FrameWork frame) {
super(frame);
this.frame = frame;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
this.setLayoutParams(params);
this.setScaleType(ScaleType.FIT_CENTER);
}
void setImageFromAssets(String filename) {
try {
AssetManager mgr = frame.getAssets();
InputStream stream = mgr.open(filename);
if (stream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(stream);
setImageBitmap(bitmap);
bitmap = null;
}
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onScreenOrientationChange(boolean isLandscape) {
// TODO Auto-generated method stub
}
@Override
public void addChild(View view) {
// TODO Auto-generated method stub
}
@Override
public void addOption(int optionId, String text) {
// TODO Auto-generated method stub
}
@Override
public void addColumn(String text, int columnType) {
// TODO Auto-generated method stub
}
@Override
public void addData(String text, int row, int column, int sheet) {
// TODO Auto-generated method stub
}
@Override
public void setValue(String v) {
}
@Override
public void setValue(int v) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int value, int size) {
// TODO Auto-generated method stub
}
@Override
public void setViewEnabled(Boolean enabled) {
// TODO Auto-generated method stub
}
@Override
public void setViewVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void setStyle(String key, String value) {
final float scale = getContext().getResources().getDisplayMetrics().density;
if (key.equals("gravity")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("bottom")) {
params.gravity = Gravity.BOTTOM;
} else if (value.equals("top")) {
params.gravity = Gravity.TOP;
} else if (value.equals("left")) {
params.gravity = Gravity.LEFT;
} else if (value.equals("right")) {
params.gravity = Gravity.RIGHT;
} else if (value.equals("center")) {
params.gravity = Gravity.CENTER;
} else if (value.equals("center-horizontal")) {
params.gravity = Gravity.CENTER_HORIZONTAL;
} else if (value.equals("center-vertical")) {
params.gravity = Gravity.CENTER_VERTICAL;
}
setLayoutParams(params);
} else if (key.equals("width")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("wrap-content")) {
params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match-parent")) {
params.width = LinearLayout.LayoutParams.MATCH_PARENT;
} else {
int pixels = (int) (Integer.parseInt(value) * scale + 0.5f);
params.width = pixels;
}
setLayoutParams(params);
} else if (key.equals("height")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("wrap-content")) {
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match-parent")) {
params.height = LinearLayout.LayoutParams.MATCH_PARENT;
} else {
int pixels = (int) (Integer.parseInt(value) * scale + 0.5f);
params.height = pixels;
}
setLayoutParams(params);
} else if (key.equals("weight")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.weight = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("padding-top")) {
setPadding(getPaddingLeft(), (int) (Integer.parseInt(value) * scale + 0.5f), getPaddingRight(), getPaddingBottom());
} else if (key.equals("padding-bottom")) {
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), (int) (Integer.parseInt(value) * scale + 0.5f));
} else if (key.equals("padding-left")) {
setPadding((int) (Integer.parseInt(value) * scale + 0.5f), getPaddingTop(), getPaddingRight(), getPaddingBottom());
} else if (key.equals("padding-right")) {
setPadding(getPaddingLeft(), getPaddingTop(), (int) (Integer.parseInt(value) * scale + 0.5f), getPaddingBottom());
} else if (key.equals("scale")) {
if (value.equals("start")) {
setScaleType(ScaleType.FIT_START);
} else if (value.equals("end")) {
setScaleType(ScaleType.FIT_END);
} else if (value.equals("center")) {
setScaleType(ScaleType.FIT_CENTER);
}
} else if (key.equals("margin-right")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.rightMargin = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("margin-left")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.leftMargin = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("margin-top")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.topMargin = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("margin-bottom")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.bottomMargin = Integer.parseInt(value);
setLayoutParams(params);
}
}
@Override
public void setError(boolean hasError, String errorText) {
// TODO Auto-generated method stub
}
@Override
public void clear() {
// TODO Auto-generated method stub
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public int getElementId() {
return getId();
}
@Override
public void setImage(byte[] bytes, int width, int height, Bitmap.Config config) {
System.out.println("SetImage " + bytes.length + " " + getWidth());
// Bitmap map = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
// BitmapFactory.decodeStream(bytes);
// BitmapFactory.de
// InputStream myInputStream = new ByteArrayInputStream(bytes);
// Bitmap map = BitmapFactory.decodeStream(myInputStream);
// if (map == null) {
// System.out.println("shieet");
// } else {
// System.out.println("mappi: " + map.getHeight());
final float scale = getContext().getResources().getDisplayMetrics().density;
// System.out.println("picture scale: " + scale + " " + width + " " + height);
// Bitmap bmp = Bitmap.createBitmap((int)scale * width, (int)scale * height, config);
Bitmap bmp = Bitmap.createBitmap(width, height, config);
// Bitmap bmp = Bitmap.createBitmap((int[])bytes, 32, 32, Bitmap.Config.ARGB_8888)
ByteBuffer buffer = ByteBuffer.wrap(bytes);
bmp.copyPixelsFromBuffer(buffer);
// Bitmap map = Bitmap.create
this.setImageBitmap(bmp);
// map = null;
invalidate();
}
@Override
public void reshape(int size) {
// TODO Auto-generated method stub
}
}
|
package org.icij.extract.core;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.Assert;
public class ExtractingConsumerTest {
private Path getFile() throws URISyntaxException {
return Paths.get(getClass().getResource("/documents/text/plain.txt").toURI());
}
@Test
public void testConsume() throws Throwable {
final Extractor extractor = new Extractor();
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final PrintStream print = new PrintStream(output);
final Spewer spewer = new PrintStreamSpewer(print);
final ExtractingConsumer consumer = new ExtractingConsumer(spewer, extractor, 1);
final Path file = getFile();
consumer.accept(file);
consumer.shutdown();
Assert.assertTrue(consumer.awaitTermination(1, TimeUnit.MINUTES));
Assert.assertEquals("This is a test.\n\n", output.toString());
}
@Test
public void testSetReporter() throws Throwable {
final Spewer spewer = new PrintStreamSpewer(new PrintStream(new ByteArrayOutputStream()));
final ExtractingConsumer consumer = new ExtractingConsumer(spewer, new Extractor(), 1);
final Reporter reporter = new Reporter(new HashMapReport());
final Path file = getFile();
// Assert that no reporter is set by default.
Assert.assertNull(consumer.getReporter());
consumer.setReporter(reporter);
Assert.assertEquals(reporter, consumer.getReporter());
// Assert that the extraction result is reported.
Assert.assertNull(reporter.result(file));
consumer.accept(file);
consumer.shutdown();
Assert.assertTrue(consumer.awaitTermination(1, TimeUnit.MINUTES));
Assert.assertEquals(ExtractionResult.SUCCEEDED, reporter.result(file));
}
}
|
package org.jenkinsci.plugins.p4.client;
import org.jenkinsci.plugins.p4.DefaultEnvironment;
import org.jenkinsci.plugins.p4.SampleServerRule;
import org.jenkinsci.plugins.p4.credentials.P4PasswordImpl;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.util.logging.Logger;
public class WorkflowTest extends DefaultEnvironment {
private static Logger logger = Logger.getLogger(ConnectionTest.class.getName());
private static final String P4ROOT = "tmp-WorkflowTest-p4root";
private static P4PasswordImpl auth;
@ClassRule
public static JenkinsRule jenkins = new JenkinsRule();
@Rule
public SampleServerRule p4d = new SampleServerRule(P4ROOT, VERSION);
@Before
public void buildCredentials() throws Exception {
auth = createCredentials("jenkins", "jenkins", p4d);
}
@Test
public void testWorkflow() throws Exception {
String id = auth.getId();
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "demo");
job.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " p4sync credential: '" + id + "', template: 'test.ws'\n"
+ " p4tag rawLabelDesc: 'TestLabel', rawLabelName: 'jenkins-label'\n"
+ " publisher = [$class: 'SubmitImpl', description: 'Submitted by Jenkins', onlyOnSuccess: false, reopen: false]\n"
+ " buildWorkspace = [$class: 'TemplateWorkspaceImpl', charset: 'none', format: 'jenkins-${NODE_NAME}-${JOB_NAME}', pinHost: false, templateName: 'test.ws']\n"
+ " p4publish credential: '" + id + "', publish: publisher, workspace: buildWorkspace" + " \n"
+ "}"));
WorkflowRun run = jenkins.assertBuildStatusSuccess(job.scheduleBuild2(0));
jenkins.assertLogContains("P4 Task: syncing files at change", run);
jenkins.assertLogContains("P4 Task: tagging build.", run);
jenkins.assertLogContains("P4 Task: reconcile files to changelist.", run);
}
@Test
public void testWorkflowEnv() throws Exception {
String id = auth.getId();
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "workflowEnv");
job.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " p4sync credential: '" + id + "', template: 'test.ws'\n"
+ " println \"P4_CHANGELIST: ${env.P4_CHANGELIST}\"\n"
+ "}"));
WorkflowRun run = jenkins.assertBuildStatusSuccess(job.scheduleBuild2(0));
jenkins.assertLogContains("P4 Task: syncing files at change", run);
jenkins.assertLogContains("P4_CHANGELIST: 40", run);
}
@Test
public void testManualP4Sync() throws Exception {
String id = auth.getId();
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "manualP4Sync");
job.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " def workspace = [$class: 'ManualWorkspaceImpl',\n"
+ " name: 'jenkins-${NODE_NAME}-${JOB_NAME}',\n"
+ " spec: [view: '//depot/... //jenkins-${NODE_NAME}-${JOB_NAME}/...']]\n"
+ " def syncOptions = [$class: 'org.jenkinsci.plugins.p4.populate.SyncOnlyImpl',\n"
+ " revert:true, have:true, modtime:true]\n"
+ " p4sync workspace:workspace, credential: '" + id + "', populate: syncOptions\n"
+ "}"));
WorkflowRun run = jenkins.assertBuildStatusSuccess(job.scheduleBuild2(0));
jenkins.assertLogContains("P4 Task: syncing files at change", run);
}
@Test
public void testP4GroovyConnectAndSync() throws Exception {
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "p4groovy");
job.setDefinition(new CpsFlowDefinition(""
+ "node() {\n"
+ " ws = [$class: 'StreamWorkspaceImpl', charset: 'none', format: 'jenkins-${NODE_NAME}-${JOB_NAME}', pinHost: false, streamName: '//stream/main']\n"
+ " p4 = p4(credential: '" + auth.getId() + "', workspace: ws)\n"
+ " p4.run('sync', '
+ "}"));
job.save();
WorkflowRun run = job.scheduleBuild2(0).get();
jenkins.assertLogContains("p4 sync //...", run);
jenkins.assertLogContains("totalFileCount 10", run);
}
@Test
public void testP4GroovySpecEdit() throws Exception {
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "p4groovy.spec");
job.setDefinition(new CpsFlowDefinition(""
+ "node() {\n"
+ " ws = [$class: 'StreamWorkspaceImpl', charset: 'none', format: 'jenkins-${NODE_NAME}-${JOB_NAME}', pinHost: false, streamName: '//stream/main']\n"
+ " p4 = p4(credential: '" + auth.getId() + "', workspace: ws)\n"
+ " clientName = p4.getClientName();\n"
+ " client = p4.fetch('client', clientName)\n"
+ " echo \"Client: ${client}\""
+ " client.put('Description', 'foo')"
+ " p4.save('client', client)"
+ "}"));
job.save();
WorkflowRun run = job.scheduleBuild2(0).get();
jenkins.assertLogContains("p4 client -o jenkins-master-p4groovy.spec", run);
}
}
|
package cn.cerc.mis.core;
import java.util.Map;
import java.util.Objects;
import cn.cerc.db.core.DataRow;
import cn.cerc.db.core.DataSet;
import cn.cerc.db.core.IHandle;
import cn.cerc.db.core.ISession;
import cn.cerc.mis.client.ServiceExecuteException;
import cn.cerc.mis.client.ServiceSign;
public class ServiceQuery implements IHandle {
private ServiceSign service;
private DataSet dataIn;
private DataSet dataOut;
private ISession session;
public static ServiceQuery open(IHandle handle, ServiceSign service, DataSet dataIn) {
return new ServiceQuery(handle, service).call(dataIn);
}
public static ServiceQuery open(IHandle handle, ServiceSign service, DataRow headIn) {
DataSet dataIn = new DataSet();
dataIn.head().copyValues(headIn);
return new ServiceQuery(handle, service).call(dataIn);
}
public static ServiceQuery open(IHandle handle, ServiceSign service, Map<String, Object> headIn) {
DataSet dataIn = new DataSet();
headIn.forEach((key, value) -> dataIn.head().setValue(key, value));
return new ServiceQuery(handle, service).call(dataIn);
}
public ServiceQuery(IHandle handle) {
this.setSession(handle.getSession());
}
public ServiceQuery(IHandle handle, ServiceSign service) {
this(handle);
this.service = service;
}
public ServiceQuery call(DataSet dataIn) {
this.dataIn = dataIn;
this.dataOut = this.service.call(this, dataIn);
return this;
}
public ServiceQuery setService(ServiceSign service) {
this.service = service;
return this;
}
public boolean isOk() {
Objects.requireNonNull(dataOut);
return dataOut.state() > 0;
}
public boolean isOkElseThrow() throws ServiceExecuteException {
if (!isOk())
throw new ServiceExecuteException(dataOut.message());
return true;
}
public boolean isFail() {
Objects.requireNonNull(dataOut);
return dataOut.state() <= 0;
}
public DataSet getDataOutElseThrow() throws ServiceExecuteException {
Objects.requireNonNull(dataOut);
if (dataOut.state() <= 0)
throw new ServiceExecuteException(dataOut.message());
return dataOut;
}
public DataRow getHeadOutElseThrow() throws ServiceExecuteException {
Objects.requireNonNull(dataOut);
if (dataOut.state() <= 0)
throw new ServiceExecuteException(dataOut.message());
return dataOut.head();
}
public final DataSet dataIn() {
if (this.dataIn == null)
this.dataIn = new DataSet();
return dataIn;
}
public final DataSet dataOut() {
if (this.dataOut == null)
this.dataOut = new DataSet();
return dataOut;
}
@Override
public ISession getSession() {
return session;
}
@Override
public void setSession(ISession session) {
this.session = session;
}
public final String serviceId() {
return service.id();
}
}
|
package leola.lang.sql;
import java.sql.Connection;
import java.sql.Savepoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import leola.vm.Leola;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoNativeClass;
import leola.vm.types.LeoObject;
/**
* Represents a DatabaseConnection
* @author Tony
*
*/
public class Conn {
/**
* SQL connection
*/
private Connection sqlConn;
private Leola runtime;
private Map<String, Savepoint> savepoints;
private LeoObject thisObject;
/**
* @param sqlConn
*/
public Conn(Leola runtime, Connection sqlConn) throws Exception {
super();
this.runtime = runtime;
this.sqlConn = sqlConn;
this.thisObject = new LeoNativeClass(this);
this.sqlConn.setAutoCommit(false);
this.savepoints = new ConcurrentHashMap<String, Savepoint>();
}
/**
* @return the sqlConn
*/
public Connection jdbc() {
return sqlConn;
}
public boolean isOpen() throws Exception {
return ! this.sqlConn.isClosed();
}
public void close() throws Exception {
if ( ! this.sqlConn.isClosed() ) {
this.sqlConn.close();
}
}
public void commit() throws Exception {
this.sqlConn.commit();
}
public void rollback() throws Exception {
this.sqlConn.rollback();
}
public void rollbackTo(LeoObject savepoint) throws Exception {
String sp = savepoint.toString();
if ( ! this.savepoints.containsKey(sp) ) {
throw new IllegalArgumentException("No savepoint defined for: " + sp);
}
this.sqlConn.rollback(this.savepoints.get(sp));
}
public void savepoint(LeoObject savepoint) throws Exception {
String sp = savepoint.toString();
this.savepoints.put(sp, this.sqlConn.setSavepoint(sp));
}
public void releaseSavepoint(LeoObject savepoint) throws Exception {
String sp = savepoint.toString();
if ( ! this.savepoints.containsKey(sp) ) {
throw new IllegalArgumentException("No savepoint defined for: " + sp);
}
this.sqlConn.releaseSavepoint(this.savepoints.get(sp));
}
public Query query(LeoObject sql) {
String query = sql.toString();
ParsedSql parsedSql = SqlParameterParser.parseSqlStatement(query);
return new Query(this.runtime, this.sqlConn, parsedSql);
}
/**
* Streams the response.
*
* @param function
* @param sql
* @param params
* @param pageSize
* @throws Exception
*/
public void streamExecute(LeoObject function, LeoObject sql, LeoMap params, Integer pageSize) throws Exception {
Query aQuery = query(sql);
aQuery.params(params);
Savepoint savepoint = this.sqlConn.setSavepoint();
try {
aQuery.streamExecute(function, pageSize);
this.sqlConn.commit();
}
catch(Exception t) {
this.sqlConn.rollback(savepoint);
throw t;
}
finally {
aQuery.close();
}
}
/**
* Executes a read-only query.
*
* @param sql
* @param params
* @return the result set
* @throws Exception
*/
public LeoObject execute(LeoObject sql, LeoMap params, Integer maxResults) throws Exception {
Query aQuery = query(sql);
aQuery.params(params);
if(maxResults != null) {
aQuery.setMaxResults(maxResults);
}
LeoObject result = null;
Savepoint savepoint = this.sqlConn.setSavepoint();
try {
result = aQuery.execute();
this.sqlConn.commit();
}
catch(Exception t) {
this.sqlConn.rollback(savepoint);
throw t;
}
finally {
aQuery.close();
}
return result;
}
/**
* Executes a update statement
* @param sql
* @param params
* @return the number of rows updated
* @throws Exception
*/
public int update(LeoObject sql, LeoMap params) throws Exception {
Query aQuery = query(sql);
aQuery.params(params);
int result = 0;
Savepoint savepoint = this.sqlConn.setSavepoint();
try {
result = aQuery.update();
this.sqlConn.commit();
}
catch(Exception t) {
this.sqlConn.rollback(savepoint);
throw t;
}
finally {
aQuery.close();
}
return result;
}
/**
* Executes a block of code around a transaction.
*
* @param interpreter
* @param func
* @return
* @throws Exception
*/
public LeoObject transaction(LeoObject func) throws Exception {
LeoObject result = null;
Savepoint savepoint = this.sqlConn.setSavepoint();
try {
result = runtime.execute(func, this.thisObject);
this.sqlConn.commit();
}
catch(Exception t) {
this.sqlConn.rollback(savepoint);
throw t;
}
return result;
}
}
|
package cn.cerc.ui.columns;
import cn.cerc.mis.core.IForm;
import cn.cerc.ui.core.HtmlWriter;
import cn.cerc.ui.core.IReadonlyOwner;
import cn.cerc.ui.core.UIOriginComponent;
import cn.cerc.ui.parts.UIComponent;
import cn.cerc.ui.vcl.UIImage;
import cn.cerc.ui.vcl.UIInput;
import cn.cerc.ui.vcl.UILabel;
public class ImageColumn extends AbstractColumn implements IDataColumn {
private UIInput input = new UIInput(this);
private UIComponent helper;
private boolean readonly;
private String width;
private String height;
public ImageColumn(UIComponent owner) {
super(owner);
if (owner instanceof IReadonlyOwner) {
this.setReadonly(((IReadonlyOwner) owner).isReadonly());
}
}
public ImageColumn(UIComponent owner, String name, String code) {
super(owner);
this.setCode(code).setName(name);
if (owner instanceof IReadonlyOwner) {
this.setReadonly(((IReadonlyOwner) owner).isReadonly());
}
input.setName(code);
}
public ImageColumn(UIComponent owner, String name, String code, int width) {
super(owner);
this.setCode(code).setName(name).setSpaceWidth(width);
if (owner instanceof IReadonlyOwner) {
this.setReadonly(((IReadonlyOwner) owner).isReadonly());
}
input.setName(code);
}
@Override
public void outputCell(HtmlWriter html) {
if (this.getOrigin() instanceof IForm) {
IForm form = (IForm) this.getOrigin();
if (form.getClient().isPhone()) {
outputCellPhone(html);
return;
}
}
outputCellWeb(html);
}
private void outputCellWeb(HtmlWriter html) {
String url = getRecord().getString(this.getCode());
if (this.readonly) {
UIImage img = new UIImage();
img.setStaticPath("");
img.setSrc(url);
img.setWidth(this.getWidth());
img.setHeight(this.getHeight());
img.output(html);
} else {
input.setValue(url);
input.output(html);
}
}
private void outputCellPhone(HtmlWriter html) {
String text = getRecord().getString(this.getCode());
if (this.readonly) {
html.print(getName() + "");
UIImage img = new UIImage();
img.setStaticPath("");
img.setSrc(text);
img.setWidth(this.getWidth());
img.setHeight(this.getHeight());
img.output(html);
} else {
UILabel label = new UILabel();
label.setFocusTarget(this.getCode());
label.setText(getName() + "");
label.output(html);
input.setId(getCode());
input.setReadonly(readonly);
input.setValue(text);
input.output(html);
}
}
@Override
public void outputLine(HtmlWriter html) {
String text = getRecord().getString(this.getCode());
if (!this.isHidden()) {
UILabel label = new UILabel();
label.setFocusTarget(this.getCode());
label.setText(getName() + "");
label.output(html);
}
input.setId(getId());
input.setReadonly(readonly);
input.setValue(text);
input.output(html);
if (!this.isHidden()) {
html.print("<span>");
if (this.helper != null)
helper.output(html);
html.println("</span>");
}
}
public UIComponent getHelper() {
if (helper != null)
helper = new UIOriginComponent(this);
return helper;
}
@Override
public boolean isReadonly() {
return readonly;
}
@Override
public ImageColumn setReadonly(boolean readonly) {
this.readonly = readonly;
return this;
}
public ImageColumn setPlaceholder(String placeholder) {
input.setPlaceholder(placeholder);
return this;
}
public String getPlaceholder() {
return input.getPlaceholder();
}
@Override
public boolean isHidden() {
return input.isHidden();
}
@Override
public ImageColumn setHidden(boolean hidden) {
input.setHidden(hidden);
return this;
}
public ImageColumn setInputType(String inputType) {
input.setInputType(inputType);
return this;
}
public String getHeight() {
return height;
}
public ImageColumn setHeight(String height) {
this.height = height;
return this;
}
public String getWidth() {
return width;
}
public ImageColumn setWidth(String width) {
this.width = width;
return this;
}
}
|
package org.testeditor.fixture.swt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
/**
* Module tests for the SWTBotFixture.
*
*/
public class SWTBotFixtureTest {
@Test
public void testMarkForRunningApplication() throws Exception {
final Set<String> monitor = new HashSet<String>();
Runnable firstLaunch = new Runnable() {
@Override
public void run() {
try {
SwtBotFixture swtBotFixture = new SwtBotFixture();
monitor.add("first launched");
swtBotFixture.waitUntilPreviousLaunchIsFinished();
Thread.sleep(30);
monitor.add("first finished");
swtBotFixture.markApplicationStopped();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Runnable secondLaunch = new Runnable() {
@Override
public void run() {
try {
monitor.add("second launched");
SwtBotFixture swtBotFixture = new SwtBotFixture();
swtBotFixture.waitUntilPreviousLaunchIsFinished();
assertTrue(monitor.contains("first finished"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(firstLaunch).start();
new Thread(secondLaunch).start();
Thread.sleep(10);
assertEquals(2, monitor.size());
assertTrue(monitor.contains("first launched"));
assertTrue(monitor.contains("second launched"));
Thread.sleep(30);
assertEquals(3, monitor.size());
assertTrue(monitor.contains("first finished"));
}
/**
* Tests the tear Down operation.
*/
@Test
public void testTearDown() {
final Set<String> monitor = new HashSet<String>();
SwtBotFixture swtBotFixture = new SwtBotFixture() {
@Override
public void stopApplication() {
monitor.add("stop");
}
};
swtBotFixture.stopApplication();
assertTrue(monitor.contains("stop"));
}
}
|
package org.utplsql.cli;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* System tests for Code Coverage Reporter
*
* @author pesse
*/
public class RunCommandCoverageReporterIT {
private static final Pattern REGEX_COVERAGE_TITLE = Pattern.compile("<a href=\"[a-zA-Z0-9#]+\" class=\"src_link\" title=\"[a-zA-Z\\._]+\">([a-zA-Z0-9\\._]+)<\\/a>");
private Set<Path> tempPaths;
private void addTempPath(Path path) {
tempPaths.add(path);
}
private String getTempCoverageFileName(int counter) {
return "tmpCoverage_" + String.valueOf(System.currentTimeMillis()) + "_" + String.valueOf(counter) + ".html";
}
/**
* Returns a random filename which does not yet exist on the local path
*
* @return
*/
private Path getTempCoverageFilePath() {
int i = 1;
Path p = Paths.get(getTempCoverageFileName(i));
while ((Files.exists(p) || tempPaths.contains(p)) && i < 100)
p = Paths.get(getTempCoverageFileName(i++));
if (i >= 100)
throw new IllegalStateException("Could not get temporary file for coverage output");
addTempPath(p);
addTempPath(Paths.get(p.toString()+"_assets"));
return p;
}
/**
* Checks Coverage HTML Output if a given packageName is listed
*
* @param content
* @param packageName
* @return
*/
private boolean hasCoverageListed(String content, String packageName) {
Matcher m = REGEX_COVERAGE_TITLE.matcher(content);
while (m.find()) {
if (packageName.equals(m.group(1)))
return true;
}
return false;
}
@BeforeEach
public void setupTest() {
tempPaths = new HashSet<>();
}
@Test
public void run_CodeCoverageWithIncludeAndExclude() throws Exception {
Path coveragePath = getTempCoverageFilePath();
RunCommand runCmd = RunCommandTestHelper.createRunCommand(RunCommandTestHelper.getConnectionString(),
"-f=ut_coverage_html_reporter", "-o=" + coveragePath, "-s", "-exclude=app.award_bonus,app.betwnstr");
int result = runCmd.run();
String content = new String(Files.readAllBytes(coveragePath));
assertEquals(true, hasCoverageListed(content, "app.remove_rooms_by_name"));
assertEquals(false, hasCoverageListed(content, "app.award_bonus"));
assertEquals(false, hasCoverageListed(content, "app.betwnstr"));
}
@Test
public void coverageReporterWriteAssetsToOutput() throws Exception {
Path coveragePath = getTempCoverageFilePath();
Path coverageAssetsPath = Paths.get(coveragePath.toString() + "_assets");
RunCommand runCmd = RunCommandTestHelper.createRunCommand(RunCommandTestHelper.getConnectionString(),
"-f=ut_coverage_html_reporter", "-o=" + coveragePath, "-s");
runCmd.run();
// Run twice to test overriding of assets
runCmd = RunCommandTestHelper.createRunCommand(RunCommandTestHelper.getConnectionString(),
"-f=ut_coverage_html_reporter", "-o=" + coveragePath, "-s");
runCmd.run();
// Check application file exists
File applicationJs = coverageAssetsPath.resolve(Paths.get("application.js")).toFile();
assertTrue(applicationJs.exists());
// Check correct script-part in HTML source exists
String content = new Scanner(coveragePath).useDelimiter("\\Z").next();
assertTrue(content.contains("<script src='" + coverageAssetsPath.toString() + "/application.js' type='text/javascript'>"));
// Check correct title exists
assertTrue(content.contains("<title>Code coverage</title>"));
}
@AfterEach
public void deleteTempFiles() {
tempPaths.forEach(p -> deleteDir(p.toFile()));
}
void deleteDir(File file) {
if (file.exists()) {
File[] contents = file.listFiles();
if (contents != null) {
for (File f : contents) {
deleteDir(f);
}
}
file.delete();
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.swows.producer;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.Node;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.Timer;
import java.util.List;
import java.util.TimerTask;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import org.swows.xmlinrdf.DomEncoder;
import org.swows.graph.DynamicChangingGraph;
import org.swows.runnable.LocalTimer;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.sparql.core.DatasetGraph;
import java.lang.Thread;
import java.lang.InterruptedException;
import org.swows.util.GraphUtils;
import org.swows.vocabulary.SPINX;
import org.swows.graph.events.DynamicGraph;
import org.swows.graph.events.DynamicDataset;
public class TwitterProducer extends GraphProducer {
private Document doc = null;
private List<Status> statuses = null;
private Element tweet = null;
private TransformerFactory transformerFactory = TransformerFactory.newInstance();
private Transformer transformer = null;
private DOMSource source;
StreamResult fileXml = null;
Date date = null;
private Element twitter, tweetUser, tweetDate, tweetText;
private int tweetsLength;
private DynamicChangingGraph dynamicChangingGraph = null;
private String twitterUsername;
private int tweetNumber;
private Graph graph;
public TwitterProducer(Graph conf, Node confRoot, ProducerMap map) {
//public static Node getSingleValueProperty(Graph graph, Node subject, Node predicate)
Node twitterUsernameNode = GraphUtils.getSingleValueProperty(conf, confRoot, SPINX.twitterUsername.asNode());
if (twitterUsernameNode != null) {
twitterUsername = twitterUsernameNode.getLiteralLexicalForm();
}
Node tweetNumberNode = GraphUtils.getSingleValueProperty(conf, confRoot, SPINX.tweetNumber.asNode());
if (tweetNumberNode != null) {
tweetNumber = Integer.parseInt(tweetNumberNode.getLiteralLexicalForm());
}
}
public TwitterProducer(String username, int tweetNumber) {
this.twitterUsername = username;
this.tweetNumber = tweetNumber;
setup();
}
// public static void main(String[] args) { //PER FARE PROVE
// Thread thread = new Thread(new TwitterProducer());
// thread.start();
// new TwitterProducer("DarioLap", 5);
//setup();
//se grafo = null, chiama setup
@Override
public DynamicGraph createGraph(DynamicDataset inputDataset) {
if (dynamicChangingGraph == null) {
setup();
}
return dynamicChangingGraph;
}
public boolean dependsFrom(Producer producer) {
return false;
}
//setup
public void setup() {
//final Document doc = null;
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
}
twitter = doc.createElement("Twitter");
doc.appendChild(twitter);
// twitter.setAttribute(twitterUsername, twitterUsername);
Attr tweetNumberAttr = doc.createAttribute("tweetNumber");
tweetNumberAttr.setValue(Integer.toString(tweetNumber));
twitter.setAttributeNode(tweetNumberAttr);
System.out.println("\n\n
final Twitter twitterElement = new TwitterFactory().getInstance();
final String selectedQuery = twitterUsername;
//final List<Status> statuses = null;
try {
statuses = twitterElement.getUserTimeline(selectedQuery);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
if (statuses.size() > 0) {
date = statuses.get(0).getCreatedAt();
}
//Vector<String> tweetList = new Vector<String>();
//tweetsLength = statuses.size();
if (statuses.size() > tweetNumber) {
tweetsLength = tweetNumber;
} else {
tweetsLength = statuses.size();
}
for (int i = 0; i < tweetsLength; i++) {
//for (Status tweets : statuses) {
System.out.println("@" + statuses.get(i).getUser().getScreenName() + " - " + statuses.get(i).getText());
// System.out.println("@" + tweetList.get(i) + " - " + tweetList.get(i + 1));
tweet = doc.createElement("tweet");
twitter.appendChild(tweet);
Attr tweetId = doc.createAttribute("id");
tweetId.setValue(Integer.toString(i));
tweet.setAttributeNode(tweetId);
// tweetUser = doc.createElement("username");
// tweetUser.appendChild(doc.createTextNode(statuses.get(i).getUser().getScreenName()));
// tweet.appendChild(tweetUser);
// tweetDate = doc.createElement("date");
// tweetDate.appendChild(doc.createTextNode(statuses.get(i).getCreatedAt().toString()));
// tweet.appendChild(tweetDate);
tweetText = doc.createElement("text");
tweetText.appendChild(doc.createTextNode(statuses.get(i).getText()));
tweet.appendChild(tweetText);
/*
* Attr data = doc.createAttribute("Data");
* data.appendChild(doc.createTextNode(statuses.get(i).getCreatedAt().toString()));
* tweet.setAttributeNode(data);
*/
//tweet.appendChild(doc.createTextNode(statuses.get(i).getText()));
//twitter.appendChild(doc.createElement("tweet"));
}
// Document docRet = null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerException te) {
te.printStackTrace();
}
source = new DOMSource(doc);
try {
fileXml = new StreamResult(new FileOutputStream("situazioneIniziale.xml"));
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
try {
transformer = transformerFactory.newTransformer();
transformer.transform(source, fileXml);
} catch (TransformerException te) {
te.printStackTrace();
}
graph = DomEncoder.encode(doc);
ModelFactory.createModelForGraph(graph).write(System.out);
//ModelFactory.createModelForGraph(graph).
dynamicChangingGraph = new DynamicChangingGraph(graph);
//LocalTimer localTimer = new LocalTimer();
//localTimer.get().schedule(null, 10000, 10000);
//Timer timer = new Timer();
LocalTimer localTimer = new LocalTimer();
localTimer.get().schedule(new TimerTask() {
public void run() {
try {
statuses = twitterElement.getUserTimeline(selectedQuery);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
if (statuses.size() > tweetNumber) {
tweetsLength = tweetNumber;
} else {
tweetsLength = statuses.size();
}
doc.removeChild(twitter);
twitter = doc.createElement("Twitter");
// twitter.setAttributeNode(tweetNumberAttr);
doc.appendChild(twitter);
for (int i = 0; i < tweetsLength; i++) {
// for (Status tweets : statuses) {
if (statuses.get(0).getCreatedAt().after(date)) {
System.out.println("@" + statuses.get(i).getUser().getScreenName() + " - " + statuses.get(i).getText());
// System.out.println("@" + tweetList.get(i) + " - " + tweetList.get(i + 1));
tweet = doc.createElement("tweet");
twitter.appendChild(tweet);
Attr tweetId = doc.createAttribute("id");
tweetId.setValue(Integer.toString(i));
tweet.setAttributeNode(tweetId);
// tweetUser = doc.createElement("username");
// tweetUser.appendChild(doc.createTextNode(statuses.get(i).getUser().getScreenName()));
// tweet.appendChild(tweetUser);
// tweetDate = doc.createElement("date");
// tweetDate.appendChild(doc.createTextNode(statuses.get(i).getCreatedAt().toString()));
// tweet.appendChild(tweetDate);
tweetText = doc.createElement("tweetText");
tweetText.appendChild(doc.createTextNode(statuses.get(i).getText()));
tweet.appendChild(tweetText);
transformerFactory = TransformerFactory.newInstance();
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerException te) {
te.printStackTrace();
}
source = new DOMSource(doc);
fileXml = null;
try {
fileXml = new StreamResult(new FileOutputStream("situazioneAggiornata.xml"));
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
try {
transformer = transformerFactory.newTransformer();
transformer.transform(source, fileXml);
} catch (TransformerException te) {
te.printStackTrace();
}
System.out.println("NUOVO TWEET: @" + statuses.get(i).getUser().getScreenName() + " - " + statuses.get(i).getText());
Graph graphUpdate = DomEncoder.encode(doc);
ModelFactory.createModelForGraph(graphUpdate).write(System.out);
//DynamicChangingGraph.setBaseGraph(graphUpdate, graph);
dynamicChangingGraph.setBaseGraph(graphUpdate);
// dynamicChangingGraph = new DynamicChangingGraph (graphUpdate);
} else {
break;
}
}
if (statuses.get(0).getCreatedAt().after(date)) {
date = statuses.get(0).getCreatedAt();
}
try {
Thread.sleep(25000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}, 1000, 25000);
}
}
|
package seedu.jimi.testutil;
import seedu.jimi.commons.exceptions.IllegalValueException;
import seedu.jimi.model.TaskBook;
import seedu.jimi.model.task.*;
public class TypicalTestFloatingTasks {
public static TestFloatingTask water, ideas, car, airport, lunch, flight, beach, night, dream;
public TypicalTestFloatingTasks() {
try {
water = new TaskBuilder().withName("add water").withTags("not urgent").build();
ideas = new TaskBuilder().withName("brainstorm ideas").withTags("project", "task").build();
car = new TaskBuilder().withName("catch a car").build();
airport = new TaskBuilder().withName("drive to airport").build();
lunch = new TaskBuilder().withName("eat lunch").build();
flight = new TaskBuilder().withName("fly to spain").build();
beach = new TaskBuilder().withName("go to the beach").build();
//Manually added
night = new TaskBuilder().withName("have a nice night").build();
dream = new TaskBuilder().withName("into a dream").build();
} catch (IllegalValueException e) {
e.printStackTrace();
assert false : "not possible";
}
}
public static void loadTaskBookWithSampleData(TaskBook ab) {
try {
ab.addFloatingTask(new FloatingTask(water));
ab.addFloatingTask(new FloatingTask(ideas));
ab.addFloatingTask(new FloatingTask(car));
ab.addFloatingTask(new FloatingTask(airport));
ab.addFloatingTask(new FloatingTask(lunch));
ab.addFloatingTask(new FloatingTask(flight));
ab.addFloatingTask(new FloatingTask(beach));
} catch (UniqueTaskList.DuplicateTaskException e) {
assert false : "not possible";
}
}
public TestFloatingTask[] getTypicalTasks() {
return new TestFloatingTask[]{water, ideas, car, airport, lunch, flight, beach};
}
public TaskBook getTypicalTaskBook(){
TaskBook ab = new TaskBook();
loadTaskBookWithSampleData(ab);
return ab;
}
}
|
package org.neo4j.kernel.ha;
import java.util.EnumMap;
import java.util.Map;
import org.neo4j.com.ComException;
import org.neo4j.helpers.Pair;
import org.neo4j.kernel.CommonFactories;
import org.neo4j.kernel.IdGeneratorFactory;
import org.neo4j.kernel.IdType;
import org.neo4j.kernel.ha.zookeeper.Machine;
import org.neo4j.kernel.ha.zookeeper.ZooKeeperException;
import org.neo4j.kernel.impl.nioneo.store.IdGenerator;
import org.neo4j.kernel.impl.nioneo.store.IdRange;
import org.neo4j.kernel.impl.nioneo.store.NeoStore;
public class SlaveIdGenerator implements IdGenerator
{
private static final long VALUE_REPRESENTING_NULL = -1;
public static class SlaveIdGeneratorFactory implements IdGeneratorFactory
{
private final Broker broker;
private final ResponseReceiver receiver;
private final Map<IdType, SlaveIdGenerator> generators =
new EnumMap<IdType, SlaveIdGenerator>( IdType.class );
private final IdGeneratorFactory localFactory =
CommonFactories.defaultIdGeneratorFactory();
public SlaveIdGeneratorFactory( Broker broker, ResponseReceiver receiver )
{
this.broker = broker;
this.receiver = receiver;
}
public IdGenerator open( String fileName, int grabSize, IdType idType, long highestIdInUse )
{
IdGenerator localIdGenerator = localFactory.open( fileName, grabSize,
idType, highestIdInUse );
localIdGenerator.clearFreeIds();
SlaveIdGenerator generator = new SlaveIdGenerator( idType, highestIdInUse, broker,
receiver, localIdGenerator );
generators.put( idType, generator );
return generator;
}
public void create( String fileName )
{
localFactory.create( fileName );
}
public IdGenerator get( IdType idType )
{
return generators.get( idType );
}
public void updateIdGenerators( NeoStore store )
{
store.updateIdGenerators();
}
public void forgetIdAllocationsFromMaster()
{
for ( SlaveIdGenerator idGenerator : generators.values() )
{
idGenerator.forgetIdAllocationFromMaster();
}
}
};
private final Broker broker;
private final ResponseReceiver receiver;
private volatile long highestIdInUse;
private volatile long defragCount;
private volatile IdRangeIterator idQueue = EMPTY_ID_RANGE_ITERATOR;
private volatile int allocationMaster;
private final IdType idType;
private final IdGenerator localIdGenerator;
public SlaveIdGenerator( IdType idType, long highestIdInUse, Broker broker,
ResponseReceiver receiver, IdGenerator localIdGenerator )
{
this.idType = idType;
this.broker = broker;
this.receiver = receiver;
this.localIdGenerator = localIdGenerator;
}
private void forgetIdAllocationFromMaster()
{
this.idQueue = EMPTY_ID_RANGE_ITERATOR;
}
public void close()
{
this.localIdGenerator.close();
}
public void freeId( long id )
{
}
public long getHighId()
{
return Math.max( this.localIdGenerator.getHighId(), highestIdInUse );
}
public long getNumberOfIdsInUse()
{
return Math.max( this.localIdGenerator.getNumberOfIdsInUse(), highestIdInUse-defragCount );
}
public synchronized long nextId()
{
try
{
long nextId = nextLocalId();
Pair<Master, Machine> master = broker.getMaster();
if ( nextId == VALUE_REPRESENTING_NULL )
{
// If we dont have anymore grabbed ids from master, grab a bunch
IdAllocation allocation = master.first().allocateIds( idType ).response();
allocationMaster = master.other().getMachineId();
nextId = storeLocally( allocation );
}
else
{
assert master.other().getMachineId() == allocationMaster;
}
return nextId;
}
catch ( ZooKeeperException e )
{
receiver.newMaster( null, e );
throw e;
}
catch ( ComException e )
{
receiver.newMaster( null, e );
throw e;
}
}
public IdRange nextIdBatch( int size )
{
throw new UnsupportedOperationException( "Should never be called" );
}
private long storeLocally( IdAllocation allocation )
{
this.highestIdInUse = allocation.getHighestIdInUse();
this.defragCount = allocation.getDefragCount();
this.idQueue = new IdRangeIterator( allocation.getIdRange() );
updateLocalIdGenerator();
return idQueue.next();
}
private void updateLocalIdGenerator()
{
long localHighId = this.localIdGenerator.getHighId();
if ( this.highestIdInUse > localHighId )
{
this.localIdGenerator.setHighId( this.highestIdInUse );
}
}
private long nextLocalId()
{
return this.idQueue.next();
}
public void setHighId( long id )
{
this.localIdGenerator.setHighId( id );
}
public long getDefragCount()
{
return this.defragCount;
}
@Override
public void clearFreeIds()
{
}
private static class IdRangeIterator
{
private int position = 0;
private final long[] defrag;
private final long start;
private final int length;
IdRangeIterator( IdRange idRange )
{
this.defrag = idRange.getDefragIds();
this.start = idRange.getRangeStart();
this.length = idRange.getRangeLength();
}
long next()
{
try
{
if ( position < defrag.length )
{
return defrag[position];
}
else
{
int offset = position - defrag.length;
return ( offset < length ) ? ( start + offset ) : VALUE_REPRESENTING_NULL;
}
}
finally
{
++position;
}
}
}
private static IdRangeIterator EMPTY_ID_RANGE_ITERATOR =
new IdRangeIterator( new IdRange( new long[0], 0, 0 ) )
{
@Override
long next()
{
return VALUE_REPRESENTING_NULL;
};
};
}
|
package org.zstack.image;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.Platform;
import org.zstack.core.asyncbatch.AsyncBatchRunner;
import org.zstack.core.asyncbatch.LoopAsyncBatch;
import org.zstack.core.cloudbus.*;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.config.GlobalConfig;
import org.zstack.core.config.GlobalConfigUpdateExtensionPoint;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.defer.Defer;
import org.zstack.core.defer.Deferred;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.thread.CancelablePeriodicTask;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.AbstractService;
import org.zstack.header.core.AsyncLatch;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.ErrorCodeList;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.identity.*;
import org.zstack.header.image.*;
import org.zstack.header.image.APICreateRootVolumeTemplateFromVolumeSnapshotEvent.Failure;
import org.zstack.header.image.ImageConstant.ImageMediaType;
import org.zstack.header.image.ImageDeletionPolicyManager.ImageDeletionPolicy;
import org.zstack.header.managementnode.ManagementNodeReadyExtensionPoint;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.message.NeedQuotaCheckMessage;
import org.zstack.header.rest.RESTFacade;
import org.zstack.header.search.SearchOp;
import org.zstack.header.storage.backup.*;
import org.zstack.header.storage.primary.PrimaryStorageVO;
import org.zstack.header.storage.primary.PrimaryStorageVO_;
import org.zstack.header.storage.snapshot.*;
import org.zstack.header.vm.CreateTemplateFromVmRootVolumeMsg;
import org.zstack.header.vm.CreateTemplateFromVmRootVolumeReply;
import org.zstack.header.vm.VmInstanceConstant;
import org.zstack.header.volume.*;
import org.zstack.identity.AccountManager;
import org.zstack.identity.QuotaUtil;
import org.zstack.search.SearchQuery;
import org.zstack.tag.TagManager;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.ObjectUtils;
import org.zstack.utils.RunOnce;
import org.zstack.utils.Utils;
import org.zstack.utils.data.SizeUnit;
import org.zstack.utils.function.ForEachFunction;
import org.zstack.utils.function.Function;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static org.zstack.utils.CollectionDSL.list;
public class ImageManagerImpl extends AbstractService implements ImageManager, ManagementNodeReadyExtensionPoint,
ReportQuotaExtensionPoint, ResourceOwnerPreChangeExtensionPoint {
private static final CLogger logger = Utils.getLogger(ImageManagerImpl.class);
@Autowired
private CloudBus bus;
@Autowired
private PluginRegistry pluginRgty;
@Autowired
private DatabaseFacade dbf;
@Autowired
private AccountManager acntMgr;
@Autowired
private ErrorFacade errf;
@Autowired
private TagManager tagMgr;
@Autowired
private ThreadFacade thdf;
@Autowired
private ResourceDestinationMaker destMaker;
@Autowired
private ImageDeletionPolicyManager deletionPolicyMgr;
@Autowired
protected RESTFacade restf;
private Map<String, ImageFactory> imageFactories = Collections.synchronizedMap(new HashMap<>());
private static final Set<Class> allowedMessageAfterDeletion = new HashSet<>();
private Future<Void> expungeTask;
static {
allowedMessageAfterDeletion.add(ImageDeletionMsg.class);
}
@Override
@MessageSafe
public void handleMessage(Message msg) {
if (msg instanceof ImageMessage) {
passThrough((ImageMessage) msg);
} else if (msg instanceof APIMessage) {
handleApiMessage(msg);
} else {
handleLocalMessage(msg);
}
}
private void handleLocalMessage(Message msg) {
bus.dealWithUnknownMessage(msg);
}
private void handleApiMessage(Message msg) {
if (msg instanceof APIAddImageMsg) {
handle((APIAddImageMsg) msg);
} else if (msg instanceof APIListImageMsg) {
handle((APIListImageMsg) msg);
} else if (msg instanceof APISearchImageMsg) {
handle((APISearchImageMsg) msg);
} else if (msg instanceof APIGetImageMsg) {
handle((APIGetImageMsg) msg);
} else if (msg instanceof APICreateRootVolumeTemplateFromRootVolumeMsg) {
handle((APICreateRootVolumeTemplateFromRootVolumeMsg) msg);
} else if (msg instanceof APICreateRootVolumeTemplateFromVolumeSnapshotMsg) {
handle((APICreateRootVolumeTemplateFromVolumeSnapshotMsg) msg);
} else if (msg instanceof APICreateDataVolumeTemplateFromVolumeMsg) {
handle((APICreateDataVolumeTemplateFromVolumeMsg) msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
private void handle(final APICreateDataVolumeTemplateFromVolumeMsg msg) {
final APICreateDataVolumeTemplateFromVolumeEvent evt = new APICreateDataVolumeTemplateFromVolumeEvent(msg.getId());
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("create-data-volume-template-from-volume-%s", msg.getVolumeUuid()));
chain.then(new ShareFlow() {
List<BackupStorageInventory> backupStorage = new ArrayList<>();
ImageVO image;
long actualSize;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "get-actual-size-of-data-volume";
@Override
public void run(final FlowTrigger trigger, Map data) {
SyncVolumeSizeMsg smsg = new SyncVolumeSizeMsg();
smsg.setVolumeUuid(msg.getVolumeUuid());
bus.makeTargetServiceIdByResourceUuid(smsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid());
bus.send(smsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
return;
}
SyncVolumeSizeReply sr = reply.castReply();
actualSize = sr.getActualSize();
trigger.next();
}
});
}
});
flow(new Flow() {
String __name__ = "create-image-in-database";
@Override
public void run(FlowTrigger trigger, Map data) {
SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class);
q.select(VolumeVO_.format, VolumeVO_.size);
q.add(VolumeVO_.uuid, Op.EQ, msg.getVolumeUuid());
Tuple t = q.findTuple();
String format = t.get(0, String.class);
long size = t.get(1, Long.class);
final ImageVO vo = new ImageVO();
vo.setUuid(msg.getResourceUuid() == null ? Platform.getUuid() : msg.getResourceUuid());
vo.setName(msg.getName());
vo.setDescription(msg.getDescription());
vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE);
vo.setMediaType(ImageMediaType.DataVolumeTemplate);
vo.setSize(size);
vo.setActualSize(actualSize);
vo.setState(ImageState.Enabled);
vo.setStatus(ImageStatus.Creating);
vo.setFormat(format);
vo.setUrl(String.format("volume://%s", msg.getVolumeUuid()));
image = dbf.persistAndRefresh(vo);
acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class);
tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName());
trigger.next();
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (image != null) {
dbf.remove(image);
}
trigger.rollback();
}
});
flow(new Flow() {
String __name__ = "select-backup-storage";
@Override
public void run(final FlowTrigger trigger, Map data) {
final String zoneUuid = new Callable<String>() {
@Override
@Transactional(readOnly = true)
public String call() {
String sql = "select ps.zoneUuid" +
" from PrimaryStorageVO ps, VolumeVO vol" +
" where vol.primaryStorageUuid = ps.uuid" +
" and vol.uuid = :volUuid";
TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class);
q.setParameter("volUuid", msg.getVolumeUuid());
return q.getSingleResult();
}
}.call();
if (msg.getBackupStorageUuids() == null) {
AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg();
amsg.setRequiredZoneUuid(zoneUuid);
amsg.setSize(actualSize);
bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID);
bus.send(amsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
backupStorage.add(((AllocateBackupStorageReply) reply).getInventory());
trigger.next();
} else {
trigger.fail(errf.stringToOperationError("cannot find proper backup storage", reply.getError()));
}
}
});
} else {
List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() {
@Override
public AllocateBackupStorageMsg call(String arg) {
AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg();
amsg.setRequiredZoneUuid(zoneUuid);
amsg.setSize(actualSize);
amsg.setBackupStorageUuid(arg);
bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID);
return amsg;
}
});
bus.send(amsgs, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
List<ErrorCode> errs = new ArrayList<>();
for (MessageReply r : replies) {
if (r.isSuccess()) {
backupStorage.add(((AllocateBackupStorageReply) r).getInventory());
} else {
errs.add(r.getError());
}
}
if (backupStorage.isEmpty()) {
trigger.fail(errf.stringToOperationError(String.format("failed to allocate all backup storage[uuid:%s], a list of error: %s",
msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs))));
} else {
trigger.next();
}
}
});
}
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (!backupStorage.isEmpty()) {
List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(backupStorage, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() {
@Override
public ReturnBackupStorageMsg call(BackupStorageInventory arg) {
ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg();
rmsg.setBackupStorageUuid(arg.getUuid());
rmsg.setSize(actualSize);
bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID);
return rmsg;
}
});
bus.send(rmsgs, new CloudBusListCallBack() {
@Override
public void run(List<MessageReply> replies) {
for (MessageReply r : replies) {
BackupStorageInventory bs = backupStorage.get(replies.indexOf(r));
logger.warn(String.format("failed to return %s bytes to backup storage[uuid:%s]", acntMgr, bs.getUuid()));
}
}
});
}
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "create-data-volume-template-from-volume";
@Override
public void run(final FlowTrigger trigger, Map data) {
List<CreateDataVolumeTemplateFromDataVolumeMsg> cmsgs = CollectionUtils.transformToList(backupStorage, new Function<CreateDataVolumeTemplateFromDataVolumeMsg, BackupStorageInventory>() {
@Override
public CreateDataVolumeTemplateFromDataVolumeMsg call(BackupStorageInventory bs) {
CreateDataVolumeTemplateFromDataVolumeMsg cmsg = new CreateDataVolumeTemplateFromDataVolumeMsg();
cmsg.setVolumeUuid(msg.getVolumeUuid());
cmsg.setBackupStorageUuid(bs.getUuid());
cmsg.setImageUuid(image.getUuid());
bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid());
return cmsg;
}
});
bus.send(cmsgs, new CloudBusListCallBack(msg) {
@Override
public void run(List<MessageReply> replies) {
int fail = 0;
String mdsum = null;
ErrorCode err = null;
String format = null;
for (MessageReply r : replies) {
BackupStorageInventory bs = backupStorage.get(replies.indexOf(r));
if (!r.isSuccess()) {
logger.warn(String.format("failed to create data volume template from volume[uuid:%s] on backup storage[uuid:%s], %s",
msg.getVolumeUuid(), bs.getUuid(), r.getError()));
fail++;
err = r.getError();
continue;
}
CreateDataVolumeTemplateFromDataVolumeReply reply = r.castReply();
ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO();
ref.setBackupStorageUuid(bs.getUuid());
ref.setStatus(ImageStatus.Ready);
ref.setImageUuid(image.getUuid());
ref.setInstallPath(reply.getInstallPath());
dbf.persist(ref);
if (mdsum == null) {
mdsum = reply.getMd5sum();
}
if (reply.getFormat() != null) {
format = reply.getFormat();
}
}
int backupStorageNum = msg.getBackupStorageUuids() == null ? 1 : msg.getBackupStorageUuids().size();
if (fail == backupStorageNum) {
ErrorCode errCode = errf.instantiateErrorCode(SysErrors.OPERATION_ERROR,
String.format("failed to create data volume template from volume[uuid:%s] on all backup storage%s. See cause for one of errors",
msg.getVolumeUuid(), msg.getBackupStorageUuids()),
err
);
trigger.fail(errCode);
} else {
image = dbf.reload(image);
if (format != null) {
image.setFormat(format);
}
image.setMd5Sum(mdsum);
image.setStatus(ImageStatus.Ready);
image = dbf.updateAndRefresh(image);
trigger.next();
}
}
});
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
evt.setInventory(ImageInventory.valueOf(image));
bus.publish(evt);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
evt.setErrorCode(errCode);
bus.publish(evt);
}
});
}
}).start();
}
private void handle(final APICreateRootVolumeTemplateFromVolumeSnapshotMsg msg) {
final APICreateRootVolumeTemplateFromVolumeSnapshotEvent evt = new APICreateRootVolumeTemplateFromVolumeSnapshotEvent(msg.getId());
SimpleQuery<VolumeSnapshotVO> q = dbf.createQuery(VolumeSnapshotVO.class);
q.select(VolumeSnapshotVO_.format);
q.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid());
String format = q.findValue();
final ImageVO vo = new ImageVO();
if (msg.getResourceUuid() != null) {
vo.setUuid(msg.getResourceUuid());
} else {
vo.setUuid(Platform.getUuid());
}
vo.setName(msg.getName());
vo.setSystem(msg.isSystem());
vo.setDescription(msg.getDescription());
vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform()));
vo.setGuestOsType(vo.getGuestOsType());
vo.setStatus(ImageStatus.Creating);
vo.setState(ImageState.Enabled);
vo.setFormat(format);
vo.setMediaType(ImageMediaType.RootVolumeTemplate);
vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE);
vo.setUrl(String.format("volumeSnapshot://%s", msg.getSnapshotUuid()));
dbf.persist(vo);
acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class);
tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName());
SimpleQuery<VolumeSnapshotVO> sq = dbf.createQuery(VolumeSnapshotVO.class);
sq.select(VolumeSnapshotVO_.volumeUuid, VolumeSnapshotVO_.treeUuid);
sq.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid());
Tuple t = sq.findTuple();
String volumeUuid = t.get(0, String.class);
String treeUuid = t.get(1, String.class);
List<CreateTemplateFromVolumeSnapshotMsg> cmsgs = msg.getBackupStorageUuids().stream().map(bsUuid -> {
CreateTemplateFromVolumeSnapshotMsg cmsg = new CreateTemplateFromVolumeSnapshotMsg();
cmsg.setSnapshotUuid(msg.getSnapshotUuid());
cmsg.setImageUuid(vo.getUuid());
cmsg.setVolumeUuid(volumeUuid);
cmsg.setTreeUuid(treeUuid);
cmsg.setBackupStorageUuid(bsUuid);
String resourceUuid = volumeUuid != null ? volumeUuid : treeUuid;
bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeSnapshotConstant.SERVICE_ID, resourceUuid);
return cmsg;
}).collect(Collectors.toList());
List<Failure> failures = new ArrayList<>();
AsyncLatch latch = new AsyncLatch(cmsgs.size(), new NoErrorCompletion(msg) {
@Override
public void done() {
if (failures.size() == cmsgs.size()) {
// failed on all
ErrorCodeList error = errf.stringToOperationError(String.format("failed to create template from" +
" the volume snapshot[uuid:%s] on backup storage[uuids:%s]", msg.getSnapshotUuid(),
msg.getBackupStorageUuids()), failures.stream().map(f -> f.error).collect(Collectors.toList()));
evt.setErrorCode(error);
dbf.remove(vo);
} else {
ImageVO imvo = dbf.reload(vo);
evt.setInventory(ImageInventory.valueOf(imvo));
logger.debug(String.format("successfully created image[uuid:%s, name:%s] from volume snapshot[uuid:%s]",
imvo.getUuid(), imvo.getName(), msg.getSnapshotUuid()));
}
if (!failures.isEmpty()) {
evt.setFailuresOnBackupStorage(failures);
}
bus.publish(evt);
}
});
RunOnce once = new RunOnce();
for (CreateTemplateFromVolumeSnapshotMsg cmsg : cmsgs) {
bus.send(cmsg, new CloudBusCallBack(latch) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
synchronized (failures) {
Failure failure = new Failure();
failure.error = reply.getError();
failure.backupStorageUuid = cmsg.getBackupStorageUuid();
failures.add(failure);
}
} else {
CreateTemplateFromVolumeSnapshotReply cr = reply.castReply();
ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO();
ref.setBackupStorageUuid(cr.getBackupStorageUuid());
ref.setInstallPath(cr.getBackupStorageInstallPath());
ref.setStatus(ImageStatus.Ready);
ref.setImageUuid(vo.getUuid());
dbf.persist(ref);
once.run(() -> {
vo.setSize(cr.getSize());
vo.setActualSize(cr.getActualSize());
vo.setStatus(ImageStatus.Ready);
dbf.update(vo);
});
}
latch.ack();
}
});
}
}
private void passThrough(ImageMessage msg) {
ImageVO vo = dbf.findByUuid(msg.getImageUuid(), ImageVO.class);
if (vo == null && allowedMessageAfterDeletion.contains(msg.getClass())) {
ImageEO eo = dbf.findByUuid(msg.getImageUuid(), ImageEO.class);
vo = ObjectUtils.newAndCopy(eo, ImageVO.class);
}
if (vo == null) {
String err = String.format("Cannot find image[uuid:%s], it may have been deleted", msg.getImageUuid());
logger.warn(err);
bus.replyErrorByMessageType((Message) msg, errf.instantiateErrorCode(SysErrors.RESOURCE_NOT_FOUND, err));
return;
}
ImageFactory factory = getImageFacotry(ImageType.valueOf(vo.getType()));
Image img = factory.getImage(vo);
img.handleMessage((Message) msg);
}
private void handle(final APICreateRootVolumeTemplateFromRootVolumeMsg msg) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("create-template-from-root-volume-%s", msg.getRootVolumeUuid()));
chain.then(new ShareFlow() {
ImageVO imageVO;
VolumeInventory rootVolume;
Long imageActualSize;
List<BackupStorageInventory> targetBackupStorages = new ArrayList<>();
String zoneUuid;
{
VolumeVO rootvo = dbf.findByUuid(msg.getRootVolumeUuid(), VolumeVO.class);
rootVolume = VolumeInventory.valueOf(rootvo);
SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class);
q.select(PrimaryStorageVO_.zoneUuid);
q.add(PrimaryStorageVO_.uuid, Op.EQ, rootVolume.getPrimaryStorageUuid());
zoneUuid = q.findValue();
}
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "get-volume-actual-size";
@Override
public void run(final FlowTrigger trigger, Map data) {
SyncVolumeSizeMsg msg = new SyncVolumeSizeMsg();
msg.setVolumeUuid(rootVolume.getUuid());
bus.makeTargetServiceIdByResourceUuid(msg, VolumeConstant.SERVICE_ID, rootVolume.getPrimaryStorageUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
return;
}
SyncVolumeSizeReply sr = reply.castReply();
imageActualSize = sr.getActualSize();
trigger.next();
}
});
}
});
flow(new Flow() {
String __name__ = "create-image-in-database";
public void run(FlowTrigger trigger, Map data) {
SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class);
q.add(VolumeVO_.uuid, Op.EQ, msg.getRootVolumeUuid());
final VolumeVO volvo = q.find();
String accountUuid = acntMgr.getOwnerAccountUuidOfResource(volvo.getUuid());
final ImageVO imvo = new ImageVO();
if (msg.getResourceUuid() != null) {
imvo.setUuid(msg.getResourceUuid());
} else {
imvo.setUuid(Platform.getUuid());
}
imvo.setDescription(msg.getDescription());
imvo.setMediaType(ImageMediaType.RootVolumeTemplate);
imvo.setState(ImageState.Enabled);
imvo.setGuestOsType(msg.getGuestOsType());
imvo.setFormat(volvo.getFormat());
imvo.setName(msg.getName());
imvo.setSystem(msg.isSystem());
imvo.setPlatform(ImagePlatform.valueOf(msg.getPlatform()));
imvo.setStatus(ImageStatus.Downloading);
imvo.setType(ImageConstant.ZSTACK_IMAGE_TYPE);
imvo.setUrl(String.format("volume://%s", msg.getRootVolumeUuid()));
imvo.setSize(volvo.getSize());
imvo.setActualSize(imageActualSize);
dbf.persist(imvo);
acntMgr.createAccountResourceRef(accountUuid, imvo.getUuid(), ImageVO.class);
tagMgr.createTagsFromAPICreateMessage(msg, imvo.getUuid(), ImageVO.class.getSimpleName());
imageVO = imvo;
trigger.next();
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (imageVO != null) {
dbf.remove(imageVO);
}
trigger.rollback();
}
});
flow(new Flow() {
String __name__ = String.format("select-backup-storage");
@Override
public void run(final FlowTrigger trigger, Map data) {
if (msg.getBackupStorageUuids() == null) {
AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg();
abmsg.setRequiredZoneUuid(zoneUuid);
abmsg.setSize(imageActualSize);
bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID);
bus.send(abmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
targetBackupStorages.add(((AllocateBackupStorageReply) reply).getInventory());
trigger.next();
} else {
trigger.fail(reply.getError());
}
}
});
} else {
List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() {
@Override
public AllocateBackupStorageMsg call(String arg) {
AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg();
abmsg.setSize(imageActualSize);
abmsg.setBackupStorageUuid(arg);
bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID);
return abmsg;
}
});
bus.send(amsgs, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
List<ErrorCode> errs = new ArrayList<>();
for (MessageReply r : replies) {
if (r.isSuccess()) {
targetBackupStorages.add(((AllocateBackupStorageReply) r).getInventory());
} else {
errs.add(r.getError());
}
}
if (targetBackupStorages.isEmpty()) {
trigger.fail(errf.stringToOperationError(String.format("unable to allocate backup storage specified by uuids%s, list errors are: %s",
msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs))));
} else {
trigger.next();
}
}
});
}
}
@Override
public void rollback(final FlowRollback trigger, Map data) {
if (targetBackupStorages.isEmpty()) {
trigger.rollback();
return;
}
List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() {
@Override
public ReturnBackupStorageMsg call(BackupStorageInventory arg) {
ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg();
rmsg.setBackupStorageUuid(arg.getUuid());
rmsg.setSize(imageActualSize);
bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID);
return rmsg;
}
});
bus.send(rmsgs, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
for (MessageReply r : replies) {
if (!r.isSuccess()) {
BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r));
logger.warn(String.format("failed to return capacity[%s] to backup storage[uuid:%s], because %s",
imageActualSize, bs.getUuid(), r.getError()));
}
}
trigger.rollback();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = String.format("start-creating-template");
@Override
public void run(final FlowTrigger trigger, Map data) {
List<CreateTemplateFromVmRootVolumeMsg> cmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<CreateTemplateFromVmRootVolumeMsg, BackupStorageInventory>() {
@Override
public CreateTemplateFromVmRootVolumeMsg call(BackupStorageInventory arg) {
CreateTemplateFromVmRootVolumeMsg cmsg = new CreateTemplateFromVmRootVolumeMsg();
cmsg.setRootVolumeInventory(rootVolume);
cmsg.setBackupStorageUuid(arg.getUuid());
cmsg.setImageInventory(ImageInventory.valueOf(imageVO));
bus.makeTargetServiceIdByResourceUuid(cmsg, VmInstanceConstant.SERVICE_ID, rootVolume.getVmInstanceUuid());
return cmsg;
}
});
bus.send(cmsgs, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
boolean success = false;
ErrorCode err = null;
for (MessageReply r : replies) {
BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r));
if (!r.isSuccess()) {
logger.warn(String.format("failed to create image from root volume[uuid:%s] on backup storage[uuid:%s], because %s",
msg.getRootVolumeUuid(), bs.getUuid(), r.getError()));
err = r.getError();
continue;
}
CreateTemplateFromVmRootVolumeReply reply = (CreateTemplateFromVmRootVolumeReply) r;
ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO();
ref.setBackupStorageUuid(bs.getUuid());
ref.setStatus(ImageStatus.Ready);
ref.setImageUuid(imageVO.getUuid());
ref.setInstallPath(reply.getInstallPath());
dbf.persist(ref);
imageVO.setStatus(ImageStatus.Ready);
if (reply.getFormat() != null) {
imageVO.setFormat(reply.getFormat());
}
dbf.update(imageVO);
imageVO = dbf.reload(imageVO);
success = true;
logger.debug(String.format("successfully created image[uuid:%s] from root volume[uuid:%s] on backup storage[uuid:%s]",
imageVO.getUuid(), msg.getRootVolumeUuid(), bs.getUuid()));
}
if (success) {
trigger.next();
} else {
trigger.fail(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, String.format("failed to create image from root volume[uuid:%s] on all backup storage, see cause for one of errors",
msg.getRootVolumeUuid()), err));
}
}
});
}
});
flow(new Flow() {
String __name__ = "copy-system-tag-to-image";
public void run(FlowTrigger trigger, Map data) {
// find the rootimage and create some systemtag if it has
SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class);
q.add(VolumeVO_.uuid, SimpleQuery.Op.EQ, msg.getRootVolumeUuid());
q.select(VolumeVO_.vmInstanceUuid);
String vmInstanceUuid = q.findValue();
if (tagMgr.hasSystemTag(vmInstanceUuid, ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat())) {
tagMgr.createNonInherentSystemTag(imageVO.getUuid(),
ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat(),
ImageVO.class.getSimpleName());
}
trigger.next();
}
@Override
public void rollback(FlowRollback trigger, Map data) {
trigger.rollback();
}
});
flow(new Flow() {
String __name__ = "copy-system-tag-to-image";
public void run(FlowTrigger trigger, Map data) {
// find the rootimage and create some systemtag if it has
SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class);
q.add(VolumeVO_.uuid, SimpleQuery.Op.EQ, msg.getRootVolumeUuid());
q.select(VolumeVO_.vmInstanceUuid);
String vmInstanceUuid = q.findValue();
if (tagMgr.hasSystemTag(vmInstanceUuid, ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat())) {
tagMgr.createNonInherentSystemTag(imageVO.getUuid(),
ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat(),
ImageVO.class.getSimpleName());
}
trigger.next();
}
@Override
public void rollback(FlowRollback trigger, Map data) {
trigger.rollback();
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId());
imageVO = dbf.reload(imageVO);
ImageInventory iinv = ImageInventory.valueOf(imageVO);
evt.setInventory(iinv);
logger.warn(String.format("successfully create template[uuid:%s] from root volume[uuid:%s]", iinv.getUuid(), msg.getRootVolumeUuid()));
bus.publish(evt);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId());
evt.setErrorCode(errCode);
logger.warn(String.format("failed to create template from root volume[uuid:%s], because %s", msg.getRootVolumeUuid(), errCode));
bus.publish(evt);
}
});
}
}).start();
}
private void handle(APIGetImageMsg msg) {
SearchQuery<ImageInventory> sq = new SearchQuery(ImageInventory.class);
sq.addAccountAsAnd(msg);
sq.add("uuid", SearchOp.AND_EQ, msg.getUuid());
List<ImageInventory> invs = sq.list();
APIGetImageReply reply = new APIGetImageReply();
if (!invs.isEmpty()) {
reply.setInventory(JSONObjectUtil.toJsonString(invs.get(0)));
}
bus.reply(msg, reply);
}
private void handle(APISearchImageMsg msg) {
SearchQuery<ImageInventory> sq = SearchQuery.create(msg, ImageInventory.class);
sq.addAccountAsAnd(msg);
String content = sq.listAsString();
APISearchImageReply reply = new APISearchImageReply();
reply.setContent(content);
bus.reply(msg, reply);
}
private void handle(APIListImageMsg msg) {
List<ImageVO> vos = dbf.listAll(ImageVO.class);
List<ImageInventory> invs = ImageInventory.valueOf(vos);
APIListImageReply reply = new APIListImageReply();
reply.setInventories(invs);
bus.reply(msg, reply);
}
@Deferred
private void handle(final APIAddImageMsg msg) {
String imageType = msg.getType();
imageType = imageType == null ? DefaultImageFactory.type.toString() : imageType;
final APIAddImageEvent evt = new APIAddImageEvent(msg.getId());
ImageVO vo = new ImageVO();
if (msg.getResourceUuid() != null) {
vo.setUuid(msg.getResourceUuid());
} else {
vo.setUuid(Platform.getUuid());
}
vo.setName(msg.getName());
vo.setDescription(msg.getDescription());
if (msg.getFormat().equals(ImageConstant.ISO_FORMAT_STRING)) {
vo.setMediaType(ImageMediaType.ISO);
} else {
vo.setMediaType(ImageMediaType.valueOf(msg.getMediaType()));
}
vo.setType(imageType);
vo.setSystem(msg.isSystem());
vo.setGuestOsType(msg.getGuestOsType());
vo.setFormat(msg.getFormat());
vo.setStatus(ImageStatus.Downloading);
vo.setState(ImageState.Enabled);
vo.setUrl(msg.getUrl());
vo.setDescription(msg.getDescription());
vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform()));
ImageFactory factory = getImageFacotry(ImageType.valueOf(imageType));
final ImageVO ivo = factory.createImage(vo, msg);
acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class);
tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName());
Defer.guard(() -> dbf.remove(ivo));
final ImageInventory inv = ImageInventory.valueOf(ivo);
for (AddImageExtensionPoint ext : pluginRgty.getExtensionList(AddImageExtensionPoint.class)) {
ext.preAddImage(inv);
}
final List<DownloadImageMsg> dmsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<DownloadImageMsg, String>() {
@Override
public DownloadImageMsg call(String arg) {
DownloadImageMsg dmsg = new DownloadImageMsg(inv);
dmsg.setBackupStorageUuid(arg);
dmsg.setFormat(msg.getFormat());
dmsg.setSystemTags(msg.getSystemTags());
bus.makeTargetServiceIdByResourceUuid(dmsg, BackupStorageConstant.SERVICE_ID, arg);
return dmsg;
}
});
CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() {
@Override
public void run(AddImageExtensionPoint ext) {
ext.beforeAddImage(inv);
}
});
new LoopAsyncBatch<DownloadImageMsg>(msg) {
AtomicBoolean success = new AtomicBoolean(false);
@Override
protected Collection<DownloadImageMsg> collect() {
return dmsgs;
}
@Override
protected AsyncBatchRunner forEach(DownloadImageMsg dmsg) {
return new AsyncBatchRunner() {
@Override
public void run(NoErrorCompletion completion) {
ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO();
ref.setImageUuid(ivo.getUuid());
ref.setInstallPath("");
ref.setBackupStorageUuid(dmsg.getBackupStorageUuid());
ref.setStatus(ImageStatus.Downloading);
dbf.persist(ref);
bus.send(dmsg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
errors.add(reply.getError());
dbf.remove(ref);
} else {
DownloadImageReply re = reply.castReply();
ref.setStatus(ImageStatus.Ready);
ref.setInstallPath(re.getInstallPath());
dbf.update(ref);
if (success.compareAndSet(false, true)) {
ivo.setMd5Sum(re.getMd5sum());
ivo.setSize(re.getSize());
ivo.setActualSize(re.getActualSize());
ivo.setStatus(ImageStatus.Ready);
dbf.update(ivo);
}
logger.debug(String.format("successfully downloaded image[uuid:%s, name:%s] to backup storage[uuid:%s]",
inv.getUuid(), inv.getName(), dmsg.getBackupStorageUuid()));
}
completion.done();
}
});
}
};
}
@Override
protected void done() {
// TODO: check if the database still has the record of the image
// if there is no record, that means user delete the image during the downloading,
// then we need to cleanup
if (success.get()) {
ImageVO vo = dbf.reload(ivo);
final ImageInventory einv = ImageInventory.valueOf(vo);
CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() {
@Override
public void run(AddImageExtensionPoint ext) {
ext.afterAddImage(einv);
}
});
evt.setInventory(einv);
} else {
final ErrorCode err = errf.instantiateErrorCode(SysErrors.CREATE_RESOURCE_ERROR, String.format("Failed to download image[name:%s] on all backup storage%s.",
inv.getName(), msg.getBackupStorageUuids()), errors);
CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() {
@Override
public void run(AddImageExtensionPoint ext) {
ext.failedToAddImage(inv, err);
}
});
dbf.remove(ivo);
evt.setErrorCode(err);
}
bus.publish(evt);
}
}.start();
}
@Override
public String getId() {
return bus.makeLocalServiceId(ImageConstant.SERVICE_ID);
}
private void populateExtensions() {
for (ImageFactory f : pluginRgty.getExtensionList(ImageFactory.class)) {
ImageFactory old = imageFactories.get(f.getType().toString());
if (old != null) {
throw new CloudRuntimeException(String.format("duplicate ImageFactory[%s, %s] for type[%s]",
f.getClass().getName(), old.getClass().getName(), f.getType()));
}
imageFactories.put(f.getType().toString(), f);
}
}
@Override
public boolean start() {
populateExtensions();
installGlobalConfigUpdater();
return true;
}
private void installGlobalConfigUpdater() {
ImageGlobalConfig.DELETION_POLICY.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() {
@Override
public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) {
startExpungeTask();
}
});
ImageGlobalConfig.EXPUNGE_INTERVAL.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() {
@Override
public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) {
startExpungeTask();
}
});
ImageGlobalConfig.EXPUNGE_PERIOD.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() {
@Override
public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) {
startExpungeTask();
}
});
}
private void startExpungeTask() {
if (expungeTask != null) {
expungeTask.cancel(true);
}
expungeTask = thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask() {
private List<Tuple> getDeletedImageManagedByUs() {
int qun = 1000;
SimpleQuery q = dbf.createQuery(ImageBackupStorageRefVO.class);
q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted);
long amount = q.count();
int times = (int) (amount / qun) + (amount % qun != 0 ? 1 : 0);
int start = 0;
List<Tuple> ret = new ArrayList<Tuple>();
for (int i = 0; i < times; i++) {
q = dbf.createQuery(ImageBackupStorageRefVO.class);
q.select(ImageBackupStorageRefVO_.imageUuid, ImageBackupStorageRefVO_.lastOpDate, ImageBackupStorageRefVO_.backupStorageUuid);
q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted);
q.setLimit(qun);
q.setStart(start);
List<Tuple> ts = q.listTuple();
start += qun;
for (Tuple t : ts) {
String imageUuid = t.get(0, String.class);
if (!destMaker.isManagedByUs(imageUuid)) {
continue;
}
ret.add(t);
}
}
return ret;
}
@Override
public boolean run() {
final List<Tuple> images = getDeletedImageManagedByUs();
if (images.isEmpty()) {
logger.debug("[Image Expunge Task]: no images to expunge");
return false;
}
for (Tuple t : images) {
String imageUuid = t.get(0, String.class);
Timestamp date = t.get(1, Timestamp.class);
String bsUuid = t.get(2, String.class);
final Timestamp current = dbf.getCurrentSqlTime();
if (current.getTime() >= date.getTime() + TimeUnit.SECONDS.toMillis(ImageGlobalConfig.EXPUNGE_PERIOD.value(Long.class))) {
ImageDeletionPolicy deletionPolicy = deletionPolicyMgr.getDeletionPolicy(imageUuid);
if (ImageDeletionPolicy.Never == deletionPolicy) {
logger.debug(String.format("the deletion policy[Never] is set for the image[uuid:%s] on the backup storage[uuid:%s]," +
"don't expunge it", images, bsUuid));
continue;
}
ExpungeImageMsg msg = new ExpungeImageMsg();
msg.setImageUuid(imageUuid);
msg.setBackupStorageUuid(bsUuid);
bus.makeTargetServiceIdByResourceUuid(msg, ImageConstant.SERVICE_ID, imageUuid);
bus.send(msg, new CloudBusCallBack() {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
//TODO
logger.warn(String.format("failed to expunge the image[uuid:%s], %s", images, reply.getError()));
}
}
});
}
}
return false;
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return ImageGlobalConfig.EXPUNGE_INTERVAL.value(Long.class);
}
@Override
public String getName() {
return "expunge-image";
}
});
}
@Override
public boolean stop() {
return true;
}
private ImageFactory getImageFacotry(ImageType type) {
ImageFactory factory = imageFactories.get(type.toString());
if (factory == null) {
throw new CloudRuntimeException(String.format("Unable to find ImageFactory with type[%s]", type));
}
return factory;
}
@Override
public void managementNodeReady() {
startExpungeTask();
}
@Override
public List<Quota> reportQuota() {
Quota.QuotaOperator checker = new Quota.QuotaOperator() {
@Override
public void checkQuota(APIMessage msg, Map<String, Quota.QuotaPair> pairs) {
if (!new QuotaUtil().isAdminAccount(msg.getSession().getAccountUuid())) {
if (msg instanceof APIAddImageMsg) {
check((APIAddImageMsg) msg, pairs);
} else if (msg instanceof APIRecoverImageMsg) {
check((APIRecoverImageMsg) msg, pairs);
} else if (msg instanceof APIChangeResourceOwnerMsg) {
check((APIChangeResourceOwnerMsg) msg, pairs);
}
} else {
if (msg instanceof APIChangeResourceOwnerMsg) {
check((APIChangeResourceOwnerMsg) msg, pairs);
}
}
}
@Override
public void checkQuota(NeedQuotaCheckMessage msg, Map<String, Quota.QuotaPair> pairs) {
}
@Override
public List<Quota.QuotaUsage> getQuotaUsageByAccount(String accountUuid) {
List<Quota.QuotaUsage> usages = new ArrayList<>();
ImageQuotaUtil.ImageQuota imageQuota = new ImageQuotaUtil().getUsed(accountUuid);
Quota.QuotaUsage usage = new Quota.QuotaUsage();
usage.setName(ImageConstant.QUOTA_IMAGE_NUM);
usage.setUsed(imageQuota.imageNum);
usages.add(usage);
usage = new Quota.QuotaUsage();
usage.setName(ImageConstant.QUOTA_IMAGE_SIZE);
usage.setUsed(imageQuota.imageSize);
usages.add(usage);
return usages;
}
@Transactional(readOnly = true)
private void check(APIChangeResourceOwnerMsg msg, Map<String, Quota.QuotaPair> pairs) {
String currentAccountUuid = msg.getSession().getAccountUuid();
String resourceTargetOwnerAccountUuid = msg.getAccountUuid();
if (new QuotaUtil().isAdminAccount(resourceTargetOwnerAccountUuid)) {
return;
}
SimpleQuery<AccountResourceRefVO> q = dbf.createQuery(AccountResourceRefVO.class);
q.add(AccountResourceRefVO_.resourceUuid, Op.EQ, msg.getResourceUuid());
AccountResourceRefVO accResRefVO = q.find();
if (accResRefVO.getResourceType().equals(ImageVO.class.getSimpleName())) {
long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue();
long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue();
long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid);
long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(resourceTargetOwnerAccountUuid);
ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getResourceUuid());
long imageNumAsked = 1;
long imageSizeAsked = image.getSize();
QuotaUtil.QuotaCompareInfo quotaCompareInfo;
{
quotaCompareInfo = new QuotaUtil.QuotaCompareInfo();
quotaCompareInfo.currentAccountUuid = currentAccountUuid;
quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid;
quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM;
quotaCompareInfo.quotaValue = imageNumQuota;
quotaCompareInfo.currentUsed = imageNumUsed;
quotaCompareInfo.request = imageNumAsked;
new QuotaUtil().CheckQuota(quotaCompareInfo);
}
{
quotaCompareInfo = new QuotaUtil.QuotaCompareInfo();
quotaCompareInfo.currentAccountUuid = currentAccountUuid;
quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid;
quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_SIZE;
quotaCompareInfo.quotaValue = imageSizeQuota;
quotaCompareInfo.currentUsed = imageSizeUsed;
quotaCompareInfo.request = imageSizeAsked;
new QuotaUtil().CheckQuota(quotaCompareInfo);
}
}
}
@Transactional(readOnly = true)
private void check(APIRecoverImageMsg msg, Map<String, Quota.QuotaPair> pairs) {
String currentAccountUuid = msg.getSession().getAccountUuid();
String resourceTargetOwnerAccountUuid = new QuotaUtil().getResourceOwnerAccountUuid(msg.getImageUuid());
long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue();
long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue();
long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid);
long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(resourceTargetOwnerAccountUuid);
ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getImageUuid());
long imageNumAsked = 1;
long imageSizeAsked = image.getSize();
QuotaUtil.QuotaCompareInfo quotaCompareInfo;
{
quotaCompareInfo = new QuotaUtil.QuotaCompareInfo();
quotaCompareInfo.currentAccountUuid = currentAccountUuid;
quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid;
quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM;
quotaCompareInfo.quotaValue = imageNumQuota;
quotaCompareInfo.currentUsed = imageNumUsed;
quotaCompareInfo.request = imageNumAsked;
new QuotaUtil().CheckQuota(quotaCompareInfo);
}
{
quotaCompareInfo = new QuotaUtil.QuotaCompareInfo();
quotaCompareInfo.currentAccountUuid = currentAccountUuid;
quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid;
quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_SIZE;
quotaCompareInfo.quotaValue = imageSizeQuota;
quotaCompareInfo.currentUsed = imageSizeUsed;
quotaCompareInfo.request = imageSizeAsked;
new QuotaUtil().CheckQuota(quotaCompareInfo);
}
}
@Transactional(readOnly = true)
private void check(APIAddImageMsg msg, Map<String, Quota.QuotaPair> pairs) {
String currentAccountUuid = msg.getSession().getAccountUuid();
String resourceTargetOwnerAccountUuid = msg.getSession().getAccountUuid();
long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue();
long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid);
long imageNumAsked = 1;
QuotaUtil.QuotaCompareInfo quotaCompareInfo;
{
quotaCompareInfo = new QuotaUtil.QuotaCompareInfo();
quotaCompareInfo.currentAccountUuid = currentAccountUuid;
quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid;
quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM;
quotaCompareInfo.quotaValue = imageNumQuota;
quotaCompareInfo.currentUsed = imageNumUsed;
quotaCompareInfo.request = imageNumAsked;
new QuotaUtil().CheckQuota(quotaCompareInfo);
}
new ImageQuotaUtil().checkImageSizeQuotaUseHttpHead(msg, pairs);
}
};
Quota quota = new Quota();
quota.setOperator(checker);
quota.addMessageNeedValidation(APIAddImageMsg.class);
quota.addMessageNeedValidation(APIRecoverImageMsg.class);
quota.addMessageNeedValidation(APIChangeResourceOwnerMsg.class);
Quota.QuotaPair p = new Quota.QuotaPair();
p.setName(ImageConstant.QUOTA_IMAGE_NUM);
p.setValue(20);
quota.addPair(p);
p = new Quota.QuotaPair();
p.setName(ImageConstant.QUOTA_IMAGE_SIZE);
p.setValue(SizeUnit.TERABYTE.toByte(10));
quota.addPair(p);
return list(quota);
}
@Override
@Transactional(readOnly = true)
public void resourceOwnerPreChange(AccountResourceRefInventory ref, String newOwnerUuid) {
}
}
|
package info.limpet.ui.xy_plot;
import info.limpet.IStoreItem;
import info.limpet.impl.NumberDocument;
import info.limpet.ui.xy_plot.Helper2D.HContainer;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.january.dataset.DoubleDataset;
import org.eclipse.nebula.visualization.widgets.datadefinition.ColorMap;
import org.eclipse.nebula.visualization.widgets.datadefinition.ColorMap.PredefinedColorMap;
import org.eclipse.nebula.visualization.widgets.figures.IntensityGraphFigure;
import org.eclipse.nebula.visualization.xygraph.linearscale.Range;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
/**
* display analysis overview of selection
*
* @author ian
*
*/
public class HeatmapView extends CommonGridView
{
/**
* The ID of the view as specified by the extension.
*/
public static final String ID = "info.limpet.ui.HeatMapView";
private IntensityGraphFigure intensityGraph;
private Canvas parentCanvas;
public HeatmapView()
{
super(ID, "Heatmap view");
}
protected void clearChart()
{
intensityGraph.setDataArray(new double[]
{});
}
/**
* This is a callback that will allow us to create the viewer and initialize it.
*/
@Override
public void createPartControl(final Composite parent)
{
// Create the composite to hold the controls
final Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
// Create the combo to hold the team names
titleLbl = new Text(composite, SWT.NONE);
titleLbl.setText(" ");
// insert the holder for the heatmap
parentCanvas = new Canvas(composite, SWT.NULL);
parentCanvas.setLayoutData(new GridData(GridData.FILL_BOTH));
// Create Intensity Graph
intensityGraph = new IntensityGraphFigure();
// use LightweightSystem to create the bridge between SWT and draw2D
final LightweightSystem lws = new LightweightSystem(parentCanvas);
lws.setContents(intensityGraph);
// ok, layout the panel
parentCanvas.pack();
makeActions();
contributeToActionBars();
// register as selection listener
setupListener();
}
@Override
protected String getTextForClipboard()
{
return "Pending";
}
@Override
public void setFocus()
{
parentCanvas.setFocus();
}
protected void show(final IStoreItem item)
{
final NumberDocument thisQ = (NumberDocument) item;
clearChart();
final String seriesName = thisQ.getName();
titleLbl.setText(seriesName + " (" + thisQ.getUnits().toString() + ")");
// get the data
final HContainer hData =
Helper2D.convert((DoubleDataset) thisQ.getDataset());
final int rows = hData.rowTitles.length;
final int cols = hData.colTitles.length;
final int DataHeight = rows;
final int DataWidth = cols;
final double[] data = new double[DataWidth * DataHeight];
for (int i = 0; i < DataHeight; i++)
{
for (int j = 0; j < DataWidth; j++)
{
final double thisVal = hData.values[i][j];
data[i + j * DataHeight] = thisVal;
}
}
final DescriptiveStatistics stats = new DescriptiveStatistics(data);
if (Double.isNaN(stats.getMax()))
{
// ok, drop out, we haven't got any data
return;
}
// Configure
intensityGraph.setMax(stats.getMax());
intensityGraph.setMin(stats.getMin());
intensityGraph.setDataHeight(DataHeight);
intensityGraph.setDataWidth(DataWidth);
intensityGraph
.setColorMap(new ColorMap(PredefinedColorMap.JET, true, true));
intensityGraph.setDataArray(data);
// sort out the axis ranges
intensityGraph.getXAxis().setRange(
new Range(hData.rowTitles[0],
hData.rowTitles[hData.rowTitles.length - 1]));
intensityGraph.getYAxis().setRange(
new Range(hData.colTitles[0],
hData.colTitles[hData.colTitles.length - 1]));
// parentCanvas.pack();
titleLbl.pack();
}
}
|
package com.splunk.spigot;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bukkit.Location;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import com.splunk.sharedmc.Point3dLong;
import com.splunk.spigot.eventloggers.BlockEventLogger;
import com.splunk.spigot.eventloggers.DeathEventLogger;
import com.splunk.spigot.eventloggers.EntityEventLogger;
import com.splunk.spigot.eventloggers.PlayerEventLogger;
public class LogToSplunkPlugin extends JavaPlugin implements Listener {
public static final String MODID = "logtosplunk";
public static final String VERSION = "1.1-SNAPSHOT";
public static final String NAME = "Splunk for Minecraft";
public static final String SPLUNK_PROPERTIES = "/config/splunk.properties";
private Properties properties;
private static final Logger logger = LogManager.getLogger(LogToSplunkPlugin.class.getName());
/**
* Called when the mod is initialized.
*/
@Override
public void onEnable() {
// Could probably move this to the AbstractEventLogger in shared
properties = new Properties();
final String path = System.getProperty("user.dir") + SPLUNK_PROPERTIES;
try (final FileReader reader = new FileReader(new File(path))) {
properties.load(reader);
} catch (final Exception e) {
logger.warn(
String.format(
"Unable to load properties for LogToSplunkMod at %s! Default values will be used.", path),
e);
}
getServer().getPluginManager().registerEvents(new BlockEventLogger(properties), this);
getServer().getPluginManager().registerEvents(new DeathEventLogger(properties), this);
getServer().getPluginManager().registerEvents(new PlayerEventLogger(properties), this);
getServer().getPluginManager().registerEvents(new EntityEventLogger(properties),this);
logAndSend("Splunk for Minecraft initialized.");
}
/**
* Logs and sends messages to be prepared for Splunk.
*
* @param message The message to log.
*/
private void logAndSend(String message) {
logger.info(message);
}
// nullable...
public static Point3dLong locationAsPoint(Location location) {
if (location == null) {
return null;
}
return new Point3dLong(location.getX(), location.getY(), location.getZ());
}
}
|
package org.micromanager.splitview;
import com.swtdesigner.SwingResourceManager;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.text.NumberFormat;
import java.util.prefs.Preferences;
import javax.swing.JColorChooser;
import mmcorej.CMMCore;
import mmcorej.TaggedImage;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.MMStudioMainFrame;
import org.micromanager.api.DataProcessor;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.DeviceControlGUI;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.ReportingUtils;
/**
*
* @author nico
*/
public class SplitViewFrame extends javax.swing.JFrame {
private final ScriptInterface gui_;
private final DeviceControlGUI dGui_;
private final CMMCore core_;
private Preferences prefs_;
private NumberFormat nf_;
private long imgDepth_;
private int width_;
private int height_;
private int newWidth_;
private int newHeight_;
private String orientation_;
Color col1_;
Color col2_;
private int frameXPos_ = 100;
private int frameYPos_ = 100;
private Timer timer_;
private double interval_ = 30;
private static final String ACQNAME = "Split View";
private static final String LR = "lr";
private static final String TB = "tb";
private static final String TOPLEFTCOLOR = "TopLeftColor";
private static final String BOTTOMRIGHTCOLOR = "BottomRightColor";
private static final String ORIENTATION = "Orientation";
private static final String FRAMEXPOS = "FRAMEXPOS";
private static final String FRAMEYPOS = "FRAMEYPOS";
private boolean autoShutterOrg_;
private String shutterLabel_;
private boolean shutterOrg_;
private boolean appliedToMDA_ = false;
private SplitViewProcessor mmImageProcessor_;
public class SplitViewProcessor extends DataProcessor<TaggedImage> {
@Override
public void process() {
try {
TaggedImage taggedImage = poll();
if (taggedImage != null && taggedImage.tags != null) {
ImageProcessor tmpImg;
int imgDepth = MDUtils.getDepth(taggedImage.tags);
int width = MDUtils.getWidth(taggedImage.tags);
int height = MDUtils.getHeight(taggedImage.tags);
int channelIndex = MDUtils.getChannelIndex(taggedImage.tags);
System.out.println("Processed one");
produce(taggedImage);
if (imgDepth == 1) {
tmpImg = new ByteProcessor(width, height);
} else if (imgDepth == 2) {
tmpImg = new ShortProcessor(width, height);
} else // TODO throw error
{
//produce(taggedImage);
return;
}
tmpImg.setPixels(taggedImage.pix);
calculateSize(imgDepth, width, height);
tmpImg.setRoi(0, 0, newWidth_, newHeight_);
// first channel
// Note, this does not copy the tags, rather the pointer
// This will mess things up. Not sure how to copy...
JSONObject tags = taggedImage.tags;
MDUtils.setWidth(tags, newWidth_);
MDUtils.setHeight(tags, newHeight_);
MDUtils.setChannelIndex(tags, channelIndex * 2);
TaggedImage firstIm = new TaggedImage(tmpImg.crop().getPixels(), tags);
//produce(firstIm);
// second channel
if (orientation_.equals(LR)) {
tmpImg.setRoi(newWidth_, 0, newWidth_, height_);
} else if (orientation_.equals(TB)) {
tmpImg.setRoi(0, newHeight_, newWidth_, newHeight_);
}
//MDUtils.setChannelIndex(tags, channelIndex * 2 + 1);
TaggedImage secondIm = new TaggedImage(tmpImg.crop().getPixels(), tags);
//produce(secondIm);
}
} catch (MMScriptException ex) {
ReportingUtils.logError("SplitViewProcessor, MMSCriptException");
} catch (JSONException ex) {
ReportingUtils.logError("SplitViewProcessor, JSON Exception");
}
}
}
public SplitViewFrame(ScriptInterface gui) throws Exception {
gui_ = gui;
dGui_ = (DeviceControlGUI) gui_;
core_ = gui_.getMMCore();
nf_ = NumberFormat.getInstance();
prefs_ = Preferences.userNodeForPackage(this.getClass());
col1_ = new Color(prefs_.getInt(TOPLEFTCOLOR, Color.red.getRGB()));
col2_ = new Color(prefs_.getInt(BOTTOMRIGHTCOLOR, Color.green.getRGB()));
orientation_ = prefs_.get(ORIENTATION, LR);
// initialize timer
// TODO: Replace with Sequence-based live mode
interval_ = 30;
ActionListener timerHandler = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
doSnap();
}
};
timer_ = new Timer((int) interval_, timerHandler);
timer_.stop();
frameXPos_ = prefs_.getInt(FRAMEXPOS, frameXPos_);
frameYPos_ = prefs_.getInt(FRAMEYPOS, frameYPos_);
Font buttonFont = new Font("Arial", Font.BOLD, 10);
initComponents();
setLocation(frameXPos_, frameYPos_);
setBackground(gui_.getBackgroundColor());
Dimension buttonSize = new Dimension(120, 20);
lrRadioButton.setSelected(true);
topLeftColorButton.setForeground(col1_);
topLeftColorButton.setPreferredSize(buttonSize);
bottomRightColorButton.setForeground(col2_);
bottomRightColorButton.setPreferredSize(buttonSize);
liveButton.setIconTextGap(6);
liveButton.setFont(buttonFont);
liveButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png"));
liveButton.setText("Live");
snapButton.setIconTextGap(6);
snapButton.setText("Snap");
snapButton.setIcon(SwingResourceManager.getIcon(SplitView.class, "/org/micromanager/icons/camera.png"));
snapButton.setFont(buttonFont);
snapButton.setToolTipText("Snap single image");
}
private void doSnap() {
calculateSize();
addSnapToImage();
}
private void enableLiveMode(boolean enable) {
try {
if (enable) {
if (timer_.isRunning()) {
return;
}
// turn off auto shutter and open the shutter
autoShutterOrg_ = core_.getAutoShutter();
shutterLabel_ = core_.getShutterDevice();
if (shutterLabel_.length() > 0) {
shutterOrg_ = core_.getShutterOpen();
}
core_.setAutoShutter(false);
// only open the shutter when we have one and the Auto shutter checkbox was checked
if ((shutterLabel_.length() > 0) && autoShutterOrg_) {
core_.setShutterOpen(true);
}
timer_.start();
liveButton.setText("Stop");
} else {
if (!timer_.isRunning()) {
return;
}
timer_.stop();
// add metadata
//addMetaData ();
// save window position since it is not saved on close
// savePosition();
// restore auto shutter and close the shutter
if (shutterLabel_.length() > 0) {
core_.setShutterOpen(shutterOrg_);
}
core_.setAutoShutter(autoShutterOrg_);
liveButton.setText("Live");
}
} catch (Exception err) {
ReportingUtils.showError(err);
}
}
private void calculateSize() {
imgDepth_ = core_.getBytesPerPixel();
width_ = (int) core_.getImageWidth();
height_ = (int) core_.getImageHeight();
calculateSize(imgDepth_, width_, height_);
}
private void calculateSize(long depth, int width, int height) {
if (!orientation_.equals(LR) && !orientation_.equals(TB)) {
orientation_ = LR;
}
if (orientation_.equals(LR)) {
newWidth_ = width_ / 2;
newHeight_ = height_;
} else if (orientation_.equals(TB)) {
newWidth_ = width_;
newHeight_ = height_ / 2;
}
}
private void openAcq() throws MMScriptException {
gui_.openAcquisition(ACQNAME, "", 1, 2, 1);
gui_.initializeAcquisition(ACQNAME, newWidth_, newHeight_, (int) imgDepth_);
gui_.getAcquisition(ACQNAME).promptToSave(false);
gui_.setChannelColor(ACQNAME, 0, col1_);
gui_.setChannelColor(ACQNAME, 1, col2_);
if (orientation_.equals(LR)) {
gui_.setChannelName(ACQNAME, 0, "Left");
gui_.setChannelName(ACQNAME, 1, "Right");
} else {
gui_.setChannelName(ACQNAME, 0, "Top");
gui_.setChannelName(ACQNAME, 1, "Bottom");
}
}
private void addSnapToImage() {
Object img;
ImageProcessor tmpImg;
try {
core_.snapImage();
img = core_.getImage();
if (imgDepth_ == 1) {
tmpImg = new ByteProcessor(width_, height_);
} else if (imgDepth_ == 2) {
tmpImg = new ShortProcessor(width_, height_);
} else // TODO throw error
{
return;
}
tmpImg.setPixels(img);
if (!gui_.acquisitionExists(ACQNAME)) {
openAcq();
} else if (gui_.getAcquisitionImageHeight(ACQNAME) != newHeight_
|| gui_.getAcquisitionImageWidth(ACQNAME) != newWidth_
|| gui_.getAcquisitionImageByteDepth(ACQNAME) != imgDepth_) {
gui_.getAcquisition(ACQNAME).closeImage5D();
gui_.closeAcquisition(ACQNAME);
openAcq();
}
tmpImg.setRoi(0, 0, newWidth_, newHeight_);
// first channel
gui_.addImage(ACQNAME, tmpImg.crop().getPixels(), 0, 0, 0);
// second channel
if (orientation_.equals(LR)) {
tmpImg.setRoi(newWidth_, 0, newWidth_, height_);
} else if (orientation_.equals(TB)) {
tmpImg.setRoi(0, newHeight_, newWidth_, newHeight_);
}
gui_.addImage(ACQNAME, tmpImg.crop().getPixels(), 0, 1, 0);
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
public void safePrefs() {
prefs_.putInt(FRAMEXPOS, this.getX());
prefs_.putInt(FRAMEYPOS, this.getY());
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
lrRadioButton = new javax.swing.JRadioButton();
tbRadioButton = new javax.swing.JRadioButton();
topLeftColorButton = new javax.swing.JButton();
bottomRightColorButton = new javax.swing.JButton();
snapButton = new javax.swing.JButton();
liveButton = new javax.swing.JButton();
applyToMDACheckBox_ = new javax.swing.JCheckBox();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
});
buttonGroup1.add(lrRadioButton);
lrRadioButton.setText("Left-Right Split");
lrRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lrRadioButtonActionPerformed(evt);
}
});
buttonGroup1.add(tbRadioButton);
tbRadioButton.setText("Top-Botom Split");
tbRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tbRadioButtonActionPerformed(evt);
}
});
topLeftColorButton.setText("Left Color");
topLeftColorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
topLeftColorButtonActionPerformed(evt);
}
});
bottomRightColorButton.setText("Right Color");
bottomRightColorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bottomRightColorButtonActionPerformed(evt);
}
});
snapButton.setText("Snap");
snapButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
snapButtonActionPerformed(evt);
}
});
liveButton.setText("Live");
liveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
liveButtonActionPerformed(evt);
}
});
applyToMDACheckBox_.setText("Apply to Acquisition");
applyToMDACheckBox_.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
applyToMDACheckBox_StateChanged(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(9, 9, 9)
.add(lrRadioButton)
.add(18, 18, 18)
.add(tbRadioButton)
.addContainerGap())
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(topLeftColorButton)
.add(layout.createSequentialGroup()
.add(21, 21, 21)
.add(snapButton)))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 38, Short.MAX_VALUE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(bottomRightColorButton)
.add(layout.createSequentialGroup()
.add(21, 21, 21)
.add(liveButton)))
.add(32, 32, 32))
.add(layout.createSequentialGroup()
.addContainerGap()
.add(applyToMDACheckBox_)
.addContainerGap(130, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(lrRadioButton)
.add(tbRadioButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(topLeftColorButton)
.add(bottomRightColorButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(liveButton)
.add(snapButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(applyToMDACheckBox_)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void lrRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lrRadioButtonActionPerformed
orientation_ = LR;
prefs_.put(ORIENTATION, LR);
topLeftColorButton.setText("Left Color");
bottomRightColorButton.setText("Right Color");
}//GEN-LAST:event_lrRadioButtonActionPerformed
private void tbRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbRadioButtonActionPerformed
orientation_ = TB;
prefs_.put(ORIENTATION, TB);
topLeftColorButton.setText("Top Color");
bottomRightColorButton.setText("Bottom Color");
}//GEN-LAST:event_tbRadioButtonActionPerformed
private void snapButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_snapButtonActionPerformed
doSnap();
}//GEN-LAST:event_snapButtonActionPerformed
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
safePrefs();
}//GEN-LAST:event_formWindowClosed
private void liveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_liveButtonActionPerformed
if (timer_.isRunning()) {
enableLiveMode(false);
liveButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png"));
} else {
timer_.setDelay((int) interval_);
enableLiveMode(true);
liveButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/cancel.png"));
}
}//GEN-LAST:event_liveButtonActionPerformed
private void topLeftColorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topLeftColorButtonActionPerformed
col1_ = JColorChooser.showDialog(getContentPane(), "Choose left/top color", col1_);
topLeftColorButton.setForeground(col1_);
prefs_.putInt(TOPLEFTCOLOR, col1_.getRGB());
try {
if (gui_.acquisitionExists(ACQNAME)) {
gui_.setChannelColor(ACQNAME, 0, col1_);
}
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
}
}//GEN-LAST:event_topLeftColorButtonActionPerformed
private void bottomRightColorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bottomRightColorButtonActionPerformed
col2_ = JColorChooser.showDialog(getContentPane(), "Choose right/bottom color", col2_);
bottomRightColorButton.setForeground(col2_);
prefs_.putInt(BOTTOMRIGHTCOLOR, col2_.getRGB());
try {
if (gui_.acquisitionExists(ACQNAME)) {
gui_.setChannelColor(ACQNAME, 0, col2_);
}
} catch (MMScriptException ex) {
ReportingUtils.logError(ex);
}
}//GEN-LAST:event_bottomRightColorButtonActionPerformed
private void applyToMDACheckBox_StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_applyToMDACheckBox_StateChanged
Object source = evt.getSource();
if (source != applyToMDACheckBox_)
return;
if (applyToMDACheckBox_.isSelected() && !appliedToMDA_) {
mmImageProcessor_ = new SplitViewProcessor();
mmImageProcessor_.setName("SplitView");
gui_.getAcquisitionEngine().addImageProcessor(mmImageProcessor_);
appliedToMDA_ = true;
} else if (!applyToMDACheckBox_.isSelected() && appliedToMDA_) {
if (mmImageProcessor_ != null)
gui_.getAcquisitionEngine().removeImageProcessor(mmImageProcessor_);
appliedToMDA_ = false;
}
}//GEN-LAST:event_applyToMDACheckBox_StateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox applyToMDACheckBox_;
private javax.swing.JButton bottomRightColorButton;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.JButton liveButton;
private javax.swing.JRadioButton lrRadioButton;
private javax.swing.JButton snapButton;
private javax.swing.JRadioButton tbRadioButton;
private javax.swing.JButton topLeftColorButton;
// End of variables declaration//GEN-END:variables
}
|
package org.ayo.view.status;
import android.content.Context;
import android.view.View;
import android.view.ViewParent;
import android.widget.FrameLayout;
public abstract class StatusProvider {
protected View statusView;
protected Context mContext;
protected FrameLayout container;
protected View contentView;
protected String status;
protected OnStatusViewCreateCallback callback;
public interface OnStatusViewCreateCallback{
void onCreate(int status, View statusView);
}
public StatusProvider(Context context, String status, View contentView, OnStatusViewCreateCallback callback){
this.mContext = context;
this.status = status;
this.contentView = contentView;
this.callback = callback;
if(contentView == null){
throw new RuntimeException("contentViewnull");
}
ViewParent p = this.contentView.getParent();
if(p instanceof FrameLayout){
this.container = (FrameLayout) p;
}else{
throw new RuntimeException(contentView.getClass().getName() + "FrameLayout");
}
}
public String getStatus(){
return status;
}
public abstract View getStatusView();
public void showStatusView(){
if(statusView == null){
statusView = getStatusView();
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
container.addView(statusView, lp);
}
statusView.setVisibility(View.VISIBLE);
statusView.bringToFront();
}
public void hideStatusView(){
if(statusView != null){
statusView.setVisibility(View.GONE);
}
}
public void showContentView(){
contentView.setVisibility(View.VISIBLE);
contentView.bringToFront();
}
}
|
package step.resources;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.io.FileUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.hash.Hashing;
import ch.exense.commons.io.FileHelper;
import step.core.objectenricher.ObjectEnricher;
public class ResourceManagerImpl implements ResourceManager {
protected final File resourceRootFolder;
protected final ResourceAccessor resourceAccessor;
protected final ResourceRevisionAccessor resourceRevisionAccessor;
protected final Map<String, ResourceType> resourceTypes;
protected static final Logger logger = LoggerFactory.getLogger(ResourceManagerImpl.class);
public ResourceManagerImpl(File resourceRootFolder, ResourceAccessor resourceAccessor,
ResourceRevisionAccessor resourceRevisionAccessor) {
super();
this.resourceRootFolder = resourceRootFolder;
this.resourceAccessor = resourceAccessor;
this.resourceRevisionAccessor = resourceRevisionAccessor;
this.resourceTypes = new ConcurrentHashMap<>();
resourceTypes.put(RESOURCE_TYPE_TEMP, new CustomResourceType(true));
resourceTypes.put(RESOURCE_TYPE_ATTACHMENT, new CustomResourceType(false));
resourceTypes.put(RESOURCE_TYPE_STAGING_CONTEXT_FILES, new CustomResourceType(false));
resourceTypes.put(RESOURCE_TYPE_FUNCTIONS, new CustomResourceType(false));
resourceTypes.put(RESOURCE_TYPE_DATASOURCE, new CustomResourceType(false));
resourceTypes.put(RESOURCE_TYPE_SECRET, new CustomResourceType(false));
resourceTypes.put(RESOURCE_TYPE_PDF_TEST_SCENARIO_FILE, new CustomResourceType(false));
}
public void registerResourceType(String name, ResourceType resourceType) {
resourceTypes.put(name, resourceType);
}
@Override
public ResourceRevisionContainer createResourceContainer(String resourceType, String resourceFileName) throws IOException {
Resource resource = createResource(resourceType, resourceFileName);
ResourceRevision revision = createResourceRevision(resourceFileName, resource.getId().toString());
createResourceRevisionContainer(resource, revision);
File file = getResourceRevisionFile(resource, revision);
FileOutputStream fileOutputStream = new FileOutputStream(file);
return new ResourceRevisionContainer(resource, revision, fileOutputStream, this);
}
protected void closeResourceContainer(Resource resource, ResourceRevision resourceRevision, boolean checkForDuplicates, ObjectEnricher objectEnricher) throws IOException, SimilarResourceExistingException {
File resourceRevisionFile = getResourceRevisionFile(resource, resourceRevision);
String checksum = getMD5Checksum(resourceRevisionFile);
resourceRevision.setChecksum(checksum);
resourceRevisionAccessor.save(resourceRevision);
resource.setCurrentRevisionId(resourceRevision.getId());
if(objectEnricher != null) {
objectEnricher.accept(resource);
}
resourceAccessor.save(resource);
if(checkForDuplicates) {
List<Resource> resourcesWithSameChecksum = getSimilarResources(resource, resourceRevision);
if(resourcesWithSameChecksum.size()>0) {
throw new SimilarResourceExistingException(resource, resourcesWithSameChecksum);
}
}
}
@Override
public Resource createResource(String resourceType, InputStream resourceStream, String resourceFileName, boolean checkForDuplicates, ObjectEnricher objectEnricher) throws IOException, SimilarResourceExistingException {
ResourceRevisionContainer resourceContainer = createResourceContainer(resourceType, resourceFileName);
FileHelper.copy(resourceStream, resourceContainer.getOutputStream(), 2048);
resourceContainer.save(checkForDuplicates, objectEnricher);
return resourceContainer.getResource();
}
@Override
public Resource saveResourceContent(String resourceId, InputStream resourceStream, String resourceFileName) throws IOException {
Resource resource = getResource(resourceId);
createResourceRevisionAndSaveContent(resourceStream, resourceFileName, resource);
updateResourceFileNameIfNecessary(resourceFileName, resource);
return resource;
}
@Override
public void deleteResource(String resourceId) {
Resource resource = getResource(resourceId);
resourceRevisionAccessor.getResourceRevisionsByResourceId(resourceId).forEachRemaining(revision->{
resourceRevisionAccessor.remove(revision.getId());
});
File resourceContainer = getResourceContainer(resource);
if(resourceContainer.exists()) {
FileHelper.deleteFolder(resourceContainer);
}
resourceAccessor.remove(resource.getId());
}
private List<Resource> getSimilarResources(Resource actualResource, ResourceRevision actualResourceRevision) {
List<Resource> result = new ArrayList<>();
resourceRevisionAccessor.getResourceRevisionsByChecksum(actualResourceRevision.getChecksum()).forEachRemaining(revision->{
if(!revision.getId().equals(actualResourceRevision.getId())) {
Resource resource = resourceAccessor.get(new ObjectId(revision.getResourceId()));
if(resource!=null) {
if (resource.getCurrentRevisionId() != null) {
// ensure it is an active revision i.e a revision that is the current revision of a resource
if(resource.getCurrentRevisionId().equals(revision.getId())) {
try {
if(FileUtils.contentEquals(getResourceRevisionFile(resource, revision), getResourceRevisionFile(actualResource, actualResourceRevision))) {
result.add(resource);
}
} catch (IOException e) {
logger.warn("Error while comparing resource revisions "+revision.getId()+" and "+actualResourceRevision.getId(), e);
}
}
} else {
logger.warn("Found resource without current revision: "+resource.getId());
}
} else {
logger.warn("Found orphan resource revision: "+revision.getId());
}
}
});
return result;
}
@Override
public ResourceRevisionContent getResourceContent(String resourceId) throws IOException {
Resource resource = getResource(resourceId);
ResourceRevision resourceRevision = getCurrentResourceRevision(resource);
return getResourceRevisionContent(resource, resourceRevision);
}
protected void closeResourceRevisionContent(Resource resource) {
if(resource.isEphemeral()) {
deleteResource(resource.getId().toString());
}
}
@Override
public ResourceRevision getResourceRevisionByResourceId(String resourceId) {
Resource resource = getResource(resourceId);
ResourceRevision resourceRevision = getCurrentResourceRevision(resource);
return resourceRevision;
}
@Override
public ResourceRevisionContentImpl getResourceRevisionContent(String resourceRevisionId) throws IOException {
ResourceRevision resourceRevision = getResourceRevision(new ObjectId(resourceRevisionId));
Resource resource = getResource(resourceRevision.getResourceId());
return getResourceRevisionContent(resource, resourceRevision);
}
@Override
public ResourceRevisionFileHandle getResourceFile(String resourceId) {
Resource resource = getResource(resourceId);
ResourceRevision resourceRevision = getCurrentResourceRevision(resource);
File resourceRevisionFile = getResourceRevisionFile(resource, resourceRevision);
return new ResourceRevisionFileHandleImpl(this, resource, resourceRevisionFile);
}
private ResourceRevisionContentImpl getResourceRevisionContent(Resource resource, ResourceRevision resourceRevision)
throws IOException {
File resourceRevisionFile = getResourceRevisionFile(resource, resourceRevision);
if(!resourceRevisionFile.exists() || !resourceRevisionFile.canRead()) {
throw new IOException("The resource revision file "+resourceRevisionFile.getAbsolutePath()+" doesn't exist or cannot be read");
}
FileInputStream resourceRevisionStream = new FileInputStream(resourceRevisionFile);
return new ResourceRevisionContentImpl(this, resource, resourceRevisionStream, resourceRevision.getResourceFileName());
}
private ResourceRevision getCurrentResourceRevision(Resource resource) {
return getResourceRevision(resource.getCurrentRevisionId());
}
private ResourceRevision getResourceRevision(ObjectId resourceRevisionId) {
ResourceRevision resourceRevision = resourceRevisionAccessor.get(resourceRevisionId);
if(resourceRevision == null) {
throw new RuntimeException("The resource revision with ID "+resourceRevisionId+" doesn't exist");
}
return resourceRevision;
}
@Override
public Resource getResource(String resourceId) {
Resource resource = resourceAccessor.get(new ObjectId(resourceId));
if(resource == null) {
throw new RuntimeException("The resource with ID "+resourceId+" doesn't exist");
}
return resource;
}
private File getResourceRevisionFile(Resource resource, ResourceRevision revision) {
return new File(getResourceRevisionContainer(resource, revision).getPath()+"/"+revision.getResourceFileName());
}
private File getResourceRevisionContainer(Resource resource, ResourceRevision revision) {
File containerFile = new File(getResourceContainer(resource).getPath()+"/"+revision.getId().toString());
return containerFile;
}
private File getResourceContainer(Resource resource) {
File containerFile = new File(resourceRootFolder+"/"+resource.getResourceType()+"/"+resource.getId().toString());
return containerFile;
}
private File createResourceRevisionContainer(Resource resource, ResourceRevision revision) throws IOException {
File containerFile = getResourceRevisionContainer(resource, revision);
boolean containerDirectoryCreated = containerFile.mkdirs();
if(!containerDirectoryCreated) {
throw new IOException("Unable to create container for resource "+resource.getId()+" in "+containerFile.getAbsolutePath());
}
return containerFile;
}
private ResourceRevision createResourceRevisionAndSaveContent(InputStream resourceStream, String resourceFileName,
Resource resource) throws IOException {
ResourceRevision revision = createResourceRevision(resourceFileName, resource.getId().toString());
createResourceRevisionContainer(resource, revision);
File resourceFile = saveResourceRevisionContent(resourceStream, resource, revision);
String checksum = getMD5Checksum(resourceFile);
revision.setChecksum(checksum);
resourceRevisionAccessor.save(revision);
resource.setCurrentRevisionId(revision.getId());
resourceAccessor.save(resource);
return revision;
}
private String getMD5Checksum(File file) throws IOException {
String hash = com.google.common.io.Files.hash(file, Hashing.md5()).toString();
return hash;
}
private void updateResourceFileNameIfNecessary(String resourceFileName, Resource resource) {
if(!resource.getResourceName().equals(resourceFileName)) {
Map<String, String> currentAttributes = resource.getAttributes();
if(currentAttributes == null) {
currentAttributes = new HashMap<String, String>();
}
currentAttributes.put("name", resourceFileName);
resource.setAttributes(currentAttributes);
resource.setResourceName(resourceFileName);
resourceAccessor.save(resource);
}
}
private Resource createResource(String resourceTypeId, String name) {
ResourceType resourceType = resourceTypes.get(resourceTypeId);
if(resourceType == null) {
throw new RuntimeException("Unknown resource type "+resourceTypeId);
}
Resource resource = new Resource();
Map<String, String> attributes = new HashMap<>();
attributes.put("name", name);
resource.setAttributes(attributes);
resource.setResourceName(name);
resource.setResourceType(resourceTypeId);
resource.setEphemeral(resourceType.isEphemeral());
return resource;
}
private ResourceRevision createResourceRevision(String resourceFileName, String resourceId) {
ResourceRevision revision = new ResourceRevision();
revision.setResourceFileName(resourceFileName);
revision.setResourceId(resourceId);
return revision;
}
private File saveResourceRevisionContent(InputStream resourceStream, Resource resource, ResourceRevision revision) throws IOException {
File resourceFile = getResourceRevisionFile(resource, revision);
Files.copy(resourceStream, resourceFile.toPath());
return resourceFile;
}
@Override
public Resource lookupResourceByName(String resourceName) {
Map<String, String> attributes = new HashMap<>();
attributes.put("name", resourceName);
return resourceAccessor.findByAttributes(attributes);
}
@Override
public boolean resourceExists(String resourceId) {
Resource resource = resourceAccessor.get(new ObjectId(resourceId));
return resource!=null;
}
@Override
public Resource saveResource(Resource resource) throws IOException {
return resourceAccessor.save(resource);
}
}
|
package oap.security;
import oap.testng.AbstractTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
public class AuthServiceTest extends AbstractTest {
private AuthService authService;
@BeforeTest
public void setUp() {
authService = new AuthService( 1 );
}
@Test
public void testShouldGenerateNewToken() {
final User user = new User();
user.email = "test@example.com";
user.password = "12345";
user.role = Role.ADMIN;
final Token token = authService.generateToken( user );
assertEquals( token.role, Role.ADMIN );
assertEquals( token.userEmail, "test@example.com" );
assertNotNull( token.id );
assertNotNull( token.created );
}
@Test
public void testShouldDeleteExpiredToken() throws InterruptedException {
final User user = new User();
user.email = "test@example.com";
user.password = "12345";
user.role = Role.ADMIN;
authService = new AuthService( 0 );
final String id = authService.generateToken( user ).id;
assertNotNull( id );
Thread.sleep( 100 );
assertThat( authService.getToken( id ) ).isEmpty();
}
}
|
package org.jetbrains.plugins.gradle.util;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.externalSystem.model.DataNode;
import com.intellij.openapi.externalSystem.model.ExternalSystemException;
import com.intellij.openapi.externalSystem.model.ProjectKeys;
import com.intellij.openapi.externalSystem.model.project.ModuleData;
import com.intellij.openapi.externalSystem.model.project.ProjectData;
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.fileChooser.FileTypeDescriptor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileFilters;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.BooleanFunction;
import com.intellij.util.containers.Stack;
import org.gradle.tooling.model.GradleProject;
import org.gradle.tooling.model.gradle.GradleScript;
import org.gradle.util.GUtil;
import org.gradle.wrapper.WrapperConfiguration;
import org.gradle.wrapper.WrapperExecutor;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Objects;
import java.util.Properties;
import static com.intellij.openapi.util.text.StringUtil.*;
import static org.jetbrains.plugins.gradle.util.GradleConstants.EXTENSION;
import static org.jetbrains.plugins.gradle.util.GradleConstants.KOTLIN_DSL_SCRIPT_EXTENSION;
/**
* Holds miscellaneous utility methods.
*
* @author Denis Zhdanov
*/
public class GradleUtil {
private static final String LAST_USED_GRADLE_HOME_KEY = "last.used.gradle.home";
private GradleUtil() { }
/**
* Allows to retrieve file chooser descriptor that filters gradle scripts.
* <p/>
* <b>Note:</b> we want to fall back to the standard {@link FileTypeDescriptor} when dedicated gradle file type
* is introduced (it's processed as groovy file at the moment). We use open project descriptor here in order to show
* custom gradle icon at the file chooser ({@link icons.GradleIcons#Gradle}, is used at the file chooser dialog via
* the dedicated gradle project open processor).
*/
@NotNull
public static FileChooserDescriptor getGradleProjectFileChooserDescriptor() {
return new FileChooserDescriptor(true, false, false, false, false, false)
.withFileFilter(file -> SystemInfo.isFileSystemCaseSensitive
? endsWith(file.getName(), "." + EXTENSION) || endsWith(file.getName(), "." + KOTLIN_DSL_SCRIPT_EXTENSION)
: endsWithIgnoreCase(file.getName(), "." + EXTENSION) || endsWithIgnoreCase(file.getName(), "." + KOTLIN_DSL_SCRIPT_EXTENSION));
}
@NotNull
public static FileChooserDescriptor getGradleHomeFileChooserDescriptor() {
// allow selecting files to avoid confusion:
// on macOS a user can select any file but after clicking OK, dialog is closed, but IDEA doesnt' receive the file and doesn't react
return FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor();
}
public static boolean isGradleDefaultWrapperFilesExist(@Nullable String gradleProjectPath) {
return getWrapperConfiguration(gradleProjectPath) != null;
}
/**
* Tries to retrieve what settings should be used with gradle wrapper for the gradle project located at the given path.
*
* @param gradleProjectPath target gradle project config (*.gradle) path or config file's directory path.
* @return gradle wrapper settings should be used with gradle wrapper for the gradle project located at the given path
* if any; {@code null} otherwise
*/
@Nullable
public static WrapperConfiguration getWrapperConfiguration(@Nullable String gradleProjectPath) {
final File wrapperPropertiesFile = findDefaultWrapperPropertiesFile(gradleProjectPath);
if (wrapperPropertiesFile == null) return null;
final WrapperConfiguration wrapperConfiguration = new WrapperConfiguration();
try {
final Properties props = GUtil.loadProperties(wrapperPropertiesFile);
String distributionUrl = props.getProperty(WrapperExecutor.DISTRIBUTION_URL_PROPERTY);
if(isEmpty(distributionUrl)) {
throw new ExternalSystemException("Wrapper 'distributionUrl' property does not exist!");
} else {
wrapperConfiguration.setDistribution(prepareDistributionUri(distributionUrl, wrapperPropertiesFile));
}
String distributionPath = props.getProperty(WrapperExecutor.DISTRIBUTION_PATH_PROPERTY);
if(!isEmpty(distributionPath)) {
wrapperConfiguration.setDistributionPath(distributionPath);
}
String distPathBase = props.getProperty(WrapperExecutor.DISTRIBUTION_BASE_PROPERTY);
if(!isEmpty(distPathBase)) {
wrapperConfiguration.setDistributionBase(distPathBase);
}
String zipStorePath = props.getProperty(WrapperExecutor.ZIP_STORE_PATH_PROPERTY);
if(!isEmpty(zipStorePath)) {
wrapperConfiguration.setZipPath(zipStorePath);
}
String zipStoreBase = props.getProperty(WrapperExecutor.ZIP_STORE_BASE_PROPERTY);
if(!isEmpty(zipStoreBase)) {
wrapperConfiguration.setZipBase(zipStoreBase);
}
return wrapperConfiguration;
}
catch (Exception e) {
GradleLog.LOG.warn(
String.format("I/O exception on reading gradle wrapper properties file at '%s'", wrapperPropertiesFile.getAbsolutePath()), e);
}
return null;
}
private static URI prepareDistributionUri(String distributionUrl, File propertiesFile) throws URISyntaxException {
URI source = new URI(distributionUrl);
return source.getScheme() != null ? source : new File(propertiesFile.getParentFile(), source.getSchemeSpecificPart()).toURI();
}
/**
* Allows to build file system path to the target gradle sub-project given the root project path.
*
* @param subProject target sub-project which config path we're interested in
* @param rootProjectPath path to root project's directory which contains 'build.gradle'
* @return path to the given sub-project's directory which contains 'build.gradle'
*/
@NotNull
public static String getConfigPath(@NotNull GradleProject subProject, @NotNull String rootProjectPath) {
try {
GradleScript script = subProject.getBuildScript();
if (script != null) {
File file = script.getSourceFile();
if (file != null) {
if (!file.isDirectory()) {
// The file points to 'build.gradle' at the moment but we keep it's parent dir path instead.
file = file.getParentFile();
}
return ExternalSystemApiUtil.toCanonicalPath(file.getCanonicalPath());
}
}
}
catch (Exception e) {
// As said by gradle team: 'One thing I'm interested in is whether you have any thoughts about how the tooling API should
// deal with missing details from the model - for example, when asking for details about the build scripts when using
// a version of Gradle that does not supply that information. Currently, you'll get a `UnsupportedOperationException`
// when you call the `getBuildScript()` method'.
// So, just ignore it and assume that the user didn't define any custom build file name.
}
File rootProjectParent = new File(rootProjectPath);
StringBuilder buffer = new StringBuilder(FileUtil.toCanonicalPath(rootProjectParent.getAbsolutePath()));
Stack<String> stack = new Stack<>();
for (GradleProject p = subProject; p != null; p = p.getParent()) {
stack.push(p.getName());
}
// pop root project
stack.pop();
while (!stack.isEmpty()) {
buffer.append(ExternalSystemConstants.PATH_SEPARATOR).append(stack.pop());
}
return buffer.toString();
}
@NotNull
public static String getLastUsedGradleHome() {
return PropertiesComponent.getInstance().getValue(LAST_USED_GRADLE_HOME_KEY, "");
}
public static void storeLastUsedGradleHome(@Nullable String gradleHomePath) {
PropertiesComponent.getInstance().setValue(LAST_USED_GRADLE_HOME_KEY, gradleHomePath, null);
}
@Nullable
public static File findDefaultWrapperPropertiesFile(@Nullable String gradleProjectPath) {
if (gradleProjectPath == null) {
return null;
}
File file = new File(gradleProjectPath);
// There is a possible case that given path points to a gradle script (*.gradle) but it's also possible that
// it references script's directory. We want to provide flexibility here.
File gradleDir;
if (file.isFile()) {
gradleDir = new File(file.getParentFile(), "gradle");
}
else {
gradleDir = new File(file, "gradle");
}
if (!gradleDir.isDirectory()) {
return null;
}
File wrapperDir = new File(gradleDir, "wrapper");
if (!wrapperDir.isDirectory()) {
return null;
}
File[] candidates = wrapperDir.listFiles(FileFilters.filesWithExtension("properties"));
if (candidates == null) {
GradleLog.LOG.warn("No *.properties file is found at the gradle wrapper directory " + wrapperDir.getAbsolutePath());
return null;
}
else if (candidates.length != 1) {
GradleLog.LOG.warn(String.format(
"%d *.properties files instead of one have been found at the wrapper directory (%s): %s",
candidates.length, wrapperDir.getAbsolutePath(), Arrays.toString(candidates)
));
return null;
}
return candidates[0];
}
@NotNull
public static String determineRootProject(@NotNull String subProjectPath) {
final Path subProject = Paths.get(subProjectPath);
Path candidate = subProject;
try {
while (candidate != null && candidate != candidate.getParent()) {
if (containsGradleSettingsFile(candidate)) {
return candidate.toString();
}
candidate = candidate.getParent();
}
} catch (IOException e) {
GradleLog.LOG.warn("Failed to determine root Gradle project directory for [" + subProjectPath + "]", e);
}
return Files.isDirectory(subProject) ? subProjectPath : subProject.getParent().toString();
}
private static boolean containsGradleSettingsFile(Path directory) throws IOException {
return Files.isDirectory(directory) && Files.walk(directory, 1)
.map(Path::getFileName)
.filter(Objects::nonNull)
.map(Path::toString)
.anyMatch(name -> name.startsWith("settings.gradle"));
}
/**
* Finds real external module data by ide module
*
* Module 'module' -> ModuleData 'module'
* Module 'module.main' -> ModuleData 'module' instead of GradleSourceSetData 'module.main'
* Module 'module.test' -> ModuleData 'module' instead of GradleSourceSetData 'module.test'
*/
@ApiStatus.Experimental
@Nullable
public static DataNode<ModuleData> findGradleModuleData(@NotNull Module module) {
String projectPath = ExternalSystemApiUtil.getExternalProjectPath(module);
if (projectPath == null) return null;
Project project = module.getProject();
DataNode<ProjectData> projectNode = ExternalSystemApiUtil.findProjectData(project, GradleConstants.SYSTEM_ID, projectPath);
if (projectNode == null) return null;
BooleanFunction<DataNode<ModuleData>> predicate = node -> projectPath.equals(node.getData().getLinkedExternalProjectPath());
return ExternalSystemApiUtil.find(projectNode, ProjectKeys.MODULE, predicate);
}
}
|
package org.jetbrains.plugins.groovy.util;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.PluginPathManager;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.pom.PomDeclarationSearcher;
import com.intellij.pom.PomTarget;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture;
import com.intellij.util.CollectConsumer;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.LocalTimeCounter;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.extensions.NamedArgumentDescriptor;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.junit.Assert;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* Utility class, that contains various methods for testing
*
* @author Ilya.Sergey
*/
public abstract class TestUtils {
public static final String TEMP_FILE = "temp.groovy";
public static final String GSP_TEMP_FILE = "temp.gsp";
public static final String CARET_MARKER = "<caret>";
public static final String BEGIN_MARKER = "<begin>";
public static final String END_MARKER = "<end>";
public static final String GROOVY_JAR = "groovy-all.jar";
public static final String GROOVY_JAR_17 = "groovy-all-1.7.jar";
public static final String GROOVY_JAR_18 = "groovy-1.8.0-beta-2.jar";
public static final String GROOVY_JAR_21 = "groovy-all-2.1.3.jar";
public static final String GROOVY_JAR_22 = "groovy-all-2.2.0-beta-1.jar";
public static final String GROOVY_JAR_23 = "groovy-all-2.3.0.jar";
public static final String GROOVY_JAR_30 = "groovy-3.0.0-alpha-2.jar";
public static String getMockJdkHome() {
return getAbsoluteTestDataPath() + "/mockJDK";
}
public static String getMockGroovyLibraryHome() {
return getAbsoluteTestDataPath() + "/mockGroovyLib";
}
public static String getMockGroovy1_6LibraryName() {
return getAbsoluteTestDataPath() + "/mockGroovyLib1.6/lib/groovy-all-1.6.jar";
}
public static String getMockGroovy1_7LibraryHome() {
return getAbsoluteTestDataPath() + "/mockGroovyLib1.7";
}
public static String getMockGroovy1_7LibraryName() {
return getMockGroovy1_7LibraryHome()+"/groovy-all-1.7.3.jar";
}
public static String getMockGroovy1_8LibraryHome() {
return getAbsoluteTestDataPath() + "/mockGroovyLib1.8";
}
public static String getMockGroovy2_1LibraryHome() {
return getAbsoluteTestDataPath() + "/mockGroovyLib2.1";
}
private static String getMockGroovy2_2LibraryHome() {
return getAbsoluteTestDataPath() + "/mockGroovyLib2.2";
}
private static String getMockGroovy2_3LibraryHome() {
return getAbsoluteTestDataPath() + "/mockGroovyLib2.3";
}
private static String getMockGroovy3_0LibraryHome() {
return getAbsoluteTestDataPath() + "/mockGroovyLib3.0";
}
public static String getMockGroovy1_8LibraryName() {
return getMockGroovy1_8LibraryHome() + "/" + GROOVY_JAR_18;
}
public static String getMockGroovy2_1LibraryName() {
return getMockGroovy2_1LibraryHome() + "/" + GROOVY_JAR_21;
}
public static String getMockGroovy2_2LibraryName() {
return getMockGroovy2_2LibraryHome() + "/" + GROOVY_JAR_22;
}
public static String getMockGroovy2_3LibraryName() {
return getMockGroovy2_3LibraryHome() + "/" + GROOVY_JAR_23;
}
public static String getMockGroovy3_0LibraryName() {
return getMockGroovy3_0LibraryHome() + "/" + GROOVY_JAR_30;
}
public static PsiFile createPseudoPhysicalGroovyFile(final Project project, final String text) throws IncorrectOperationException {
return createPseudoPhysicalFile(project, TEMP_FILE, text);
}
public static PsiFile createPseudoPhysicalFile(final Project project, final String fileName, final String text) throws IncorrectOperationException {
return PsiFileFactory.getInstance(project).createFileFromText(
fileName,
FileTypeManager.getInstance().getFileTypeByFileName(fileName),
text,
LocalTimeCounter.currentTime(),
true);
}
public static String getAbsoluteTestDataPath() {
return FileUtil.toSystemIndependentName(PluginPathManager.getPluginHomePath("groovy")) + "/testdata/";
}
public static String getTestDataPath() {
return FileUtil.toSystemIndependentName(PluginPathManager.getPluginHomePathRelative("groovy")) + "/testdata/";
}
public static String removeBeginMarker(String text) {
int index = text.indexOf(BEGIN_MARKER);
return text.substring(0, index) + text.substring(index + BEGIN_MARKER.length());
}
public static String removeEndMarker(String text) {
int index = text.indexOf(END_MARKER);
return text.substring(0, index) + text.substring(index + END_MARKER.length());
}
public static List<String> readInput(String filePath) {
String content;
try {
content = StringUtil.convertLineSeparators(FileUtil.loadFile(new File(filePath)));
}
catch (IOException e) {
throw new RuntimeException(e);
}
Assert.assertNotNull(content);
List<String> input = new ArrayList<>();
int separatorIndex;
content = StringUtil.replace(content, "\r", ""); // for MACs
while ((separatorIndex = content.indexOf("
input.add(content.substring(0, separatorIndex - 1));
content = content.substring(separatorIndex);
while (StringUtil.startsWithChar(content, '-')) {
content = content.substring(1);
}
if (StringUtil.startsWithChar(content, '\n')) {
content = content.substring(1);
}
}
input.add(content);
Assert.assertTrue("No data found in source file", input.size() > 0);
Assert.assertTrue("Test output points to null", input.size() > 1);
return input;
}
public static void checkCompletionContains(JavaCodeInsightTestFixture fixture, PsiFile file, String ... expectedVariants) {
fixture.configureFromExistingVirtualFile(file.getVirtualFile());
checkCompletionContains(fixture, expectedVariants);
}
public static void checkCompletionContains(JavaCodeInsightTestFixture fixture, String ... expectedVariants) {
LookupElement[] lookupElements = fixture.completeBasic();
Assert.assertNotNull(lookupElements);
Set<String> missedVariants = ContainerUtil.newHashSet(expectedVariants);
for (LookupElement lookupElement : lookupElements) {
String lookupString = lookupElement.getLookupString();
missedVariants.remove(lookupString);
Object object = lookupElement.getObject();
if (object instanceof ResolveResult) {
object = ((ResolveResult)object).getElement();
}
if (object instanceof PsiMethod) {
missedVariants.remove(lookupString + "()");
}
else if (object instanceof PsiVariable) {
missedVariants.remove('@' + lookupString);
}
else if (object instanceof NamedArgumentDescriptor) {
missedVariants.remove(lookupString + ':');
}
}
if (missedVariants.size() > 0) {
Assert.fail("Some completion variants are missed " + missedVariants);
}
}
public static void checkCompletionType(JavaCodeInsightTestFixture fixture, String lookupString, String expectedTypeCanonicalText) {
LookupElement[] lookupElements = fixture.completeBasic();
PsiType type = null;
for (LookupElement lookupElement : lookupElements) {
if (lookupElement.getLookupString().equals(lookupString)) {
PsiElement element = lookupElement.getPsiElement();
if (element instanceof PsiField) {
type = ((PsiField)element).getType();
break;
}
if (element instanceof PsiMethod) {
type = ((PsiMethod)element).getReturnType();
break;
}
}
}
if (type == null) {
Assert.fail("No field or method called '" + lookupString + "' found in completion lookup elements");
}
Assert.assertEquals(expectedTypeCanonicalText, type.getCanonicalText());
}
public static void checkResolve(PsiFile file, final String ... expectedUnresolved) {
final List<String> actualUnresolved = new ArrayList<>();
final StringBuilder sb = new StringBuilder();
final String text = file.getText();
final Ref<Integer> lastUnresolvedRef = Ref.create(0);
file.acceptChildren(new PsiRecursiveElementVisitor() {
@Override
public void visitElement(PsiElement element) {
if (element instanceof GrReferenceExpression) {
GrReferenceExpression psiReference = (GrReferenceExpression)element;
GrExpression qualifier = psiReference.getQualifierExpression();
if (qualifier instanceof GrReferenceExpression) {
if (((GrReferenceExpression)qualifier).resolve() == null) {
super.visitElement(element);
return;
}
}
if (psiReference.resolve() == null) {
CollectConsumer<PomTarget> consumer = new CollectConsumer<>();
for (PomDeclarationSearcher searcher : PomDeclarationSearcher.EP_NAME.getExtensions()) {
searcher.findDeclarationsAt(psiReference, 0, consumer);
if (consumer.getResult().size() > 0) break;
}
if (consumer.getResult().isEmpty()) {
PsiElement nameElement = psiReference.getReferenceNameElement();
assert nameElement != null;
String name = nameElement.getText();
assert name.equals(psiReference.getReferenceName());
int last = lastUnresolvedRef.get();
sb.append(text, last, nameElement.getTextOffset());
sb.append('!').append(name).append('!');
lastUnresolvedRef.set(nameElement.getTextOffset() + nameElement.getTextLength());
actualUnresolved.add(name);
return;
}
}
}
super.visitElement(element);
}
@Override
public void visitFile(PsiFile file) {
}
});
sb.append("\n\n");
Assert.assertEquals(sb.toString(), Arrays.asList(expectedUnresolved), actualUnresolved);
}
public static PsiMethod[] getMethods(PsiClass aClass) {
//workaround for IDEA-148973: Groovy static compilation fails to compile calls of overriding methods with covariant type in interfaces
return aClass.getMethods();
}
public static void disableAstLoading(@NotNull Project project, @NotNull Disposable parent) {
PsiManagerEx.getInstanceEx(project).setAssertOnFileLoadingFilter(VirtualFileFilter.ALL, parent);
}
}
|
package org.haxe.duell;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
// import android.system.Os;
// import android.system.OsConstants;
import android.system.ErrnoException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import org.haxe.HXCPP;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
public class DuellActivity extends Activity
{
private static WeakReference<DuellActivity> activity = new WeakReference<DuellActivity>(null);
private final Handler mainJavaThreadHandler;
private MainHaxeThreadHandler mainHaxeThreadHandler;
/** Exposes the parent so that it can be used to set the content view instead */
public FrameLayout parent;
/// libraries that initialize a view, may choose to set this, so that other libraries can act upon this
public WeakReference<View> mainView;
private final List<Extension> extensions;
public DuellActivity()
{
DuellActivity.activity = new WeakReference<DuellActivity>(this);
mainView = new WeakReference<View>(null);
mainJavaThreadHandler = new Handler();
// default handler
mainHaxeThreadHandler = new MainHaxeThreadHandler()
{
@Override
public void queueRunnableOnMainHaxeThread(Runnable runObj)
{
mainJavaThreadHandler.post(runObj);
}
};
extensions = new ArrayList<Extension>();
::foreach PLATFORM.ACTIVITY_EXTENSIONS::;
extensions.add(new ::__current__:: ());::end::
}
public static DuellActivity getInstance()
{
return activity.get();
}
protected void onCreate(Bundle state)
{
super.onCreate(state);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
// /// MAKE SURE WE ALWAYS HAVE CRASHLOGS
// /// Only available for Lolipop and above
// try
// Os.prctl(OsConstants.PR_SET_DUMPABLE, 1, 0, 0, 0);
// catch(ErrnoException exception)
// Log.d("DUELL", "prctl error:" + exception.getMessage());
::if PLATFORM.FULLSCREEN::
::if (PLATFORM.TARGET_SDK_VERSION < 19)::
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
::end::
::end::
::foreach NDLLS::
System.loadLibrary("::NAME::");::end::
;parent = new FrameLayout(this);
super.setContentView(parent);
HXCPP.run("HaxeApplication");
for (Extension extension : extensions)
{
extension.onCreate(state);
}
}
::if (PLATFORM.FULLSCREEN)::
::if (PLATFORM.TARGET_SDK_VERSION >= 19)::
// IMMERSIVE MODE SUPPORT
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
{
hideSystemUi();
}
}
private void hideSystemUi()
{
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
::end::
::end::
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
for (Extension extension : extensions)
{
if (!extension.onActivityResult(requestCode, resultCode, data))
{
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onDestroy()
{
for (Extension extension : extensions)
{
extension.onDestroy();
}
activity = new WeakReference<DuellActivity>(null);
super.onDestroy();
}
@Override
public void onLowMemory()
{
super.onLowMemory();
for (Extension extension : extensions)
{
extension.onLowMemory();
}
}
@Override
protected void onNewIntent(final Intent intent)
{
for (Extension extension : extensions)
{
extension.onNewIntent(intent);
}
super.onNewIntent(intent);
}
@Override
protected void onPause()
{
super.onPause();
for (Extension extension : extensions)
{
extension.onPause();
}
}
@Override
protected void onRestart()
{
super.onRestart();
for (Extension extension : extensions)
{
extension.onRestart();
}
}
@Override
protected void onResume()
{
super.onResume();
for (Extension extension : extensions)
{
extension.onResume();
}
}
@Override
protected void onStart()
{
super.onStart();
::if PLATFORM.FULLSCREEN::::if (PLATFORM.ANDROID_TARGET_SDK_VERSION >= 16)::
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN);
}
::end::::end::
for (Extension extension : extensions)
{
extension.onStart();
}
}
@Override
protected void onStop()
{
super.onStop();
for (Extension extension : extensions)
{
extension.onStop();
}
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
for (Extension extension : extensions)
{
extension.onSaveInstanceState(outState);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
for (Extension extension : extensions)
{
extension.onKeyDown(keyCode, event);
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event)
{
for (Extension extension : extensions)
{
extension.onKeyUp(keyCode, event);
}
return super.onKeyUp(keyCode, event);
}
::if (PLATFORM.TARGET_SDK_VERSION >= 14)::
@Override
public void onTrimMemory(int level)
{
super.onTrimMemory(level);
for (Extension extension : extensions)
{
extension.onTrimMemory(level);
}
}
::end::
public void registerExtension(Extension extension)
{
if (extensions.indexOf(extension) == -1)
{
extensions.add(extension);
}
}
/// post to this queue any java to haxe communication on the main thread.
/// may be set by extension to be something else, for example, the opengl library can setMainThreadHandler
/// to be processed in the gl thread because it is generally preferable to communicate with haxe by that.
/// defaults to itself
public void queueOnHaxeThread(Runnable run)
{
mainHaxeThreadHandler.queueRunnableOnMainHaxeThread(run);
}
/// if you want to force some callback to be executed on the main thread
public void queueOnMainThread(Runnable run)
{
mainJavaThreadHandler.post(run);
}
public void setMainHaxeThreadHandler(MainHaxeThreadHandler handler)
{
mainHaxeThreadHandler = handler;
}
@Override
public void setContentView(View view)
{
throw new IllegalStateException("Callers should interact with the parent FrameLayout instead of with the view directly");
}
}
|
package com.valkryst.generator;
import com.valkryst.TestHelper;
import com.valkryst.builder.CombinatorialBuilder;
import org.junit.Test;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.IntUnaryOperator;
public class CombinatorialNameGeneratorTest {
@Test
public void generateName() {
// Setup the Builder:
final CombinatorialBuilder builder = new CombinatorialBuilder();
try {
builder.setBeginnings(TestHelper.resource("Dwarven/Fantasy/Khordaldrum_Last_A.txt"));
builder.setEndings(TestHelper.resource("Dwarven/Fantasy/Khordaldrum_Last_B.txt"));
} catch (final IOException e) {
e.printStackTrace();
}
// Setup & Test the Generator:
final CombinatorialNameGenerator generator = builder.build(false);
for (int i = 0 ; i < 100 ; i++) {
generator.generateName(i % 20, 0);
}
}
@Test
public void longGeneration() {
// Setup the Builder:
final CombinatorialBuilder builder = new CombinatorialBuilder();
try {
builder.setBeginnings(TestHelper.resource("Dwarven/Fantasy/Khordaldrum_Last_A.txt"));
builder.setEndings(TestHelper.resource("Dwarven/Fantasy/Khordaldrum_Last_B.txt"));
} catch (final IOException e) {
e.printStackTrace();
}
// Setup & Test the Generator:
final CombinatorialNameGenerator generator = builder.build(false);
for (int i = 0 ; i < 100 ; i++) {
System.out.println(generator.generateName(i, 0));
}
for (int i = 0 ; i < 1_000_000 ; i++) {
generator.generateName(i % 20, 0);
}
}
}
|
package com.rbmhtechnology.vind.test;
import com.rbmhtechnology.vind.SearchServerException;
import com.rbmhtechnology.vind.annotations.language.Language;
import com.rbmhtechnology.vind.api.Document;
import com.rbmhtechnology.vind.api.SearchServer;
import com.rbmhtechnology.vind.api.query.FulltextSearch;
import com.rbmhtechnology.vind.api.query.Search;
import com.rbmhtechnology.vind.api.query.datemath.DateMathExpression;
import com.rbmhtechnology.vind.api.query.delete.Delete;
import com.rbmhtechnology.vind.api.query.facet.Facet;
import com.rbmhtechnology.vind.api.query.facet.Interval;
import com.rbmhtechnology.vind.api.query.facet.TermFacetOption;
import com.rbmhtechnology.vind.api.query.filter.Filter;
import com.rbmhtechnology.vind.api.query.suggestion.DescriptorSuggestionSearch;
import com.rbmhtechnology.vind.api.query.suggestion.ExecutableSuggestionSearch;
import com.rbmhtechnology.vind.api.query.update.Update;
import com.rbmhtechnology.vind.api.result.DeleteResult;
import com.rbmhtechnology.vind.api.result.GetResult;
import com.rbmhtechnology.vind.api.result.PageResult;
import com.rbmhtechnology.vind.api.result.SearchResult;
import com.rbmhtechnology.vind.api.result.SuggestionResult;
import com.rbmhtechnology.vind.api.result.facet.RangeFacetResult;
import com.rbmhtechnology.vind.api.result.facet.TermFacetResult;
import com.rbmhtechnology.vind.configure.SearchConfiguration;
import com.rbmhtechnology.vind.model.ComplexFieldDescriptorBuilder;
import com.rbmhtechnology.vind.model.DocumentFactory;
import com.rbmhtechnology.vind.model.DocumentFactoryBuilder;
import com.rbmhtechnology.vind.model.FieldDescriptor;
import com.rbmhtechnology.vind.model.FieldDescriptorBuilder;
import com.rbmhtechnology.vind.model.MultiValueFieldDescriptor;
import com.rbmhtechnology.vind.model.MultiValueFieldDescriptor.NumericFieldDescriptor;
import com.rbmhtechnology.vind.model.MultiValuedComplexField;
import com.rbmhtechnology.vind.model.SingleValueFieldDescriptor;
import com.rbmhtechnology.vind.model.SingleValuedComplexField;
import com.rbmhtechnology.vind.model.value.LatLng;
import org.apache.commons.lang3.tuple.Pair;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static com.rbmhtechnology.vind.api.query.datemath.DateMathExpression.TimeUnit.DAY;
import static com.rbmhtechnology.vind.api.query.datemath.DateMathExpression.TimeUnit.HOUR;
import static com.rbmhtechnology.vind.api.query.datemath.DateMathExpression.TimeUnit.MILLISECONDS;
import static com.rbmhtechnology.vind.api.query.datemath.DateMathExpression.TimeUnit.YEAR;
import static com.rbmhtechnology.vind.api.query.facet.Facets.interval;
import static com.rbmhtechnology.vind.api.query.facet.Facets.pivot;
import static com.rbmhtechnology.vind.api.query.facet.Facets.query;
import static com.rbmhtechnology.vind.api.query.facet.Facets.range;
import static com.rbmhtechnology.vind.api.query.facet.Facets.stats;
import static com.rbmhtechnology.vind.api.query.facet.Facets.type;
import static com.rbmhtechnology.vind.api.query.filter.Filter.Scope;
import static com.rbmhtechnology.vind.api.query.filter.Filter.and;
import static com.rbmhtechnology.vind.api.query.filter.Filter.before;
import static com.rbmhtechnology.vind.api.query.filter.Filter.eq;
import static com.rbmhtechnology.vind.api.query.filter.Filter.hasChildrenDocuments;
import static com.rbmhtechnology.vind.api.query.filter.Filter.not;
import static com.rbmhtechnology.vind.api.query.filter.Filter.or;
import static com.rbmhtechnology.vind.api.query.sort.Sort.Direction;
import static com.rbmhtechnology.vind.api.query.sort.Sort.SpecialSort.distance;
import static com.rbmhtechnology.vind.api.query.sort.Sort.SpecialSort.score;
import static com.rbmhtechnology.vind.api.query.sort.Sort.SpecialSort.scoredDate;
import static com.rbmhtechnology.vind.api.query.sort.Sort.asc;
import static com.rbmhtechnology.vind.api.query.sort.Sort.desc;
import static com.rbmhtechnology.vind.api.query.sort.Sort.field;
import static com.rbmhtechnology.vind.model.MultiValueFieldDescriptor.DateFieldDescriptor;
import static com.rbmhtechnology.vind.model.MultiValueFieldDescriptor.TextFieldDescriptor;
import static com.rbmhtechnology.vind.test.Backend.Elastic;
import static com.rbmhtechnology.vind.test.Backend.Solr;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* @author Thomas Kurz (tkurz@apache.org)
* @since 15.06.16.
*/
public class ServerTest {
@Rule
public TestBackend testBackend = new TestBackend();
@Test
@RunWithBackend({Solr, Elastic})
public void testEmbeddedSolr() {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime yesterday = ZonedDateTime.now(ZoneId.of("UTC")).minus(1, ChronoUnit.DAYS);
FieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("title.test.test");
SingleValueFieldDescriptor.DateFieldDescriptor<ZonedDateTime> created = new FieldDescriptorBuilder()
.setFacet(true)
.buildDateField("created");
SingleValueFieldDescriptor.UtilDateFieldDescriptor<Date> modified = new FieldDescriptorBuilder()
.setFacet(true)
.buildUtilDateField("modified");
NumericFieldDescriptor<Long> category = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedNumericField("category", Long.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(title)
.addField(created)
.addField(category)
.addField(modified)
.build();
Document d1 = assets.createDoc("1")
.setValue(title, "Hello World")
.setValue(created, yesterday)
.setValue(modified, new Date())
.setValues(category, Arrays.asList(1L, 2L));
Document d2 = assets.createDoc("2")
.setValue(title, "Hello Friends")
.setValue(created, now)
.setValue(modified, new Date())
.addValue(category, 4L);
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.commit();
Interval.ZonedDateTimeInterval i1 = Interval.dateInterval("past_24_hours", ZonedDateTime.now().minus(Duration.ofDays(1)), ZonedDateTime.now());
Interval.ZonedDateTimeInterval i2 = Interval.dateInterval("past_week", ZonedDateTime.now().minus(Duration.ofDays(7)), ZonedDateTime.now());
FulltextSearch search = Search.fulltext("hello")
.filter(category.between(0, 10))
.filter(not(created.after(ZonedDateTime.now())))
.filter(modified.before(new Date()))
.facet(pivot("cats", category, created))
.facet(pivot("catVStitle", category, title))
.facet(stats("avg Cat", category, "cats", "catVStitle").count().sum().percentiles(9.9, 1.0).mean())
.facet(stats("countDate", created).count().sum().mean())
.facet(query("new An dHot", category.between(0, 5), "cats"))
.facet(query("anotherQuery", and(category.between(7, 10), created.after(ZonedDateTime.now().minus(Duration.ofDays(1))))))
.facet(range("dates", created, ZonedDateTime.now().minus(Duration.ofDays(1)), ZonedDateTime.now(), Duration.ofHours(1)))
.facet(range("mod a", modified, new Date(), new Date(), 1L, TimeUnit.HOURS, "cats"))
.facet(interval("quality", category, Interval.numericInterval("low", 0L, 2L), Interval.numericInterval("high", 3L, 4L)))
.facet(interval("time", created, i1, i2))
.facet(interval("time2", modified,
Interval.dateInterval("early", new Date(0), new Date(10000)),
Interval.dateInterval("late", new Date(10000), new Date(20000))))
.facet(category)
.facet(created)
.facet(modified)
.facet(new TermFacetOption().setPrefix("He"), title)
.page(1, 25)
.sort(desc(created));
PageResult result = (PageResult)server.execute(search,assets);
assertEquals(2, result.getNumOfResults());
assertEquals(2, result.getResults().size());
assertEquals("2", result.getResults().get(0).getId());
assertEquals("asset", result.getResults().get(0).getType());
assertEquals("2", result.getResults().get(0).getId());
assertEquals("asset", result.getResults().get(0).getType());
assertTrue(now.equals(result.getResults().get(0).getValue(created)));
assertTrue(now.equals(result.getResults().get(0).getValue("created")));
assertEquals(2, result.getFacetResults().getIntervalFacet("quality").getValues().size());
assertEquals(2, result.getFacetResults().getIntervalFacet("time").getValues().size());
System.out.println(result);
PageResult next = (PageResult)result.nextPage();
SearchResult prev = next.previousPage();
TermFacetResult<Long> facet = result.getFacetResults().getTermFacet(category);
RangeFacetResult<ZonedDateTime> dates = result.getFacetResults().getRangeFacet("dates", ZonedDateTime.class);
ZonedDateTime rangeDate = dates.getValues().get(0).getValue();
}
@Test
@RunWithBackend({Solr, Elastic})
public void testSuggestions() {
SearchServer server = testBackend.getSearchServer();
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime yesterday = ZonedDateTime.now().minus(1, ChronoUnit.DAYS);
FieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.setSuggest(true)
.buildTextField("title");
SingleValueFieldDescriptor.DateFieldDescriptor<ZonedDateTime> created = new FieldDescriptorBuilder()
.setFacet(true)
.buildDateField("created");
NumericFieldDescriptor<Long> category = new FieldDescriptorBuilder()
.setFacet(true)
.setSuggest(true)
.buildMultivaluedNumericField("category", Long.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(title)
.addField(created)
.addField(category)
.build();
Document d1 = assets.createDoc("1")
.setValue(title, "Hello 4 World")
.setValue(created, yesterday)
.setValues(category, Arrays.asList(1L, 2L, 4L));
Document d2 = assets.createDoc("2")
.setValue(title, "Hello 4 Friends")
.setValue(created, now)
.addValue(category, 4L);
server.index(d1);
server.index(d2);
server.commit(true);
SuggestionResult emptySuggestion = server.execute(Search.suggest().addField(title).filter(created.before(ZonedDateTime.now().minus(6, ChronoUnit.DAYS))).text("Hel"), assets);
assertTrue(emptySuggestion.size() == 0);
SuggestionResult suggestion = server.execute(Search.suggest().fields(title, category).filter(created.before(ZonedDateTime.now().minus(6, ChronoUnit.HOURS))).text("4"), assets);
assertTrue(suggestion.size() > 0);
suggestion = server.execute(Search.suggest("helli").fields(title, category), assets);
assertEquals("hello", suggestion.getSpellcheck());
}
@Test
@RunWithBackend({Solr, Elastic})
public void testTypeIDScoreAsFieldname() {
SearchServer server = testBackend.getSearchServer();
FieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("title");
FieldDescriptor<String> id = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("id");
FieldDescriptor<String> type = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("type");
FieldDescriptor<String> score = new FieldDescriptorBuilder()
.setFacet(true)
.buildTextField("score");
DocumentFactory factory = new DocumentFactoryBuilder("test")
.addField(score, type, id, title)
.build();
server.index(factory.createDoc("1").setValue(title, "Title").setValue(id, "ID").setValue(type, "TYPE").setValue(score, "Score"));
server.commit();
SearchResult result = server.execute(Search.fulltext().facet("id", "type", "score"), factory);
assertEquals(1, result.getNumOfResults());
Document doc = result.getResults().get(0);
assertEquals("ID", doc.getValue("id"));
assertEquals("Title", doc.getValue("title"));
assertEquals("Score", doc.getValue("score"));
assertEquals("TYPE", doc.getValue("type"));
assertEquals(1.0, doc.getScore(), 0);
assertEquals("test", doc.getType());
assertEquals("1", doc.getId());
}
@Test
@RunWithBackend({Solr, Elastic})
public void testPartialUpdate() {
SearchServer server = testBackend.getSearchServer();
SingleValueFieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.buildTextField("title");
MultiValueFieldDescriptor.DateFieldDescriptor<ZonedDateTime> created = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedDateField("created");
NumericFieldDescriptor<Long> category = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedNumericField("category", Long.class);
SingleValueFieldDescriptor.NumericFieldDescriptor<Integer> count = new FieldDescriptorBuilder()
.setFacet(true)
.buildNumericField("count", Integer.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.setUpdatable(true)
.addField(title, created, category, count)
.build();
ZonedDateTime now = ZonedDateTime.now();
Document d1 = assets.createDoc("123")
.setValue(title, "Hello World")
.setValue(count, 0)
.setValues(category, 1L, 2L, 3L)
.addValue(created, now);
server.index(d1);
server.commit();
server.execute(Search.update("123").set(title, "123").add(category, 6L, 10L).remove(created, now)/*.removeRegex(category, "10")*/.increment(count, 1), assets);
server.commit();
SearchResult result = server.execute(Search.fulltext("123"), assets);
assertEquals(1, result.getResults().size());
assertEquals("123", result.getResults().get(0).getValue("_id_"));
assertEquals("asset", result.getResults().get(0).getType());
server.execute(Search.update("123").remove(category).increment(count, -1), assets);
server.commit();
SearchResult result2 = server.execute(Search.fulltext(), assets);
assertEquals(1, result2.getResults().size());
}
@Ignore
@Test
@RunWithBackend(Solr)
public void testSubdocuments() throws IOException {
SearchServer server = testBackend.getSearchServer();
SingleValueFieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("title");
SingleValueFieldDescriptor<String> color = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("color");
DocumentFactory asset = new DocumentFactoryBuilder("asset")
.addField(title, color)
.build();
DocumentFactory marker = new DocumentFactoryBuilder("marker")
.addField(title, color)
.build();
Document a1 = asset.createDoc("A1")
.setValue(title, "A1 1")
.setValue(color, "blue");
Document a2 = asset.createDoc("A2")
.setValue(title, "A2")
.setValue(color, "red")
.addChild(marker.createDoc("M1")
.setValue(title, "M1")
.setValue(color, "blue")
);
Document a3 = asset.createDoc("A3").setValue(title,"A3").setValue(color, "green")
.addChild(marker.createDoc("M2")
.setValue(title, "M2")
.setValue(color, "red"));
Document a4 = asset.createDoc("A4").setValue(title, "A4").setValue(color, "blue")
.addChild(marker.createDoc("M3")
.setValue(title, "M3")
.setValue(color, "blue"));
server.index(a1);
server.index(a2);
server.index(a3);
server.index(a4);
server.commit();
server.execute(Search.fulltext("some"), asset); //search in all assets
server.execute(Search.fulltext("some"), marker); //search in all markers
SearchResult orChildrenFilteredSearch = server.execute(Search.fulltext().filter(Filter.eq(color, "blue")).orChildrenSearch(marker), asset);//search in all markers
SearchResult andChildrenFilteredSearch = server.execute(Search.fulltext().filter(Filter.eq(color, "blue")).andChildrenSearch(marker), asset);//search in all markers
Assert.assertTrue(orChildrenFilteredSearch.getNumOfResults() == 3);
Assert.assertTrue(andChildrenFilteredSearch.getNumOfResults() == 1);
SearchResult orChildrenCustomSearch = server.execute(Search.fulltext("1").filter(Filter.eq(color, "blue")).orChildrenSearch(Search.fulltext().filter(Filter.eq(color, "red")), marker), asset);//search in all markers
//TODO: confirm with Thomas
Assert.assertEquals(3, orChildrenCustomSearch.getNumOfResults());
//server.execute(Search.fulltext("some").facet(children(title)),asset); //get title facts for children
//server.executdeepSearchResulte(Search.fulltext("some").facet(parent(title)),marker); //get title facets for parents
//server.execute(Search.fulltext("some").includeChildren(true),marker); //search everywhere and include matching children
}
@Test
@RunWithBackend({Solr, Elastic})
public void testTermFacetAccess() {
SearchServer server = testBackend.getSearchServer();
MultiValueFieldDescriptor<String> term = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildMultivaluedTextField("term");
DocumentFactory factory = new DocumentFactoryBuilder("doc").addField(term).build();
server.index(factory.createDoc("1").setValue(term, "t1").addValue(term, "t2"));
server.index(factory.createDoc("2").setValue(term, "t2"));
server.commit();
SearchResult result = server.execute(Search.fulltext().facet(term), factory);
assertEquals(2, result.getFacetResults().getTermFacet(term).getValues().size());
assertEquals(2, result.getFacetResults().getTermFacet("term", String.class).getValues().size());
assertEquals(2, result.getFacetResults().getTermFacets().get(term).getValues().size());
}
//MBDN-352
@Test
@RunWithBackend({Solr, Elastic})
public void testIndexMultipleDocuments () {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime yesterday = ZonedDateTime.now(ZoneId.of("UTC")).minus(1, ChronoUnit.DAYS);
ZonedDateTime oneHourAgo = ZonedDateTime.now(ZoneId.of("UTC")).minus(1, ChronoUnit.HOURS);
ZonedDateTime halfDayAgo = ZonedDateTime.now(ZoneId.of("UTC")).minus(1, ChronoUnit.HALF_DAYS);
FieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("title");
SingleValueFieldDescriptor.DateFieldDescriptor<ZonedDateTime> created = new FieldDescriptorBuilder()
.setFacet(true)
.buildDateField("created");
SingleValueFieldDescriptor.UtilDateFieldDescriptor<Date> modified = new FieldDescriptorBuilder()
.setFacet(true)
.buildUtilDateField("modified");
NumericFieldDescriptor<Long> category = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedNumericField("category", Long.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(title)
.addField(created)
.addField(category)
.addField(modified)
.build();
Document d1 = assets.createDoc("1")
.setValue(title, "Hello World")
.setValue(created, yesterday)
.setValue(modified, new Date())
.setValues(category, Arrays.asList(1L, 2L));
Document d2 = assets.createDoc("2")
.setValue(title, "Hello Friends")
.setValue(created, now)
.setValue(modified, new Date())
.addValue(category, 4L);
Document d3 = assets.createDoc("3")
.setValue(title, "Hello You")
.setValue(created, halfDayAgo)
.setValue(modified, new Date())
.setValues(category, Arrays.asList(4L, 5L));
Document d4 = assets.createDoc("4")
.setValue(title, "Hello them")
.setValue(created, oneHourAgo)
.setValue(modified, new Date())
.addValue(category, 7L);
SearchServer server = testBackend.getSearchServer();
List<Document> docList = new ArrayList<>();
docList.add(d3);
docList.add(d4);
server.index(d1,d2);
server.index(docList);
server.commit();
FulltextSearch search = Search.fulltext("hello")
.page(1, 25)
.sort(desc(created));
SearchResult result = server.execute(search,assets);
assertEquals(4, result.getNumOfResults());
assertEquals(4, result.getResults().size());
assertEquals("2", result.getResults().get(0).getId());
assertEquals("asset", result.getResults().get(0).getType());
assertEquals("4", result.getResults().get(1).getId());
assertEquals("asset", result.getResults().get(1).getType());
assertTrue(now.equals(result.getResults().get(0).getValue(created)));
assertTrue(now.equals(result.getResults().get(0).getValue("created")));
}
@Test
@RunWithBackend({Solr, Elastic})
public void testSearchGetById() {
SearchServer server = testBackend.getSearchServer();
MultiValueFieldDescriptor<String> term = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildMultivaluedTextField("term");
DocumentFactory factory = new DocumentFactoryBuilder("testDocFactory").addField(term).build();
server.index(factory.createDoc("1").setValue(term,"t1").addValue(term,"t2"));
server.index(factory.createDoc("2").setValue(term, "t2"));
server.index(factory.createDoc("21").setValue(term,"t2"));
server.index(factory.createDoc("42").setValue(term, "t42"));
server.commit();
GetResult result = server.execute(Search.getById("2"), factory);
assertEquals(1, result.getResults().size());
assertEquals("2", result.getResults().get(0).getId());
GetResult multiResult = server.execute(Search.getById("1", "2", "42"), factory);
assertEquals(3, multiResult.getResults().size());
assertEquals("1", multiResult.getResults().get(0).getId());
GetResult empty = server.execute(Search.getById("nonExistentId"), factory);
assertEquals(0, empty.getResults().size());
}
/*
@Test
public void testZKConnection() {
SearchConfiguration.set(SearchConfiguration.SERVER_SOLR_PROVIDER, "RemoteSolrServerProvider");
SearchConfiguration.set(SearchConfiguration.SERVER_SOLR_CLOUD, true);
SearchConfiguration.set(SearchConfiguration.SERVER_SOLR_HOST, "zkServerA:2181,zkServerB:2181,zkServerC:2181");
SearchConfiguration.set(SearchConfiguration.SERVER_SOLR_COLLECTION, "my_collection");
SearchServer server = SearchServer.getInstance();
DocumentFactory assets = new DocumentFactoryBuilder("asset").build();
SearchResult result = server.execute(Search.fulltext(), assets);
}
*/
//MBDN-431
@Test
@RunWithBackend({Solr, Elastic})
public void testDeleteByQuery() {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime yesterday = ZonedDateTime.now(ZoneId.of("UTC")).minus(1, ChronoUnit.DAYS);
ZonedDateTime oneHourAgo = ZonedDateTime.now(ZoneId.of("UTC")).minus(1, ChronoUnit.HOURS);
FieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("title");
SingleValueFieldDescriptor.DateFieldDescriptor<ZonedDateTime> created = new FieldDescriptorBuilder()
.setFacet(true)
.buildDateField("created");
SingleValueFieldDescriptor.UtilDateFieldDescriptor<Date> modified = new FieldDescriptorBuilder()
.setFacet(true)
.buildUtilDateField("modified");
NumericFieldDescriptor<Long> category = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedNumericField("category", Long.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(title)
.addField(created)
.addField(category)
.addField(modified)
.build();
Document d1 = assets.createDoc("1")
.setValue(title, "Hello World")
.setValue(created, yesterday)
.setValue(modified, new Date())
.setValues(category, Arrays.asList(1L, 2L));
Document d2 = assets.createDoc("2")
.setValue(title, "Hello Friends")
.setValue(created, now)
.setValue(modified, new Date())
.addValue(category, 4L);
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.commit();
FulltextSearch searchAll = Search.fulltext();
final SearchResult searchResult = server.execute(searchAll, assets);
assertEquals("No of results", 2, searchResult.getNumOfResults());
final Document result = searchResult.getResults().get(0);
assertThat("Doc-Title", result.getValue(title), Matchers.equalTo("Hello World"));
Delete deleteBeforeOneHourAgo = new Delete(Filter.before("created",oneHourAgo));
server.execute(deleteBeforeOneHourAgo, assets);
server.commit();
final SearchResult searchAfterDeleteResult = server.execute(searchAll, assets);
assertEquals("No of results", 1, searchAfterDeleteResult.getNumOfResults());
final Document nonDeletedResult = searchAfterDeleteResult.getResults().get(0);
assertThat("Doc-Title", nonDeletedResult.getValue(title), Matchers.equalTo("Hello Friends"));
Delete deleteByTitle = new Delete(Filter.eq(title, "Hello Friends"));
server.execute(deleteByTitle, assets);
server.commit();
final SearchResult searchAfterTitleDeletionResult = server.execute(searchAll, assets);
assertEquals("No of results", 0, searchAfterTitleDeletionResult.getNumOfResults());
}
@Test
@RunWithBackend({Solr, Elastic})
public void testSolrUtilDateMultivalueFields() {
MultiValueFieldDescriptor.UtilDateFieldDescriptor<Date> date = new FieldDescriptorBuilder()
.buildMultivaluedUtilDateField("date");
DocumentFactory factory = new DocumentFactoryBuilder("doc")
.addField(date)
.build();
Document document = factory.createDoc("1").setValue(date, new Date());
SearchServer server = testBackend.getSearchServer();
server.index(document);
server.commit();
}
//MBDN-432
@Test
@RunWithBackend({Solr, Elastic})
public void testClearIndex() {
//Storing as text_en solr type
SingleValueFieldDescriptor.TextFieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setStored(true)
.buildTextField("title");
FieldDescriptor<String> entityID = new FieldDescriptorBuilder()
.buildTextField("entityID");
SingleValueFieldDescriptor<String> description = new FieldDescriptorBuilder()
.setLanguage(Language.English)
.buildTextField("description");
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(title)
.addField(description)
.addField(entityID)
.build();
Document d1 = assets.createDoc("1")
.setValue(title, "Hello World")
.setValue(entityID, "123")
.setValue(description, "This value is not stored");
Document d2 = assets.createDoc("2")
.setValue(entityID, "456")
.setValue(title, "Hello Friends")
.setValue(description, "This value is also not stored");
SearchServer server = testBackend.getSearchServer();
server.clearIndex();
server.index(d1);
server.index(d2);
server.commit();
FulltextSearch searchAll = Search.fulltext();
final SearchResult searchResult = server.execute(searchAll, assets);
assertEquals("No of results", 2, searchResult.getNumOfResults());
final Document result = searchResult.getResults().get(0);
assertThat("Doc-Title", result.getValue(title), Matchers.equalTo("Hello World"));
server.clearIndex();
server.commit();
final SearchResult searchResultClear = server.execute(searchAll, assets);
assertEquals("No of results", 0, searchResultClear.getNumOfResults());
}
//MBDN-441
@Test
@RunWithBackend({Solr, Elastic})
public void timeZoneSearchTest() {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime yesterday = ZonedDateTime.now(ZoneId.of("UTC")).minus(1, ChronoUnit.DAYS);
ZonedDateTime oneHourAgo = ZonedDateTime.now(ZoneId.systemDefault()).minus(1, ChronoUnit.HOURS);
FieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.buildTextField("title");
SingleValueFieldDescriptor.DateFieldDescriptor<ZonedDateTime> created = new FieldDescriptorBuilder()
.setFacet(true)
.buildDateField("created");
SingleValueFieldDescriptor.UtilDateFieldDescriptor<Date> modified = new FieldDescriptorBuilder()
.setFacet(true)
.buildUtilDateField("modified");
NumericFieldDescriptor<Long> category = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedNumericField("category", Long.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(title)
.addField(created)
.addField(category)
.addField(modified)
.build();
Document d1 = assets.createDoc("1")
.setValue(title, "Hello World")
.setValue(created, yesterday)
.setValue(modified, new Date())
.setValues(category, Arrays.asList(1L, 2L));
Document d2 = assets.createDoc("2")
.setValue(title, "Hello Friends")
.setValue(created, now)
.setValue(modified, new Date())
.addValue(category, 4L);
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.commit();
FulltextSearch searchAll = Search.fulltext().filter(before("created", new DateMathExpression().sub(1, HOUR))).timeZone("America/Havana");
final SearchResult searchResult = server.execute(searchAll, assets);
assertEquals("No of results", 1, searchResult.getNumOfResults());
final Document result = searchResult.getResults().get(0);
assertThat("Doc-Title", result.getValue(title), Matchers.equalTo("Hello World"));
}
//MBDN-450
@Test
@RunWithBackend({Solr, Elastic})
public void testDateMathIntervals() {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime yesterday = ZonedDateTime.now(ZoneId.of("UTC")).minus(1, ChronoUnit.DAYS);
FieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("title");
SingleValueFieldDescriptor.DateFieldDescriptor<ZonedDateTime> created = new FieldDescriptorBuilder()
.setFacet(true)
.setStored(true)
.buildDateField("created");
SingleValueFieldDescriptor.UtilDateFieldDescriptor<Date> modified = new FieldDescriptorBuilder()
.setFacet(true)
.buildUtilDateField("modified");
NumericFieldDescriptor<Long> category = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedNumericField("category", Long.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(title)
.addField(created)
.addField(category)
.addField(modified)
.build();
Document d1 = assets.createDoc("1")
.setValue(title, "Hello World")
.setValue(created, yesterday)
.setValue(modified, new Date())
.setValues(category, Arrays.asList(1L, 2L));
Document d2 = assets.createDoc("2")
.setValue(title, "Hello Friends")
.setValue(created, now)
.setValue(modified, new Date())
.addValue(category, 4L);
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.commit();
Interval.DateMathInterval i1 = Interval.dateInterval("past_24_hours", new DateMathExpression().sub(1, DAY), new DateMathExpression());
Interval.DateMathInterval i2 = Interval.dateInterval("past_week", new DateMathExpression().sub(7, DAY), new DateMathExpression());
FulltextSearch search = Search.fulltext("hello")
.filter(created.before(new DateMathExpression()))
.facet(query("anotherQuery", and(category.between(7, 10), created.after(new DateMathExpression().sub(1, DAY)))))
.facet(range("dates", created, new DateMathExpression().sub(1, DAY), new DateMathExpression(), Duration.ofHours(1)))
.facet(range("mod a", modified, new Date(), new Date(), 1L, TimeUnit.HOURS, "cats"))
.facet(interval("quality", category, Interval.numericInterval("low", 0L, 2L), Interval.numericInterval("high", 3L, 4L)))
.facet(interval("time", created, i1, i2))
.facet(interval("time2", modified,
Interval.dateInterval("early", new Date(0), new Date(10000)),
Interval.dateInterval("late", new Date(10000), new Date(20000))))
.facet(interval("time3", modified,
Interval.dateInterval("early", new DateMathExpression(), new DateMathExpression().add(10000, MILLISECONDS)),
Interval.dateInterval("late", new DateMathExpression().add(10000, MILLISECONDS), new DateMathExpression().add(20000, MILLISECONDS))))
.page(1, 25)
.sort(desc(created));
PageResult result = (PageResult)server.execute(search,assets);
assertEquals(2, result.getNumOfResults());
assertEquals(2, result.getResults().size());
assertEquals("2", result.getResults().get(0).getId());
assertEquals("asset", result.getResults().get(0).getType());
assertEquals("2", result.getResults().get(0).getId());
assertEquals("asset", result.getResults().get(0).getType());
assertTrue(now.equals(result.getResults().get(0).getValue(created)));
assertTrue(now.equals(result.getResults().get(0).getValue("created")));
assertEquals(2, result.getFacetResults().getIntervalFacet("quality").getValues().size());
assertEquals(2, result.getFacetResults().getIntervalFacet("time").getValues().size());
System.out.println(result);
PageResult next = (PageResult)result.nextPage();
SearchResult prev = next.previousPage();
TermFacetResult<Long> facet = result.getFacetResults().getTermFacet(category);
RangeFacetResult<ZonedDateTime> dates = result.getFacetResults().getRangeFacet("dates", ZonedDateTime.class);
ZonedDateTime rangeDate = dates.getValues().get(0).getValue();
}
//MBDN-451
@Test
@RunWithBackend({Solr, Elastic})
public void wildcardIntervalLimitTest() {
SingleValueFieldDescriptor<Float> numberField = new FieldDescriptorBuilder()
.setFacet(true)
.buildNumericField("number", Float.class);
FieldDescriptor<String> entityID = new FieldDescriptorBuilder()
.buildTextField("entityID");
SingleValueFieldDescriptor<Date> dateField = new FieldDescriptorBuilder()
.setFacet(true)
.buildUtilDateField("date");
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(numberField)
.addField(dateField)
.addField(entityID)
.build();
Document d1 = assets.createDoc("1")
.setValue(numberField, 24f)
.setValue(entityID, "123")
.setValue(dateField, new Date());
Document d2 = assets.createDoc("2")
.setValue(numberField, 2f)
.setValue(entityID, "123")
.setValue(dateField, new Date());
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.commit();
FulltextSearch searchAll = Search.fulltext().facet(interval("numbers", numberField,
Interval.numericInterval("low", null, 20f),
Interval.numericInterval("high", 21f, null)))
.facet(interval("dates", dateField,
Interval.dateInterval("before", null, new Date()),
Interval.dateInterval("after", new Date(), null)));
final SearchResult searchResult = server.execute(searchAll, assets);
assertEquals("No of interval facets", 2, searchResult.getFacetResults().getIntervalFacet("numbers").getValues().size());
assertEquals("No of interval facets", 2, searchResult.getFacetResults().getIntervalFacet("dates").getValues().size());
assertEquals("No of interval facets", 2, searchResult.getFacetResults().getIntervalFacet("dates").getValues().get(0).getCount());
}
//MBDN-454
@Test
@RunWithBackend({Solr, Elastic})
public void binaryFieldTest() {
FieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("title");
SingleValueFieldDescriptor.DateFieldDescriptor<ZonedDateTime> created = new FieldDescriptorBuilder()
.setFacet(true)
.buildDateField("created");
SingleValueFieldDescriptor.UtilDateFieldDescriptor<Date> modified = new FieldDescriptorBuilder()
.setFacet(true)
.buildUtilDateField("modified");
NumericFieldDescriptor<Long> category = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedNumericField("category", Long.class);
SingleValueFieldDescriptor.BinaryFieldDescriptor<ByteBuffer> byteField = new FieldDescriptorBuilder()
.setStored(true)
.buildBinaryField("blob");
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(title)
.addField(created)
.addField(category)
.addField(modified)
.addField(byteField)
.build();
Document d1 = assets.createDoc("1")
.setValue(title, "Hello World")
.setValue(modified, new Date())
.setValue(byteField,ByteBuffer.wrap("ooalalalalala".getBytes()))
.setValues(category, Arrays.asList(1L, 2L));
Document d2 = assets.createDoc("2")
.setValue(title, "Hello Friends")
.setValue(modified, new Date())
.addValue(category, 4L)
.setValue(byteField, ByteBuffer.wrap("oolelelelele".getBytes()));
SearchServer server = testBackend.getSearchServer();
server.clearIndex();
server.index(d1);
server.index(d2);
server.commit();
FulltextSearch search = Search.fulltext();
SearchResult result = server.execute(search, assets);
assertEquals(2, result.getNumOfResults());
assertEquals(2, result.getResults().size());
assertTrue(ByteBuffer.class.isAssignableFrom(result.getResults().get(0).getValue("blob").getClass()));
assertEquals("ooalalalalala",new String(((ByteBuffer)result.getResults().get(0).getValue("blob")).array()));
server.execute(search, assets);
}
//MBDN-455
@Test
@RunWithBackend({Elastic,Solr})
public void complexFieldTest() {
SingleValuedComplexField.NumericComplexField<Taxonomy,Integer,String> numericComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,Integer,String>()
.setFacet(true, tx -> Arrays.asList(tx.getId()))
.setFullText(true, tx -> Arrays.asList(tx.getTerm()))
.setSuggest(true, tx -> Arrays.asList(tx.getLabel()))
.buildNumericComplexField("numberFacetTaxonomy", Taxonomy.class, Integer.class, String.class);
SingleValuedComplexField.DateComplexField<Taxonomy,ZonedDateTime,String> dateComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,ZonedDateTime,String>()
.setFacet(true, tx -> Arrays.asList(tx.getDate()))
.setFullText(true, tx -> Arrays.asList(tx.getTerm()))
.setSuggest(true, tx -> Arrays.asList(tx.getLabel()))
.buildDateComplexField("dateFacetTaxonomy", Taxonomy.class, ZonedDateTime.class, String.class);
SingleValuedComplexField.TextComplexField<Taxonomy,String,String> textComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,String,String>()
.setFacet(true, tx -> Arrays.asList(tx.getLabel()))
.setSuggest(true, tx -> Arrays.asList(tx.getLabel()))
.setStored(true, tx -> tx.getTerm())
.buildTextComplexField("textFacetTaxonomy", Taxonomy.class, String.class, String.class);
SingleValuedComplexField.DateComplexField<Taxonomy,ZonedDateTime,ZonedDateTime> dateStoredComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,ZonedDateTime,ZonedDateTime>()
.setStored(true, tx -> tx.getDate())
.buildSortableDateComplexField("dateStoredFacetTaxonomy", Taxonomy.class, ZonedDateTime.class, ZonedDateTime.class, cdf -> cdf.getDate());
MultiValuedComplexField.TextComplexField<Taxonomy,String,String> multiComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,String,String>()
.setFacet(true, tx -> Arrays.asList(tx.getLabel()))
.setSuggest(true, tx -> Arrays.asList(tx.getLabel()))
.setStored(true, tx -> tx.getTerm())
.buildMultivaluedTextComplexField("multiTextTaxonomy", Taxonomy.class, String.class, String.class);
FieldDescriptor<String> entityID = new FieldDescriptorBuilder()
.buildTextField("entityID");
SingleValueFieldDescriptor<Date> dateField = new FieldDescriptorBuilder()
.buildUtilDateField("date");
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(numericComplexField)
.addField(dateComplexField)
.addField(textComplexField)
.addField(dateField)
.addField(dateStoredComplexField)
.addField(entityID)
.addField(multiComplexField)
.build();
Document d1 = assets.createDoc("1")
.setValue(numericComplexField, new Taxonomy("uno", 1, "Uno label", ZonedDateTime.now()))
.setValue(dateComplexField, new Taxonomy("uno", 1, "Uno label",ZonedDateTime.now()))
.setValue(textComplexField, new Taxonomy("uno", 1, "Label", ZonedDateTime.now()))
.setValue(entityID, "123")
.setValue(dateStoredComplexField, new Taxonomy("uno", 1, "Label",ZonedDateTime.now()))
.setValues(multiComplexField, new Taxonomy("uno", 1, "Label", ZonedDateTime.now()), new Taxonomy("dos", 2, "Label dos", ZonedDateTime.now()))
.setValue(dateField, new Date());
Document d2 = assets.createDoc("2")
.setValue(numericComplexField, new Taxonomy("dos", 2, "dos label", ZonedDateTime.now()))
.setValue(dateComplexField,new Taxonomy("dos", 2, "dos label",ZonedDateTime.now()))
.setValue(textComplexField,new Taxonomy("uno", 2, "Label",ZonedDateTime.now()))
.setValue(entityID, "456")
.setValue(dateStoredComplexField,new Taxonomy("uno", 1, "Label",ZonedDateTime.now().plusMonths(1)))
.setValues(multiComplexField, new Taxonomy("uno", 1, "Label", ZonedDateTime.now()), new Taxonomy("dos", 1, "Label", ZonedDateTime.now()))
.setValue(dateField, new Date());
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.commit();
FulltextSearch searchAll = Search.fulltext().filter(
and(textComplexField.isNotEmpty(Scope.Facet),
or(Filter.eq(numericComplexField, 1), Filter.eq(numericComplexField, 2)),
numericComplexField.between(0, 5),
dateComplexField.between(ZonedDateTime.now().minusDays(3), ZonedDateTime.now().plusDays(3)),
textComplexField.equals("Label")))
.facet(interval("facetNumber", numericComplexField, Interval.numericInterval("[1-4]", 0, 5), Interval.numericInterval("[6-9]", 5, 10)))
.facet(interval("facetDateInterval", dateComplexField,
Interval.dateInterval("3_days_ago_till_now-1_hour]", ZonedDateTime.now().minusDays(3), ZonedDateTime.now().minusHours(1)),
Interval.dateInterval("[now-1_hour_till_the_future]", ZonedDateTime.now().minusHours(1), null)))
.facet(range("facetRange", numericComplexField, 0, 10, 5))
.facet(range("facetDateRange", dateComplexField, ZonedDateTime.now().minusDays(3), ZonedDateTime.now().plusDays(3), Duration.ofDays(1)))
.facet(((Facet.StatsNumericFacet)stats("facetStats", numericComplexField)).min().max().sum())
.facet(stats("facetDateStats", dateComplexField))
//.facet(stats("facetTextStats", textComplexField))
.facet(pivot("facetNumericPivot", numericComplexField, entityID, dateComplexField, textComplexField))
.facet(numericComplexField, entityID, dateComplexField, textComplexField)
.sort(desc(dateStoredComplexField));
final SearchResult searchResult = server.execute(searchAll, assets);
assertEquals("Stored text exists", "uno", searchResult.getResults().get(0).getValue(textComplexField));
assertThat("Multivalued text exists", (List<String>) searchResult.getResults().get(0).getValue(multiComplexField), containsInAnyOrder("uno", "dos"));
assertEquals("No of interval", 2, searchResult.getFacetResults().getIntervalFacet("facetNumber").getValues().size());
assertEquals("No of doc in interval", 2, searchResult.getFacetResults().getIntervalFacet("facetNumber").getValues().get(0).getCount());
assertEquals("No of StatsFacets", 2, searchResult.getFacetResults().getStatsFacets().size());
assertEquals("Stats Min: ", (Integer) 1, searchResult.getFacetResults().getStatsFacet("facetStats", Integer.class).getMin());
assertEquals("Stats Max: ", (Integer) 2, searchResult.getFacetResults().getStatsFacet("facetStats", Integer.class).getMax());
assertEquals("Stats Sum: ", (Double) 3.0, searchResult.getFacetResults().getStatsFacet("facetStats", Integer.class).getSum());
final SuggestionResult suggestSearch = server.execute(Search.suggest("la").fields(numericComplexField, textComplexField),assets);
assertEquals(3, suggestSearch.size());
assertEquals("Label", suggestSearch.get(textComplexField).getValues().get(0).getValue());
assertEquals("Uno label", suggestSearch.get(numericComplexField).getValues().get(0).getValue());
}
//MBDN-452
@Test
@RunWithBackend({Solr, Elastic})
public void supportUnderscoredFieldNamesTest() {
SingleValueFieldDescriptor<Float> numberField = new FieldDescriptorBuilder()
.buildNumericField("number_one", Float.class);
FieldDescriptor<String> entityID = new FieldDescriptorBuilder()
.setLanguage(Language.English)
.buildTextField("entity_ID");
SingleValueFieldDescriptor<Date> dateField = new FieldDescriptorBuilder()
.buildUtilDateField("date_field");
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(numberField)
.addField(dateField)
.addField(entityID)
.build();
Document d1 = assets.createDoc("1")
.setValue(numberField, 24f)
.setValue(entityID, "123")
.setValue(dateField, new Date());
Document d2 = assets.createDoc("2")
.setValue(numberField, 2f)
.setValue(entityID, "123")
.setValue(dateField, new Date());
SearchServer server = testBackend.getSearchServer();
server.clearIndex();
server.index(d1);
server.index(d2);
server.commit();
FulltextSearch searchAll = Search.fulltext();
final SearchResult searchResult = server.execute(searchAll, assets);
assertEquals("Number of results", 2, searchResult.getNumOfResults());
assertEquals("Number_one field", 24f, searchResult.getResults().get(0).getValue("number_one"));
}
@Test
@RunWithBackend({Solr, Elastic})
public void testLocationDescriptor() {
final LatLng gijon = new LatLng(43.545231, -5.661920);
final LatLng oviedo = new LatLng(28.669996, -81.208122);
final LatLng salzburg = new LatLng(47.809490, 13.055010);
final LatLng wuhan = new LatLng(30.592850, 114.305542);
SingleValueFieldDescriptor.LocationFieldDescriptor<LatLng> locationSingle = new FieldDescriptorBuilder()
.setFacet(true)
.buildLocationField("locationSingle");
MultiValueFieldDescriptor.LocationFieldDescriptor<LatLng> locationMulti = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedLocationField("locationMulti");
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(locationSingle)
.addField(locationMulti)
.build();
Document doc1 = assets.createDoc("1")
.setValue(locationSingle, wuhan)
.setValues(locationMulti, salzburg);
Document doc2 = assets.createDoc("2")
.setValue(locationSingle, salzburg)
.setValues(locationMulti, gijon);
Document doc3 = assets.createDoc("3")
.setValues(locationMulti, oviedo, gijon);
SearchServer server = testBackend.getSearchServer();
server.index(doc1);
server.index(doc2);
server.index(doc3);
server.commit();
//test bbox filter: within Austria
FulltextSearch searchAll = Search.fulltext().filter(locationSingle.withinBBox(new LatLng(49.003646, 9.446277), new LatLng(46.379149, 17.174708)));
SearchResult searchResult = server.execute(searchAll, assets).print();
assertEquals("LatLng filter 'within' does not filter properly single value fields", 1, searchResult.getNumOfResults());
//test bbox filter multivalue: within Asturias
searchAll = Search.fulltext().filter(locationMulti.withinBBox(new LatLng(43.646013,-7.173549), new LatLng(42.902125,-4.513121)));
searchResult = server.execute(searchAll, assets).print();
assertEquals("LatLng filter 'within' does not filter properly mutivalued fields", 2, searchResult.getNumOfResults());
//test circle filter: center Beijing with a radius of 230km
final LatLng beijing = new LatLng(29.3464, 116.199);
searchAll = Search.fulltext().filter(locationSingle.withinCircle(beijing, 230));
searchResult = server.execute(searchAll, assets).print();
assertEquals("LatLng filter 'withinCircle' does not filter properly singlevalued fields", 1, searchResult.getNumOfResults());
//test circle filter: center Madrid with a radius of 384km
final LatLng madrid = new LatLng(40.4165, -3.70256);
searchAll = Search.fulltext().filter(locationMulti.withinCircle(madrid, 384));
searchResult = server.execute(searchAll, assets).print();
assertEquals("LatLng filter 'withinFilter' does not filter properly multivalued fields", 2, searchResult.getNumOfResults());
//test retrieving geodist
//TODO this feature is a little hacky, but should be easy to clean uo
searchAll = Search.fulltext().geoDistance(locationSingle, beijing);
searchResult = server.execute(searchAll, assets).print();
assertEquals("Distance is not appended to results", 229, searchResult.getResults().get(0).getDistance(),0.1);
//test sorting
//TODO does not yet work (parsing error)
searchAll = Search.fulltext().sort(distance()).geoDistance(locationSingle, madrid);;
searchResult = server.execute(searchAll, assets).print();
assertTrue("Distance sorting is not correct", searchResult.getResults().get(0).getDistance() < searchResult.getResults().get(1).getDistance());
}
//MBDN-458
@Test
@RunWithBackend({Solr, Elastic})
public void testContextSearch() {
final SingleValueFieldDescriptor<Float> numberField = new FieldDescriptorBuilder()
.setFacet(true)
.buildNumericField("numberone", Float.class);
final FieldDescriptor<String> entityID = new FieldDescriptorBuilder()
.setFacet(true)
.setLanguage(Language.English)
.buildTextField("entityID");
final SingleValueFieldDescriptor<Date> dateField = new FieldDescriptorBuilder()
.buildUtilDateField("datefield");
final MultiValueFieldDescriptor.TextFieldDescriptor<String> multiTextField = new FieldDescriptorBuilder()
.setFacet(true)
.setSuggest(true)
.buildMultivaluedTextField("textMulti");
final DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(numberField)
.addField(dateField)
.addField(entityID)
.addField(multiTextField)
.setUpdatable(true)
.build();
final Document d1 = assets.createDoc("1")
.setValue(numberField, 0f)
.setContextualizedValue(numberField, "numberContext", 24f)
.setContextualizedValue(numberField, "singleContext", 3f)
.setValue(entityID, "123")
.setValue(dateField, new Date());
final Document d2 = assets.createDoc("2")
.setValue(numberField, 2f)
.setValue(entityID, "123")
.setContextualizedValues(multiTextField, "multicontext", "text1", "text2")
.setValue(dateField, new Date());
final SearchServer server = testBackend.getSearchServer();
server.clearIndex();
server.index(d1);
server.index(d2);
server.commit();
final SuggestionResult suggestion = server.execute(Search.suggest("text1").context("multicontext").addField(multiTextField), assets);
assertEquals("One contextualize suggestion expected",1,suggestion.size());
FulltextSearch searchAll = Search.fulltext();
SearchResult searchResult = server.execute(searchAll, assets);
assertEquals("Number of results", 2, searchResult.getNumOfResults());
assertEquals("Number_one field", 0f, searchResult.getResults().get(0).getValue("numberone"));
searchAll = Search.fulltext().context("numberContext").filter(and(eq(entityID, "123"), eq(numberField,24f))).facet(entityID);
searchResult = server.execute(searchAll, assets);
assertEquals("Number of results", 1, searchResult.getNumOfResults());
assertEquals("Number_one field", 24f, searchResult.getResults().get(0).getContextualizedValue("numberone", "numberContext"));
assertEquals("Number_one field", null, searchResult.getResults().get(0).getContextualizedValue("numberone", "singleContext"));
searchAll = Search.fulltext().context("singleContext");
searchResult = server.execute(searchAll, assets);
assertEquals("Number of results", 2, searchResult.getNumOfResults());
assertEquals("Number_one field", 3f, searchResult.getResults().get(0).getContextualizedValue("numberone", "singleContext"));
assertEquals("Number_one field", null, searchResult.getResults().get(0).getContextualizedValue("numberone", "numberContext"));
searchAll = Search.fulltext().context("multicontext");
searchResult = server.execute(searchAll, assets);
assertEquals("Number of results", 2, searchResult.getNumOfResults());
assertThat("textMulti multi text field", (List<String>) searchResult.getResults().get(1).getContextualizedValue("textMulti", "multicontext"), containsInAnyOrder("text1", "text2"));
Delete deleteInContext = new Delete(multiTextField.isNotEmpty()).context("multicontext");
server.execute(deleteInContext, assets);
server.commit();
searchResult = server.execute(searchAll, assets);
assertEquals("Number of results", 1, searchResult.getResults().size());
server.execute(Search.update("1").set(numberField, 1f), assets);
server.commit();
searchResult = server.execute(searchAll, assets);
assertEquals("Number_one field", 1f, searchResult.getResults().get(0).getValue("numberone"));
server.execute(Search.update("1").set("singleContext", numberField, 4f), assets);
server.commit();
searchResult = server.execute(searchAll.context("singleContext"), assets);
assertEquals("Number_one field", 4f, searchResult.getResults().get(0).getContextualizedValue("numberone", "singleContext"));
server.execute(Search.update("1").remove("singleContext", numberField, null), assets);
server.commit();
searchResult = server.execute(searchAll.context("singleContext"), assets);
assertEquals("Number_one field in single context has been removed", null, searchResult.getResults().get(0).getContextualizedValue("numberone", "singleContext"));
}
//MBDN-459
@Test
@RunWithBackend({Solr, Elastic})
public void isNotEmptyFilterTest() {
final SingleValueFieldDescriptor.TextFieldDescriptor<String> textSingle = new FieldDescriptorBuilder()
.setFacet(true)
.buildTextField("textSingle");
final SingleValueFieldDescriptor.NumericFieldDescriptor<Integer> numberSingle = new FieldDescriptorBuilder()
.setFacet(true)
.buildNumericField("intSingle", Integer.class);
final MultiValueFieldDescriptor.TextFieldDescriptor<String> textMulti = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedTextField("textMulti");
final DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(textSingle)
.addField(textMulti)
.addField(numberSingle)
.build();
final Document doc1 = assets.createDoc("1")
.setValue(textSingle, "text 1");
final Document doc2 = assets.createDoc("2")
.setValues(textMulti, "text 2.1", "text 2.2");
final Document doc3 = assets.createDoc("3")
.setValue(textSingle, "")
.addValue(textMulti, null)
.setValue(numberSingle, 9);
final SearchServer server = testBackend.getSearchServer();
server.clearIndex();
server.index(doc1);
server.index(doc2);
server.index(doc3);
server.commit();
//test empty filter in single valued field
FulltextSearch searchAll = Search.fulltext().filter(textSingle.isNotEmpty());
SearchResult searchResult = server.execute(searchAll, assets).print();
assertEquals("Just documents with single text fields are returned", 1, searchResult.getNumOfResults());
//test empty filter in multivalue field
searchAll = Search.fulltext().filter(textMulti.isNotEmpty());
searchResult = server.execute(searchAll, assets).print();
assertEquals("Just documents with multi valued text fields are returned", 1, searchResult.getNumOfResults());
//test empty filter in single valued field
searchAll = Search.fulltext().filter(textSingle.isEmpty());
searchResult = server.execute(searchAll, assets).print();
assertEquals("Just documents with not or empty single text fields are returned", 2, searchResult.getNumOfResults());
//test empty filter in single valued field
searchAll = Search.fulltext().filter(not(textMulti.isNotEmpty()));
searchResult = server.execute(searchAll, assets).print();
assertEquals("Just documents with not or empty multi text fields are returned", 2, searchResult.getNumOfResults());
//test empty filter in single valued numberfield
searchAll = Search.fulltext().filter(numberSingle.isNotEmpty());
searchResult = server.execute(searchAll, assets).print();
assertEquals("Just documents with not or empty multi number fields are returned", 1, searchResult.getNumOfResults());
//test empty filter in single valued numberfield
searchAll = Search.fulltext().filter(Filter.or(textMulti.isNotEmpty(), textSingle.isEmpty()));
searchResult = server.execute(searchAll, assets).print();
assertEquals("Just documents with not or empty multi text or empty single text fields are returned", 2, searchResult.getNumOfResults());
}
//MBDN-430
@Test
@RunWithBackend({Elastic, Solr})
public void testSortableMultiValuedFields() {
final TextFieldDescriptor textMulti = new FieldDescriptorBuilder()
.buildMultivaluedTextField("textMulti");
final NumericFieldDescriptor<Integer> numMulti = new FieldDescriptorBuilder()
.buildMultivaluedNumericField("numMulti", Integer.class);
final Function<Collection<ZonedDateTime>, ZonedDateTime> dateSortFunction = txs -> txs.stream().max(Comparator.<ZonedDateTime>naturalOrder()).get();
final DateFieldDescriptor dateMulti = new FieldDescriptorBuilder()
.buildSortableMultivaluedDateField("dateMulti", dateSortFunction);
final SingleValuedComplexField.UtilDateComplexField<Taxonomy,Date,Date> dateSingle = new ComplexFieldDescriptorBuilder<Taxonomy,Date,Date>()
.setStored(true, tx -> tx.getUtilDate())
.buildUtilDateComplexField("singleDate", Taxonomy.class, Date.class, Date.class);
final MultiValuedComplexField.DateComplexField<Taxonomy,ZonedDateTime,ZonedDateTime> dateComplexMulti = new ComplexFieldDescriptorBuilder<Taxonomy,ZonedDateTime,ZonedDateTime>()
.setStored(true, tx -> tx.getDate())
.buildMultivaluedDateComplexField("dateComplexMulti", Taxonomy.class, ZonedDateTime.class, ZonedDateTime.class);
final DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(textMulti)
.addField(numMulti)
.addField(dateMulti)
.addField(dateSingle)
.addField(dateComplexMulti)
.build();
final Document doc1 = assets.createDoc("1")
.setValues(textMulti, "text 1.1", "text 1.2")
.setValues(numMulti,6,7,8)
.setValue(dateSingle, new Taxonomy("today", 2, "todays date", ZonedDateTime.now()))
.setValues(dateComplexMulti, new Taxonomy("today", 2, "todays date", ZonedDateTime.now()), new Taxonomy("today", 2, "todays date", ZonedDateTime.now().minusDays(1)))
.setValues(dateMulti, ZonedDateTime.now().minusMonths(3));
final Document doc2 = assets.createDoc("2")
.setValues(textMulti, "text 2.1", "text 2.2")
.setValues(numMulti, 1, 2, 3)
.setValue(dateSingle, new Taxonomy("today", 1, "todays date", ZonedDateTime.now().plusDays(1)))
.setValues(dateComplexMulti, new Taxonomy("today", 2, "todays date", ZonedDateTime.now().plusDays(2)), new Taxonomy("today", 2, "todays date", ZonedDateTime.now().minusDays(1)))
.setValues(dateMulti, ZonedDateTime.now().plusMonths(1));
final Document doc3 = assets.createDoc("3")
.addValue(textMulti, null);
final SearchServer server = testBackend.getSearchServer();
server.index(doc1);
server.index(doc2);
server.index(doc3);
server.commit();
//test empty filter in single valued field
FulltextSearch searchAll = Search.fulltext().sort(asc(textMulti));
SearchResult searchResult = server.execute(searchAll, assets).print();
assertEquals("Documents are properly ordered by multi valued text field", "1", searchResult.getResults().get(0).getId());
searchAll = Search.fulltext().sort(desc(numMulti));
searchResult = server.execute(searchAll, assets).print();
assertEquals("Documents are properly ordered by multi valued numeric field", "1", searchResult.getResults().get(0).getId());
searchAll = Search.fulltext().sort(desc(dateMulti));
searchResult = server.execute(searchAll, assets).print();
assertEquals("Documents are properly ordered by multi valued date field", "2",searchResult.getResults().get(0).getId());
searchAll = Search.fulltext().sort(desc(dateSingle));
searchResult = server.execute(searchAll, assets).print();
assertEquals("Documents are properly ordered by multi valued date field", "2",searchResult.getResults().get(0).getId());
searchAll = Search.fulltext().sort(desc(dateComplexMulti));
searchResult = server.execute(searchAll, assets).print();
assertEquals("Documents are properly ordered by multi valued date field", "2",searchResult.getResults().get(0).getId());
}
//MBDN-483
@Test
@RunWithBackend({Elastic,Solr})
public void atomicUpdateComplexFieldsTest() {
SingleValuedComplexField.NumericComplexField<Taxonomy,Integer,String> numericComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,Integer,String>()
.setFacet(true, tx -> Arrays.asList(tx.getId()))
.setFullText(true, tx -> Arrays.asList(tx.getTerm()))
.setSuggest(true, tx -> Arrays.asList(tx.getLabel()))
.buildNumericComplexField("numberFacetTaxonomy", Taxonomy.class, Integer.class, String.class);
SingleValuedComplexField.DateComplexField<Taxonomy,ZonedDateTime,String> dateComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,ZonedDateTime,String>()
.setFacet(true, tx -> Arrays.asList(tx.getDate()))
.setFullText(true, tx -> Arrays.asList(tx.getTerm()))
.setSuggest(true, tx -> Arrays.asList(tx.getLabel()))
.buildDateComplexField("dateFacetTaxonomy", Taxonomy.class, ZonedDateTime.class, String.class);
SingleValuedComplexField.TextComplexField<Taxonomy,String,String> textComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,String,String>()
.setFacet(true, tx -> Arrays.asList(tx.getLabel()))
.setAdvanceFilter(true, tx -> Arrays.asList(tx.getLabel()))
.setSuggest(true, tx -> Arrays.asList(tx.getLabel()))
.setStored(true, tx -> tx.getTerm())
.buildTextComplexField("textFacetTaxonomy", Taxonomy.class, String.class, String.class);
SingleValuedComplexField.DateComplexField<Taxonomy,ZonedDateTime,ZonedDateTime> dateStoredComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,ZonedDateTime,ZonedDateTime>()
.setStored(true, tx -> tx.getDate())
.buildSortableDateComplexField("dateStoredFacetTaxonomy", Taxonomy.class, ZonedDateTime.class, ZonedDateTime.class, cdf -> cdf.getDate());
MultiValuedComplexField.TextComplexField<Taxonomy,String,String> multiComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,String,String>()
.setFacet(true, tx -> Arrays.asList(tx.getLabel()))
.setAdvanceFilter(true, tx -> Arrays.asList(tx.getLabel()))
.setSuggest(true, tx -> Arrays.asList(tx.getLabel()))
.setStored(true, tx -> tx.getTerm())
.buildMultivaluedTextComplexField("multiTextTaxonomy", Taxonomy.class, String.class, String.class);
FieldDescriptor<String> entityID = new FieldDescriptorBuilder()
.buildTextField("entityID");
SingleValueFieldDescriptor<Date> dateField = new FieldDescriptorBuilder()
.buildUtilDateField("date");
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(numericComplexField)
.addField(dateComplexField)
.addField(textComplexField)
.addField(dateField)
.addField(dateStoredComplexField)
.addField(entityID)
.addField(multiComplexField)
.setUpdatable(true)
.build();
Document d1 = assets.createDoc("1")
.setValue(numericComplexField, new Taxonomy("uno", 1, "Uno label", ZonedDateTime.now()))
.setValue(dateComplexField, new Taxonomy("uno", 1, "Uno label",ZonedDateTime.now()))
.setValue(textComplexField, new Taxonomy("uno", 1, "Label", ZonedDateTime.now()))
.setValue(entityID, "123")
.setValue(dateStoredComplexField, new Taxonomy("uno", 1, "Label",ZonedDateTime.now()))
.setValues(multiComplexField, new Taxonomy("uno", 1, "Label", ZonedDateTime.now()), new Taxonomy("dos", 2, "Label dos", ZonedDateTime.now()))
.setValue(dateField, new Date());
Document d2 = assets.createDoc("2")
.setValue(numericComplexField, new Taxonomy("dos", 2, "dos label", ZonedDateTime.now()))
.setValue(dateComplexField,new Taxonomy("dos", 2, "dos label",ZonedDateTime.now()))
.setValue(textComplexField,new Taxonomy("uno", 2, "Label",ZonedDateTime.now()))
.setValue(entityID, "456")
.setValue(dateStoredComplexField,new Taxonomy("uno", 1, "Label",ZonedDateTime.now().plusMonths(1)))
.setValues(multiComplexField, new Taxonomy("uno", 1, "Label", ZonedDateTime.now()), new Taxonomy("dos", 1, "Label", ZonedDateTime.now()))
.setValue(dateField, new Date());
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.commit();
server.execute(Search.update("1")
.set(textComplexField, new Taxonomy("unoUpdated", 11, "Uno label updated", ZonedDateTime.now().plusMonths(1))), assets);
server.commit();
GetResult result = server.execute(Search.getById("1"), assets);
Assert.assertTrue(true);
server.execute(Search.update("1")
.set(
multiComplexField,
new Taxonomy("multiUpdated", 11, "label multiUpdated", ZonedDateTime.now().plusMonths(1))), assets);
server.commit();
result = server.execute(Search.getById("1"), assets);
Assert.assertTrue(true);
}
//MDBN-486
@Test
@RunWithBackend({Elastic, Solr})
public void advanceFilterTest() {
SingleValuedComplexField.TextComplexField<Taxonomy,String,String> textComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,String,String>()
.setFacet(true, tx -> Arrays.asList(tx.getLabel()))
.setAdvanceFilter(true, tx -> Arrays.asList(tx.getTerm()))
.buildTextComplexField("textFacetTaxonomy", Taxonomy.class, String.class, String.class);
MultiValuedComplexField.TextComplexField<Taxonomy,String,String> multiComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,String,String>()
.setFacet(true, tx -> Arrays.asList(tx.getLabel()))
.setStored(true, tx -> tx.getTerm())
.setAdvanceFilter(true, tx -> Arrays.asList(tx.getTerm()))
.buildMultivaluedTextComplexField("multiTextTaxonomy", Taxonomy.class, String.class, String.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(textComplexField)
.addField(multiComplexField)
.build();
Document d1 = assets.createDoc("1")
.setValue(textComplexField, new Taxonomy("uno", 1, "Label", ZonedDateTime.now()))
.setValues(multiComplexField, new Taxonomy("uno", 1, "Label", ZonedDateTime.now()), new Taxonomy("dos", 2, "Label dos", ZonedDateTime.now()));
Document d2 = assets.createDoc("2")
.setValue(textComplexField, new Taxonomy("dos", 2, "Label", ZonedDateTime.now()))
.setValues(multiComplexField, new Taxonomy("dos . uno", 1, "Label", ZonedDateTime.now()), new Taxonomy("dos . dos", 1, "Label", ZonedDateTime.now()));
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.commit();
SearchResult result = server.execute(Search.fulltext().filter(textComplexField.equals("uno",Scope.Filter)), assets);
Assert.assertEquals(1, result.getNumOfResults());
Assert.assertEquals("1", result.getResults().get(0).getId());
result = server.execute(Search.fulltext().filter(multiComplexField.equals("uno",Scope.Filter)), assets);
Assert.assertEquals(1, result.getNumOfResults());
Assert.assertEquals("1", result.getResults().get(0).getId());
}
//MBDN-461
@Test
@RunWithBackend({Solr, Elastic})
public void prefixFilterTest(){
final SingleValueFieldDescriptor.TextFieldDescriptor<String> textSingle = new FieldDescriptorBuilder()
.setFacet(true)
.buildTextField("textSingle");
final MultiValueFieldDescriptor.TextFieldDescriptor<String> textMulti = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedTextField("textMulti");
final DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(textSingle)
.addField(textMulti)
.build();
final Document doc1 = assets.createDoc("1")
.setValue(textSingle, "text 1");
final Document doc2 = assets.createDoc("2")
.setValue(textSingle, "Other text 2")
.setValues(textMulti, "text 2.1", "text 2.2");
final SearchServer server = testBackend.getSearchServer();
server.index(doc1);
server.index(doc2);
server.commit();
FulltextSearch searchAll = Search.fulltext().filter(textSingle.prefix("tex"));
SearchResult searchResult = server.execute(searchAll, assets).print();
assertEquals("Just documents with single text fields starting with 'tex'", 1, searchResult.getNumOfResults());
searchAll = Search.fulltext().filter(textMulti.prefix("tex"));
searchResult = server.execute(searchAll, assets).print();
assertEquals("Just documents with multi text fields starting with 'tex'", 1, searchResult.getNumOfResults());
}
//MBDN-487
@Test
@RunWithBackend({Elastic,Solr})
public void scopedFilterTest() {
MultiValuedComplexField.TextComplexField<Taxonomy,String,String> multiComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,String,String>()
.setFacet(true, tx -> Arrays.asList(tx.getLabel()))
.setStored(true, tx -> tx.getTerm())
.setAdvanceFilter(true, tx -> Arrays.asList(tx.getTerm()))
.buildMultivaluedTextComplexField("multiTextTaxonomy", Taxonomy.class, String.class, String.class);
SingleValuedComplexField.TextComplexField<Taxonomy,String,String> textComplexField = new ComplexFieldDescriptorBuilder<Taxonomy,String,String>()
.setFacet(true, tx -> Arrays.asList(tx.getLabel()))
.setAdvanceFilter(true, tx -> Arrays.asList(tx.getTerm()))
.buildTextComplexField("textFacetTaxonomy", Taxonomy.class, String.class, String.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(textComplexField)
.addField(multiComplexField)
.build();
Document d1 = assets.createDoc("1")
.setValue(textComplexField, new Taxonomy("uno", 1, "Label", ZonedDateTime.now()))
.setValues(multiComplexField, new Taxonomy("uno", 1, "Label", ZonedDateTime.now()), new Taxonomy("dos", 2, "Label dos", ZonedDateTime.now()));
Document d2 = assets.createDoc("2")
.setValue(textComplexField, new Taxonomy("dos", 2, "Label", ZonedDateTime.now()))
.setValues(multiComplexField, new Taxonomy("dos . uno", 1, "Label", ZonedDateTime.now()), new Taxonomy("dos . dos", 1, "Label", ZonedDateTime.now()));
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.commit();
SearchResult result = server.execute(Search.fulltext().filter(textComplexField.equals("uno", Scope.Filter)), assets);
Assert.assertEquals(1, result.getNumOfResults());
Assert.assertEquals("1", result.getResults().get(0).getId());
result = server.execute(Search.fulltext().filter(multiComplexField.equals("uno", Scope.Filter)), assets);
Assert.assertEquals(1, result.getNumOfResults());
Assert.assertEquals("1", result.getResults().get(0).getId());
}
//MBDN-495
@Test
@RunWithBackend({Elastic,Solr})
public void sliceResultTest(){
final TextFieldDescriptor textMulti = new FieldDescriptorBuilder()
.buildMultivaluedTextField("textMulti");
final NumericFieldDescriptor<Integer> numMulti = new FieldDescriptorBuilder()
.buildMultivaluedNumericField("numMulti", Integer.class);
final DateFieldDescriptor dateMulti = new FieldDescriptorBuilder()
.buildSortableMultivaluedDateField("dateMulti", txs -> ((Collection<ZonedDateTime>) txs).stream().max(Comparator.<ZonedDateTime>naturalOrder()).get());
final SingleValuedComplexField.UtilDateComplexField<Taxonomy,Date,Date> dateSingle = new ComplexFieldDescriptorBuilder<Taxonomy,Date,Date>()
.setStored(true, tx -> tx.getUtilDate())
.buildUtilDateComplexField("singleDate", Taxonomy.class, Date.class, Date.class);
final MultiValuedComplexField.DateComplexField<Taxonomy,ZonedDateTime,ZonedDateTime> dateComplexMulti = new ComplexFieldDescriptorBuilder<Taxonomy,ZonedDateTime,ZonedDateTime>()
.setStored(true, tx -> tx.getDate())
.buildMultivaluedDateComplexField("dateComplexMulti", Taxonomy.class, ZonedDateTime.class, ZonedDateTime.class);
final DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(textMulti)
.addField(numMulti)
.addField(dateMulti)
.addField(dateSingle)
.addField(dateComplexMulti)
.build();
final Document doc1 = assets.createDoc("1")
.setValues(textMulti, "text 1.1", "text 1.2")
.setValues(numMulti,6,7,8)
.setValue(dateSingle, new Taxonomy("today", 2, "todays date", ZonedDateTime.now()))
.setValues(dateComplexMulti, new Taxonomy("today", 2, "todays date", ZonedDateTime.now()), new Taxonomy("today", 2, "todays date", ZonedDateTime.now().minusDays(1)))
.setValues(dateMulti, ZonedDateTime.now().minusMonths(3));
final Document doc2 = assets.createDoc("2")
.setValues(textMulti, "text 2.1", "text 2.2")
.setValues(numMulti, 1, 2, 3)
.setValue(dateSingle, new Taxonomy("today", 1, "todays date", ZonedDateTime.now()))
.setValues(dateComplexMulti, new Taxonomy("today", 2, "todays date", ZonedDateTime.now().plusDays(2)), new Taxonomy("today", 2, "todays date", ZonedDateTime.now().minusDays(1)))
.setValues(dateMulti, ZonedDateTime.now().plusMonths(1));
final Document doc3 = assets.createDoc("3")
.addValue(textMulti, null);
final SearchServer server = testBackend.getSearchServer();
server.index(doc1);
server.index(doc2);
server.index(doc3);
server.commit();
//test empty filter in single valued field
FulltextSearch searchAll = Search.fulltext().slice(1).sort(asc(textMulti));
SearchResult searchResult = server.execute(searchAll, assets).print();
assertEquals("An Slice starting in index 1", "2", searchResult.getResults().get(0).getId());
}
//MBDN-498
@Test
@RunWithBackend({Solr, Elastic})
public void byQueryFacetConfigurationTest() {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime yesterday = ZonedDateTime.now(ZoneId.of("UTC")).minus(1, ChronoUnit.DAYS);
FieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("title");
SingleValueFieldDescriptor.DateFieldDescriptor<ZonedDateTime> created = new FieldDescriptorBuilder()
.setFacet(true)
.buildDateField("created");
SingleValueFieldDescriptor.UtilDateFieldDescriptor<Date> modified = new FieldDescriptorBuilder()
.setFacet(true)
.buildUtilDateField("modified");
NumericFieldDescriptor<Long> category = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedNumericField("category", Long.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(title, created, category, modified)
.build();
Document d1 = assets.createDoc("1")
.setValue(title, "Hello World")
.setValue(created, yesterday)
.setValue(modified, new Date())
.setValues(category,1L, 2L);
Document d2 = assets.createDoc("2")
.setValue(title, "Friends")
.setValue(created, now)
.setValue(modified, new Date())
.addValue(category, 4L);
Document d3 = assets.createDoc("3")
.setValue(title, "Hello")
.setValue(created, now)
.setValue(modified, new Date());
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.index(d3);
server.commit();
FulltextSearch search = Search.fulltext("hello")
.facet(category)
.setFacetLimit(2)
.setFacetMinCount(1)
.sort(desc(created));
PageResult result = (PageResult)server.execute(search,assets);
assertEquals(2, result.getFacetResults().getTermFacet(category).getValues().size());
}
@Test
@RunWithBackend({Solr, Elastic})
public void queryTermWithDashCharTest(){
SingleValueFieldDescriptor.TextFieldDescriptor internalId = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("internalId");
SingleValueFieldDescriptor.TextFieldDescriptor textField = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("textField");
NumericFieldDescriptor<Long> category = new FieldDescriptorBuilder()
.setFacet(true)
.buildMultivaluedNumericField("category", Long.class);
DocumentFactory assets = new DocumentFactoryBuilder("asset")
.addField(internalId, textField, category)
.build();
Document d1 = assets.createDoc("1")
.setValue(internalId, "A-20170322-001")
.setValue(textField, "")
.setValues(category, 1L, 2L);
Document d2 = assets.createDoc("2")
.setValue(internalId, "PN-1HBTR8P952111")
.setValue(textField, "")
.addValue(category, 4L);
Document d3 = assets.createDoc("3")
.setValue(internalId, "1234-34345-54656")
.setValue(textField, "");
Document d4 = assets.createDoc("4")
.setValue(internalId, "")
.setValue(textField, "This is a text1234 field");
Document d5 = assets.createDoc("5")
.setValue(internalId, "And this is another text-1234 field")
.setValue(textField, "");
Document d6= assets.createDoc("6")
.setValue(internalId, "")
.setValue(textField, "This is a text 1234 field");
SearchServer server = testBackend.getSearchServer();
server.index(d1);
server.index(d2);
server.index(d3);
server.index(d4);
server.index(d5);
server.index(d6);
server.commit();
FulltextSearch search = Search.fulltext("A-20170322-001 1234-34345-54656 PN-1HBTR8P952111");
PageResult result = (PageResult)server.execute(search,assets);
assertEquals(3, result.getResults().size());
search = Search.fulltext("1234");
result = (PageResult)server.execute(search,assets);
assertEquals(1, result.getResults().size());
}
//MBDN-563
@Test
@RunWithBackend(Solr)
public void testSubdocumentFullReindex() throws IOException {
SearchServer server = testBackend.getSearchServer();
server.clearIndex();
server.commit();
SingleValueFieldDescriptor<String> title = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.buildTextField("title");
SingleValueFieldDescriptor<String> color = new FieldDescriptorBuilder()
.setFullText(true)
.setFacet(true)
.setSuggest(true)
.buildTextField("color");
SingleValueFieldDescriptor<String> parent = new FieldDescriptorBuilder().setFacet(true).buildTextField("parent");
DocumentFactory asset = new DocumentFactoryBuilder("asset")
.setUpdatable(true)
.addField(title, color)
.build();
DocumentFactory marker = new DocumentFactoryBuilder("marker")
.setUpdatable(true)
.addField(title, color, parent)
.build();
Document a1 = asset.createDoc("A1")
.setValue(title, "A1 1")
.setValue(color, "blue");
Document a2 = asset.createDoc("A2")
.setValue(title, "A2")
.setValue(color, "red")
.addChild(marker.createDoc("M1")
.setValue(title, "M1")
.setValue(parent, "A2")
.setValue(color, "blue")
)
.addChild(marker.createDoc("M4")
.setValue(title, "M4")
.setValue(parent, "A2")
.setValue(color, "green")
)
.addChild(marker.createDoc("M5")
.setValue(title, "M5")
.setValue(parent, "A2")
.setValue(color, "yellow")
);
Document a3 = asset.createDoc("A3").setValue(title,"A3").setValue(color, "green").addChild(marker.createDoc("M2").setValue(title, "M2").setValue(parent, "A3").setValue(color, "red"));
Document a4 = asset.createDoc("A4").setValue(title, "A4").setValue(color, "blue").addChild(marker.createDoc("M3").setValue(title, "M3").setValue(parent, "A4").setValue(color, "blue"));
server.index(a1);
server.index(a2);
server.index(a3);
server.index(a4);
server.commit();
//Test whether sub-documents are automatically removed from index when full indexing a parent document without them
a2.getChildren().clear();
a2.addChild(marker.createDoc("M6")
.setValue(title, "M6")
.setValue(parent, "A2")
.setValue(color, "purple")
);
server.index(a2);
server.commit();
final GetResult getM6child = server.execute(Search.getById("M6"), marker);//search in all markers
assertEquals("Subdocument with id:'M6' is indexed", 1, getM6child.getNumOfResults());
final GetResult getM4child = server.execute(Search.getById("M4"), marker);//search in all markers
assertEquals("subdocument with id:'M4' is no more in the index", 0, getM4child.getNumOfResults());
|
package at.maui.cardar.ui.ar;
import static at.maui.cardar.ui.ar.GLUtils.checkGLError;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.opengl.Matrix;
import com.google.vrtoolkit.cardboard.CardboardView;
import com.google.vrtoolkit.cardboard.EyeTransform;
import com.google.vrtoolkit.cardboard.HeadTransform;
import com.google.vrtoolkit.cardboard.Viewport;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import at.maui.cardar.R;
import timber.log.Timber;
public class Renderer implements CardboardView.StereoRenderer {
// We keep the light always position just above the user.
private final float[] mLightPosInWorldSpace = new float[] {0.0f, 2.0f, 0.0f, 1.0f};
private final float[] mLightPosInEyeSpace = new float[4];
private static final int COORDS_PER_VERTEX = 3;
private static final float CAMERA_Z = 0.01f;
//private static final float TIME_DELTA = 0.3f;
private static final float YAW_LIMIT = 0.12f;
private static final float PITCH_LIMIT = 0.12f;
private final WorldLayoutData DATA = new WorldLayoutData();
private Context mContext;
private int[] mGlPrograms;
private FloatBuffer mFloorVertices;
private FloatBuffer mFloorColors;
private FloatBuffer mFloorNormals;
private FloatBuffer mWallVertices;
private FloatBuffer mWallColors;
private FloatBuffer mWallNormals;
//private FloatBuffer mCubeVertices;
//private FloatBuffer mCubeColors;
//private FloatBuffer mCubeFoundColors;
//private FloatBuffer mCubeNormals;
// Head Position
private float[] mHeadView;
private float[] mView;
private float[] mModelCube;
private float[] mCamera;
private float[] mModelFloor;
private float[] mModelWall;
private float[] mModelViewProjection;
private float[] mModelViewProjectionWall;
private float[] mModelView;
private float[] mModelViewWall;
private int[] mTextures;
private int mPositionParam;
private int mTextureCoordParam;
private int mTextureParam;
private int mNormalParam;
private int mColorParam;
private int mModelViewProjectionParam;
private int mLightPosParam;
private int mModelViewParam;
private int mModelParam;
private int mIsFloorParam;
private FloatBuffer pVertex;
private FloatBuffer pTexCoord;
private Camera mRealCamera;
private SurfaceTexture mRealCameraTexture;
private float mObjectDistance = 12f;
private float mFloorDepth = 60f;
public Renderer(Context ctx) {
mContext = ctx;
mCamera = new float[16];
mView = new float[16];
mHeadView = new float[16];
mGlPrograms = new int[2];
mModelCube = new float[16];
mModelFloor = new float[16];
mModelWall = new float[16];
mModelViewProjection = new float[16];
mModelViewProjectionWall = new float[16];
mModelView = new float[16];
mModelViewWall = new float[16];
float[] vtmp = { 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f };
float[] ttmp = { 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f };
pVertex = ByteBuffer.allocateDirect(8 * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
pVertex.put ( vtmp );
pVertex.position(0);
pTexCoord = ByteBuffer.allocateDirect(8*4).order(ByteOrder.nativeOrder()).asFloatBuffer();
pTexCoord.put ( ttmp );
pTexCoord.position(0);
}
@Override
public void onNewFrame(HeadTransform headTransform) {
// Build the Model part of the ModelView matrix.
//Matrix.rotateM(mModelCube, 0, TIME_DELTA, 0.5f, 0.5f, 1.0f);
// Build the camera matrix and apply it to the ModelView.
Matrix.setLookAtM(mCamera, 0, 0.0f, 0.0f, CAMERA_Z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
headTransform.getHeadView(mHeadView, 0);
mRealCameraTexture.updateTexImage();
checkGLError("onReadyToDraw");
}
@Override
public void onDrawEye(EyeTransform eyeTransform) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
// Apply the eye transformation to the camera.
Matrix.multiplyMM(mView, 0, eyeTransform.getEyeView(), 0, mCamera, 0);
/*GLES20.glUseProgram(mGlPrograms[0]);
mPositionParam = GLES20.glGetAttribLocation(mGlPrograms[0], "vPosition");
mTextureCoordParam = GLES20.glGetAttribLocation(mGlPrograms[0], "vTexCoord");
mTextureParam = GLES20.glGetAttribLocation(mGlPrograms[0], "sTexture");
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextures[0]);
GLES20.glUniform1i(mTextureParam, 0);
GLES20.glVertexAttribPointer(mPositionParam, 2, GLES20.GL_FLOAT, false, 4*2, pVertex);
GLES20.glVertexAttribPointer(mTextureCoordParam, 2, GLES20.GL_FLOAT, false, 4*2, pTexCoord );
GLES20.glEnableVertexAttribArray(mPositionParam);
GLES20.glEnableVertexAttribArray(mTextureCoordParam);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
GLES20.glFlush();
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT);*/
GLES20.glUseProgram(mGlPrograms[1]);
mTextureParam = GLES20.glGetAttribLocation(mGlPrograms[1], "v_Texture");
mTextureCoordParam = GLES20.glGetAttribLocation(mGlPrograms[1], "v_TextCoord");
mModelViewProjectionParam = GLES20.glGetUniformLocation(mGlPrograms[1], "u_MVP");
mLightPosParam = GLES20.glGetUniformLocation(mGlPrograms[1], "u_LightPos");
mModelViewParam = GLES20.glGetUniformLocation(mGlPrograms[1], "u_MVMatrix");
mModelParam = GLES20.glGetUniformLocation(mGlPrograms[1], "u_Model");
mIsFloorParam = GLES20.glGetUniformLocation(mGlPrograms[1], "u_IsFloor");
mPositionParam = GLES20.glGetAttribLocation(mGlPrograms[1], "a_Position");
mNormalParam = GLES20.glGetAttribLocation(mGlPrograms[1], "a_Normal");
mColorParam = GLES20.glGetAttribLocation(mGlPrograms[1], "a_Color");
GLES20.glVertexAttribPointer(mTextureCoordParam, 2, GLES20.GL_FLOAT, false, 4*2, pTexCoord );
GLES20.glEnableVertexAttribArray(mTextureCoordParam);
GLES20.glEnableVertexAttribArray(mPositionParam);
GLES20.glEnableVertexAttribArray(mNormalParam);
GLES20.glEnableVertexAttribArray(mColorParam);
checkGLError("mColorParam");
// Set the position of the light
Matrix.multiplyMV(mLightPosInEyeSpace, 0, mView, 0, mLightPosInWorldSpace, 0);
GLES20.glUniform3f(mLightPosParam, mLightPosInEyeSpace[0], mLightPosInEyeSpace[1],
mLightPosInEyeSpace[2]);
// Build the ModelView and ModelViewProjection matrices
// for calculating cube position and light.
Matrix.multiplyMM(mModelView, 0, mView, 0, mModelCube, 0);
Matrix.multiplyMM(mModelViewProjection, 0, eyeTransform.getPerspective(), 0, mModelView, 0);
//drawCube();
//Matrix.multiplyMM(mModelView, 0, mView, 0, mModelWall, 0);
Matrix.setIdentityM(mModelViewWall, 0);
Matrix.translateM(mModelViewWall, 0, 0, -5f, -78f);
Matrix.multiplyMM(mModelViewProjectionWall, 0, eyeTransform.getPerspective(), 0,
mModelViewWall, 0);
drawWall();
// Set mModelView for the floor, so we draw floor in the correct location
Matrix.multiplyMM(mModelView, 0, mView, 0, mModelFloor, 0);
Matrix.multiplyMM(mModelViewProjection, 0, eyeTransform.getPerspective(), 0,
mModelView, 0);
drawFloor(eyeTransform.getPerspective());
}
/* public void drawCube() {
// This is not the floor!
GLES20.glUniform1f(mIsFloorParam, 0f);
// Set the Model in the shader, used to calculate lighting
GLES20.glUniformMatrix4fv(mModelParam, 1, false, mModelCube, 0);
// Set the ModelView in the shader, used to calculate lighting
GLES20.glUniformMatrix4fv(mModelViewParam, 1, false, mModelView, 0);
// Set the position of the cube
GLES20.glVertexAttribPointer(mPositionParam, COORDS_PER_VERTEX, GLES20.GL_FLOAT,
false, 0, mCubeVertices);
// Set the ModelViewProjection matrix in the shader.
GLES20.glUniformMatrix4fv(mModelViewProjectionParam, 1, false, mModelViewProjection, 0);
// Set the normal positions of the cube, again for shading
GLES20.glVertexAttribPointer(mNormalParam, 3, GLES20.GL_FLOAT,
false, 0, mCubeNormals);
if (isLookingAtObject()) {
GLES20.glVertexAttribPointer(mColorParam, 4, GLES20.GL_FLOAT, false,
0, mCubeFoundColors);
} else {
GLES20.glVertexAttribPointer(mColorParam, 4, GLES20.GL_FLOAT, false,
0, mCubeColors);
}
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 36);
checkGLError("Drawing cube");
} */
public void drawWall() {
GLES20.glUniform1f(mIsFloorParam, 0.3f);
// Set the Model in the shader, used to calculate lighting
GLES20.glUniformMatrix4fv(mModelParam, 1, false, mModelViewWall, 0);
// Set the ModelView in the shader, used to calculate lighting
GLES20.glUniformMatrix4fv(mModelViewParam, 1, false, mModelViewWall, 0);
// Set the position of the cube
GLES20.glVertexAttribPointer(mPositionParam, COORDS_PER_VERTEX, GLES20.GL_FLOAT,
false, 0, mWallVertices);
// Set the ModelViewProjection matrix in the shader.
GLES20.glUniformMatrix4fv(mModelViewProjectionParam, 1, false, mModelViewProjectionWall, 0);
// Set the normal positions of the cube, again for shading
GLES20.glVertexAttribPointer(mNormalParam, 3, GLES20.GL_FLOAT,
false, 0, mWallNormals);
GLES20.glVertexAttribPointer(mColorParam, 4, GLES20.GL_FLOAT, false,
0, mWallColors);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextures[0]);
GLES20.glUniform1i(mTextureParam, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
checkGLError("drawing wall");
}
public void drawFloor(float[] perspective) {
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
GLES20.glBlendColor(1.f, 1.f, 1.f, 0.7f);
// This is the floor!
GLES20.glUniform1f(mIsFloorParam, 1f);
// Set ModelView, MVP, position, normals, and color
GLES20.glUniformMatrix4fv(mModelParam, 1, false, mModelFloor, 0);
GLES20.glUniformMatrix4fv(mModelViewParam, 1, false, mModelView, 0);
GLES20.glUniformMatrix4fv(mModelViewProjectionParam, 1, false, mModelViewProjection, 0);
GLES20.glVertexAttribPointer(mPositionParam, COORDS_PER_VERTEX, GLES20.GL_FLOAT,
false, 0, mFloorVertices);
GLES20.glVertexAttribPointer(mNormalParam, 3, GLES20.GL_FLOAT, false, 0, mFloorNormals);
GLES20.glVertexAttribPointer(mColorParam, 4, GLES20.GL_FLOAT, false, 0, mFloorColors);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);
GLES20.glDisable(GLES20.GL_BLEND);
checkGLError("drawing floor");
}
@Override
public void onFinishFrame(Viewport viewport) {
}
@Override
public void onSurfaceChanged(int width, int height) {
Timber.e("onSurfaceChanged(%d, %d)", width, height);
}
@Override
public void onSurfaceCreated(EGLConfig eglConfig) {
Timber.e("onSurfaceCreated");
GLES20.glClearColor(0.1f, 0.1f, 0.1f, 0.5f); // Dark background so text shows up well
// Init Objects here
initTextures();
initRealWorldCamera();
initModels();
initWorldShader();
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
// Object first appears directly in front of user
Matrix.setIdentityM(mModelCube, 0);
Matrix.translateM(mModelCube, 0, 0, 0, -mObjectDistance);
Matrix.setIdentityM(mModelFloor, 0);
Matrix.translateM(mModelFloor, 0, 0, -mFloorDepth, 0); // Floor appears below user
Matrix.setIdentityM(mModelWall, 0);
Matrix.translateM(mModelWall, 0, 0, 0, -16f);
checkGLError("onSurfaceCreated");
}
private void initTextures() {
mTextures = new int[1];
GLES20.glGenTextures ( 1, mTextures, 0 );
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextures[0]);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
}
private void initRealWorldCamera() {
mRealCamera = Camera.open(0);
//Set the camera parameters
Camera.Parameters params = mRealCamera.getParameters();
int fps = 0;
for(Integer nfps : params.getSupportedPreviewFrameRates()) {
if(nfps > fps)
fps = nfps;
}
params.setPreviewFrameRate(fps);
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
params.setPreviewSize(1920,1080);
mRealCamera.setParameters(params);
mRealCameraTexture = new SurfaceTexture(mTextures[0]);
try {
mRealCamera.setPreviewTexture(mRealCameraTexture);
} catch (IOException t) {
Timber.e("Cannot set preview texture target!");
}
//Start the preview
mRealCamera.startPreview();
}
/**
* Find a new random position for the object.
* We'll rotate it around the Y-axis so it's out of sight, and then up or down by a little bit.
*/
public void hideObject() {
float[] rotationMatrix = new float[16];
float[] posVec = new float[4];
// First rotate in XZ plane, between 90 and 270 deg away, and scale so that we vary
// the object's distance from the user.
float angleXZ = (float) Math.random() * 180 + 90;
Matrix.setRotateM(rotationMatrix, 0, angleXZ, 0f, 1f, 0f);
float oldObjectDistance = mObjectDistance;
mObjectDistance = (float) Math.random() * 15 + 5;
float objectScalingFactor = mObjectDistance / oldObjectDistance;
Matrix.scaleM(rotationMatrix, 0, objectScalingFactor, objectScalingFactor, objectScalingFactor);
Matrix.multiplyMV(posVec, 0, rotationMatrix, 0, mModelCube, 12);
// Now get the up or down angle, between -20 and 20 degrees
float angleY = (float) Math.random() * 80 - 40; // angle in Y plane, between -40 and 40
angleY = (float) Math.toRadians(angleY);
float newY = (float)Math.tan(angleY) * mObjectDistance;
Matrix.setIdentityM(mModelCube, 0);
Matrix.translateM(mModelCube, 0, posVec[0], newY, posVec[2]);
}
/**
* Check if user is looking at object by calculating where the object is in eye-space.
* @return
*/
public boolean isLookingAtObject() {
float[] initVec = {0, 0, 0, 1.0f};
float[] objPositionVec = new float[4];
// Convert object space to camera space. Use the headView from onNewFrame.
Matrix.multiplyMM(mModelView, 0, mHeadView, 0, mModelCube, 0);
Matrix.multiplyMV(objPositionVec, 0, mModelView, 0, initVec, 0);
float pitch = (float)Math.atan2(objPositionVec[1], -objPositionVec[2]);
float yaw = (float)Math.atan2(objPositionVec[0], -objPositionVec[2]);
Timber.i("Object position: X: " + objPositionVec[0]
+ " Y: " + objPositionVec[1] + " Z: " + objPositionVec[2]);
Timber.i("Object Pitch: " + pitch +" Yaw: " + yaw);
return (Math.abs(pitch) < PITCH_LIMIT) && (Math.abs(yaw) < YAW_LIMIT);
}
private void initModels() {
/* ByteBuffer bbVertices = ByteBuffer.allocateDirect(DATA.CUBE_COORDS.length * 4);
bbVertices.order(ByteOrder.nativeOrder());
mCubeVertices = bbVertices.asFloatBuffer();
mCubeVertices.put(DATA.CUBE_COORDS);
mCubeVertices.position(0);
ByteBuffer bbColors = ByteBuffer.allocateDirect(DATA.CUBE_COLORS.length * 4);
bbColors.order(ByteOrder.nativeOrder());
mCubeColors = bbColors.asFloatBuffer();
mCubeColors.put(DATA.CUBE_COLORS);
mCubeColors.position(0);
ByteBuffer bbFoundColors = ByteBuffer.allocateDirect(DATA.CUBE_FOUND_COLORS.length * 4);
bbFoundColors.order(ByteOrder.nativeOrder());
mCubeFoundColors = bbFoundColors.asFloatBuffer();
mCubeFoundColors.put(DATA.CUBE_FOUND_COLORS);
mCubeFoundColors.position(0);
ByteBuffer bbNormals = ByteBuffer.allocateDirect(DATA.CUBE_NORMALS.length * 4);
bbNormals.order(ByteOrder.nativeOrder());
mCubeNormals = bbNormals.asFloatBuffer();
mCubeNormals.put(DATA.CUBE_NORMALS);
mCubeNormals.position(0); */
// make a floor
ByteBuffer bbFloorVertices = ByteBuffer.allocateDirect(DATA.FLOOR_COORDS.length * 4);
bbFloorVertices.order(ByteOrder.nativeOrder());
mFloorVertices = bbFloorVertices.asFloatBuffer();
mFloorVertices.put(DATA.FLOOR_COORDS);
mFloorVertices.position(0);
ByteBuffer bbFloorNormals = ByteBuffer.allocateDirect(DATA.FLOOR_NORMALS.length * 4);
bbFloorNormals.order(ByteOrder.nativeOrder());
mFloorNormals = bbFloorNormals.asFloatBuffer();
mFloorNormals.put(DATA.FLOOR_NORMALS);
mFloorNormals.position(0);
ByteBuffer bbFloorColors = ByteBuffer.allocateDirect(DATA.FLOOR_COLORS.length * 4);
bbFloorColors.order(ByteOrder.nativeOrder());
mFloorColors = bbFloorColors.asFloatBuffer();
mFloorColors.put(DATA.FLOOR_COLORS);
mFloorColors.position(0);
// make wall
ByteBuffer bbWallVertices = ByteBuffer.allocateDirect(DATA.WALL_COORDS.length * 4);
bbWallVertices.order(ByteOrder.nativeOrder());
mWallVertices = bbWallVertices.asFloatBuffer();
mWallVertices.put(DATA.WALL_COORDS);
mWallVertices.position(0);
ByteBuffer bbWallNormals = ByteBuffer.allocateDirect(DATA.WALL_NORMALS.length * 4);
bbWallNormals.order(ByteOrder.nativeOrder());
mWallNormals = bbWallNormals.asFloatBuffer();
mWallNormals.put(DATA.WALL_NORMALS);
mWallNormals.position(0);
ByteBuffer bbWallColors = ByteBuffer.allocateDirect(DATA.WALL_COLORS.length * 4);
bbWallColors.order(ByteOrder.nativeOrder());
mWallColors = bbWallColors.asFloatBuffer();
mWallColors.put(DATA.WALL_COLORS);
mWallColors.position(0);
}
private int initWorldShader() {
int vertexShader = GLUtils.loadGLShader(mContext, GLES20.GL_VERTEX_SHADER, R.raw.light_vertex);
int gridShader = GLUtils.loadGLShader(mContext, GLES20.GL_FRAGMENT_SHADER, R.raw.grid_fragment);
mGlPrograms[1] = GLES20.glCreateProgram();
GLES20.glAttachShader(mGlPrograms[1], vertexShader);
GLES20.glAttachShader(mGlPrograms[1], gridShader);
GLES20.glLinkProgram(mGlPrograms[1]);
return mGlPrograms[1];
}
@Override
public void onRendererShutdown() {
Timber.e("onRendererShutdown");
GLES20.glDeleteTextures ( 1, mTextures, 0 );
mRealCamera.stopPreview();
mRealCamera.setPreviewCallbackWithBuffer(null);
mRealCamera.release();
}
}
|
package com.example.pac.pacman;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
public class PacMan extends Character {
private static final int MOUTH_RIGHT = 0;
private static final int MOUTH_LEFT = 180;
private static final int MOUTH_UP = 270;
private static final int MOUTH_DOWN = 90;
private int _pMouth = MOUTH_RIGHT;
private static final int MOUTH_OPEN_GRAD = 30;
private static final int MOUTH_CLOSED_GRAD = 0;
private int _mouthOpenGrad = MOUTH_OPEN_GRAD;
private boolean _mouthClosing;
private Paint _paint;
public PacMan(Resources resources, Labyrinth labyrinth) {
super(labyrinth);
_paint = new Paint(Paint.ANTI_ALIAS_FLAG);
_paint.setStyle(Paint.Style.FILL);
_paint.setColor(resources.getColor(R.color.pacman));
}
@Override
public void init() {
super.init();
Rect bounds = _labyrinth.getBounds();
_x = bounds.centerX();
_y = bounds.centerY();
}
@Override
public void draw(Canvas canvas) {
float radius = _size/2;
RectF r = new RectF(_x - radius, _y - radius, _x + radius, _y + radius);
canvas.drawArc(r, _pMouth + _mouthOpenGrad, 360 - 2*_mouthOpenGrad, true, _paint);
}
@Override
public boolean move() {
boolean moved = super.move();
setMouthOpen (moved);
switch (_direction) {
case Stopped:
case Right:
_pMouth = MOUTH_RIGHT;
break;
case Left:
_pMouth = MOUTH_LEFT;
break;
case Up:
_pMouth = MOUTH_UP;
break;
case Down:
_pMouth = MOUTH_DOWN;
break;
}
return moved;
}
private void setMouthOpen(boolean canMove) {
if (!canMove) {
_mouthOpenGrad = MOUTH_OPEN_GRAD;
_mouthClosing = true;
return;
}
if (_mouthOpenGrad == MOUTH_OPEN_GRAD) {
_mouthClosing = true;
} else if (_mouthOpenGrad == MOUTH_CLOSED_GRAD) {
_mouthClosing = false;
}
_mouthOpenGrad += _mouthClosing ? -5 : 5;
}
public void go(float x_touched, float y_touched) {
if (isHorizontal(x_touched, y_touched)) { // horizontal move
if (x_touched < _x) {
goLeft();
} else {
goRight();
}
} else { // vertical move
if (y_touched < _y) {
goUp();
} else {
goDown();
}
}
}
private void goDown() {
_wishDirection = Direction.Down;
}
private void goUp() {
_wishDirection = Direction.Up;
}
private void goRight() {
_wishDirection = Direction.Right;
}
private void goLeft() {
_wishDirection = Direction.Left;
}
private boolean isHorizontal(float x_touched, float y_touched) {
return Math.abs(x_touched - _x) > Math.abs(y_touched - _y);
}
}
|
package net.md_5.bungee;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import io.netty.channel.Channel;
import java.util.Queue;
import lombok.RequiredArgsConstructor;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.config.TexturePackInfo;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.event.ServerKickEvent;
import net.md_5.bungee.api.scoreboard.Objective;
import net.md_5.bungee.api.scoreboard.Score;
import net.md_5.bungee.api.scoreboard.Team;
import net.md_5.bungee.connection.CancelSendSignal;
import net.md_5.bungee.connection.DownstreamBridge;
import net.md_5.bungee.netty.HandlerBoss;
import net.md_5.bungee.packet.DefinedPacket;
import net.md_5.bungee.packet.Packet1Login;
import net.md_5.bungee.packet.Packet9Respawn;
import net.md_5.bungee.packet.PacketCDClientStatus;
import net.md_5.bungee.packet.PacketCEScoreboardObjective;
import net.md_5.bungee.packet.PacketCFScoreboardScore;
import net.md_5.bungee.packet.PacketD1Team;
import net.md_5.bungee.packet.PacketFAPluginMessage;
import net.md_5.bungee.packet.PacketFDEncryptionRequest;
import net.md_5.bungee.packet.PacketFFKick;
import net.md_5.bungee.packet.PacketHandler;
@RequiredArgsConstructor
public class ServerConnector extends PacketHandler
{
private final ProxyServer bungee;
private Channel ch;
private final UserConnection user;
private final ServerInfo target;
private State thisState = State.ENCRYPT_REQUEST;
private enum State
{
ENCRYPT_REQUEST, LOGIN, FINISHED;
}
@Override
public void connected(Channel channel) throws Exception
{
this.ch = channel;
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF( "Login" );
out.writeUTF( user.getAddress().getAddress().getHostAddress() );
out.writeInt( user.getAddress().getPort() );
channel.write( new PacketFAPluginMessage( "BungeeCord", out.toByteArray() ) );
channel.write( user.handshake );
channel.write( PacketCDClientStatus.CLIENT_LOGIN );
}
@Override
public void handle(Packet1Login login) throws Exception
{
Preconditions.checkState( thisState == State.LOGIN, "Not exepcting LOGIN" );
ServerConnection server = new ServerConnection( ch, target, login );
ServerConnectedEvent event = new ServerConnectedEvent( user, server );
bungee.getPluginManager().callEvent( event );
ch.write( BungeeCord.getInstance().registerChannels() );
// TODO: Race conditions with many connects
Queue<DefinedPacket> packetQueue = ( (BungeeServerInfo) target ).getPacketQueue();
while ( !packetQueue.isEmpty() )
{
ch.write( packetQueue.poll() );
}
if ( user.settings != null )
{
ch.write( user.settings );
}
synchronized ( user.getSwitchMutex() )
{
if ( user.getServer() == null )
{
BungeeCord.getInstance().connections.put( user.getName(), user );
bungee.getTabListHandler().onConnect( user );
// Once again, first connection
user.clientEntityId = login.entityId;
user.serverEntityId = login.entityId;
// Set tab list size
Packet1Login modLogin = new Packet1Login(
login.entityId,
login.levelType,
login.gameMode,
(byte) login.dimension,
login.difficulty,
login.unused,
(byte) user.getPendingConnection().getListener().getTabListSize() );
user.ch.write( modLogin );
ch.write( BungeeCord.getInstance().registerChannels() );
TexturePackInfo texture = user.getPendingConnection().getListener().getTexturePack();
if ( texture != null )
{
ch.write( new PacketFAPluginMessage( "MC|TPack", ( texture.getUrl() + "\00" + texture.getSize() ).getBytes() ) );
}
} else
{
bungee.getTabListHandler().onServerChange( user );
if ( user.serverSentScoreboard != null )
{
for ( Objective objective : user.serverSentScoreboard.getObjectives() )
{
user.ch.write( new PacketCEScoreboardObjective( objective.getName(), objective.getValue(), (byte) 1 ) );
}
for ( Team team : user.serverSentScoreboard.getTeams() )
{
user.ch.write( PacketD1Team.destroy( team.getName() ) );
}
user.serverSentScoreboard = null;
}
user.sendPacket( Packet9Respawn.DIM1_SWITCH );
user.sendPacket( Packet9Respawn.DIM2_SWITCH );
user.serverEntityId = login.entityId;
user.ch.write( new Packet9Respawn( login.dimension, login.difficulty, login.gameMode, (short) 256, login.levelType ) );
// Remove from old servers
user.getServer().setObsolete( true );
user.getServer().disconnect( "Quitting" );
}
// TODO: Fix this?
if ( !user.ch.isActive() )
{
server.disconnect( "Quitting" );
throw new IllegalStateException( "No client connected for pending server!" );
}
// Add to new server
// TODO: Move this to the connected() method of DownstreamBridge
target.addPlayer( user );
user.setServer( server );
ch.pipeline().get( HandlerBoss.class ).setHandler( new DownstreamBridge( bungee, user, server ) );
}
thisState = State.FINISHED;
throw new CancelSendSignal();
}
@Override
public void handle(PacketFDEncryptionRequest encryptRequest) throws Exception
{
Preconditions.checkState( thisState == State.ENCRYPT_REQUEST, "Not expecting ENCRYPT_REQUEST" );
thisState = State.LOGIN;
}
@Override
public void handle(PacketFFKick kick) throws Exception
{
ServerInfo def = bungee.getServerInfo( user.getPendingConnection().getListener().getDefaultServer() );
if ( target == def )
{
def = null;
}
ServerKickEvent event = bungee.getPluginManager().callEvent( new ServerKickEvent( user, kick.message, def ) );
if ( event.isCancelled() && event.getCancelServer() != null )
{
user.connect( event.getCancelServer() );
return;
}
String message = ChatColor.RED + "Kicked whilst connecting to " + target.getName() + ": " + kick.message;
if ( user.getServer() == null )
{
user.disconnect( message );
} else
{
user.sendMessage( message );
}
}
@Override
public String toString()
{
return "[" + user.getName() + "] <-> ServerConnector [" + target.getName() + "]";
}
}
|
package org.zstack.test.mevoco;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.allocator.HostCapacityOverProvisioningManager;
import org.zstack.header.configuration.DiskOfferingInventory;
import org.zstack.header.configuration.InstanceOfferingInventory;
import org.zstack.header.console.APIRequestConsoleAccessMsg;
import org.zstack.header.host.HostInventory;
import org.zstack.header.host.HostVO;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.network.l2.L2NetworkInventory;
import org.zstack.header.network.l3.IpRangeInventory;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.network.l3.UsedIpVO;
import org.zstack.header.storage.primary.ImageCacheVO;
import org.zstack.header.storage.primary.PrimaryStorageInventory;
import org.zstack.header.storage.primary.PrimaryStorageOverProvisioningManager;
import org.zstack.header.storage.primary.PrimaryStorageVO;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmNicInventory;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.kvm.KVMAgentCommands.AttachDataVolumeCmd;
import org.zstack.kvm.KVMAgentCommands.StartVmCmd;
import org.zstack.kvm.KVMSystemTags;
import org.zstack.mevoco.KVMAddOns.NicQos;
import org.zstack.mevoco.KVMAddOns.VolumeQos;
import org.zstack.mevoco.MevocoConstants;
import org.zstack.mevoco.MevocoSystemTags;
import org.zstack.network.service.flat.FlatDhcpBackend.ApplyDhcpCmd;
import org.zstack.network.service.flat.FlatDhcpBackend.DhcpInfo;
import org.zstack.network.service.flat.FlatDhcpBackend.PrepareDhcpCmd;
import org.zstack.network.service.flat.FlatNetworkServiceSimulatorConfig;
import org.zstack.network.service.flat.FlatNetworkSystemTags;
import org.zstack.core.db.SimpleQuery;
import org.zstack.header.allocator.HostCapacityOverProvisioningManager;
import org.zstack.header.identity.*;
import org.zstack.header.query.QueryOp;
import org.zstack.header.storage.primary.PrimaryStorageOverProvisioningManager;
import org.zstack.network.service.flat.FlatNetworkServiceSimulatorConfig;
import org.zstack.simulator.kvm.KVMSimulatorConfig;
import org.zstack.storage.primary.local.LocalStorageSimulatorConfig;
import org.zstack.storage.primary.local.LocalStorageSimulatorConfig.Capacity;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.test.identity.IdentityCreator;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.data.SizeUnit;
import org.zstack.utils.function.Function;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import org.zstack.utils.network.NetworkUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.zstack.core.Platform._;
import static org.zstack.utils.CollectionDSL.list;
/**
* test predefined policies
*/
public class TestMevoco21 {
CLogger logger = Utils.getLogger(TestMevoco21.class);
Deployer deployer;
Api api;
ComponentLoader loader;
CloudBus bus;
DatabaseFacade dbf;
SessionInventory session;
LocalStorageSimulatorConfig config;
FlatNetworkServiceSimulatorConfig fconfig;
KVMSimulatorConfig kconfig;
PrimaryStorageOverProvisioningManager psRatioMgr;
HostCapacityOverProvisioningManager hostRatioMgr;
long totalSize = SizeUnit.GIGABYTE.toByte(100);
@Before
public void setUp() throws Exception {
DBUtil.reDeployDB();
WebBeanConstructor con = new WebBeanConstructor();
deployer = new Deployer("deployerXml/mevoco/TestMevoco.xml", con);
deployer.addSpringConfig("mevocoRelated.xml");
deployer.load();
loader = deployer.getComponentLoader();
bus = loader.getComponent(CloudBus.class);
dbf = loader.getComponent(DatabaseFacade.class);
config = loader.getComponent(LocalStorageSimulatorConfig.class);
fconfig = loader.getComponent(FlatNetworkServiceSimulatorConfig.class);
kconfig = loader.getComponent(KVMSimulatorConfig.class);
psRatioMgr = loader.getComponent(PrimaryStorageOverProvisioningManager.class);
hostRatioMgr = loader.getComponent(HostCapacityOverProvisioningManager.class);
Capacity c = new Capacity();
c.total = totalSize;
c.avail = totalSize;
config.capacityMap.put("host1", c);
deployer.build();
api = deployer.getApi();
session = api.loginAsAdmin();
}
private void validate(List<PolicyVO> ps, String policyName, String statementAction, AccountConstant.StatementEffect effect) {
for (PolicyVO vo : ps) {
if (vo.getName().equals(policyName)) {
List<PolicyInventory.Statement> ss = JSONObjectUtil.toCollection(vo.getData(), ArrayList.class, PolicyInventory.Statement.class);
for (PolicyInventory.Statement s : ss) {
for (String action : s.getActions()) {
if (action.equals(statementAction) && effect == s.getEffect()) {
return;
}
}
}
}
}
Assert.fail(String.format("cannot find policy[name: %s, action: %s, effect: %s\n\n %s", policyName, statementAction,
effect, JSONObjectUtil.toJsonString(PolicyInventory.valueOf(ps))));
}
/*
private void validate(List<PolicyVO> ps, String policyName, List<String> statementActions, AccountConstant.StatementEffect effect) {
for (PolicyVO vo : ps) {
if (vo.getName().equals(policyName)) {
List<PolicyInventory.Statement> ss = JSONObjectUtil.toCollection(vo.getData(), ArrayList.class, PolicyInventory.Statement.class);
for (PolicyInventory.Statement s : ss) {
if (s.getActions().containsAll(statementActions) && effect == s.getEffect()) {
return;
}
}
}
}
Assert.fail(String.format("cannot find policy[name: %s, action: %s, effect: %s\n\n %s", policyName, statementActions,
effect, JSONObjectUtil.toJsonString(PolicyInventory.valueOf(ps))));
}
*/
@Test
public void test() throws ApiSenderException {
IdentityCreator creator = new IdentityCreator(api);
AccountInventory test = creator.createAccount("test", "test");
SimpleQuery<PolicyVO> q = dbf.createQuery(PolicyVO.class);
q.add(PolicyVO_.accountUuid, SimpleQuery.Op.EQ, test.getUuid());
List<PolicyVO> ps = q.list();
validate(ps, "VM.CREATE", "instance:APICreateVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.UPDATE", "instance:APIUpdateVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.START", "instance:APIStartVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.STOP", "instance:APIStopVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.REBOOT", "instance:APIRebootVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.DESTROY", "instance:APIDestroyVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.RECOVER", "instance:APIRecoverVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.EXPUNGE", "instance:APIExpungeVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.CONSOLE", "console:APIRequestConsoleAccessMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.ISO.ADD", "instance:APIAttachIsoToVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.ISO.REMOVE", "instance:APIDetachIsoFromVmInstanceMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.MIGRATE", "instance:APIMigrateVmMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.L3.ATTACH", "instance:APIAttachL3NetworkToVmMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.L3.DETACH", "instance:APIDetachL3NetworkFromVmMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VM.INSTANCE-OFFERING.CHANGE", "instance:APIChangeInstanceOfferingMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.CREATE", "volume:APICreateDataVolumeMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.UPDATE", "volume:APIUpdateVolumeMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.ATTACH", "volume:APIAttachDataVolumeToVmMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.DETACH", "volume:APIDetachDataVolumeFromVmMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.CHANGE-STATE", "volume:APIChangeVolumeStateMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.DELETE", "volume:APIDeleteDataVolumeMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.EXPUNGE", "volume:APIExpungeDataVolumeMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.SNAPSHOT.CREATE", "volumeSnapshot:APICreateVolumeSnapshotMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.SNAPSHOT.UPDATE", "volumeSnapshot:APIUpdateVolumeSnapshotMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.SNAPSHOT.DELETE", "volumeSnapshot:APIDeleteVolumeSnapshotMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "VOLUME.SNAPSHOT.REVERT", "volumeSnapshot:APIRevertVolumeFromSnapshotMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.CREATE", "securityGroup:APICreateSecurityGroupMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.UPDATE", "securityGroup:APIUpdateSecurityGroupMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.CHANGE-STATE", "securityGroup:APIChangeSecurityGroupStateMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.DELETE", "securityGroup:APIDeleteSecurityGroupMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.ADD-NIC", "securityGroup:APIAddVmNicToSecurityGroupMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.REMOVE-NIC", "securityGroup:APIDeleteVmNicFromSecurityGroupMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.ADD-RULE", "securityGroup:APIAddSecurityGroupRuleMsg", AccountConstant.StatementEffect.Allow);
validate(ps, "SECURITY-GROUP.REMOVE-RULE", "securityGroup:APIDeleteSecurityGroupRuleMsg", AccountConstant.StatementEffect.Allow);
APIQueryPolicyMsg qmsg = new APIQueryPolicyMsg();
qmsg.addQueryCondition("accountUuid", QueryOp.EQ, test.getUuid());
APIQueryPolicyReply r = api.query(qmsg, APIQueryPolicyReply.class, creator.getAccountSession());
Assert.assertFalse(r.getInventories().isEmpty());
UserInventory user = creator.createUser("user", "password");
qmsg = new APIQueryPolicyMsg();
qmsg.addQueryCondition("user.uuid", QueryOp.EQ, user.getUuid());
qmsg.addQueryCondition("name", QueryOp.EQ, "DEFAULT-READ");
r = api.query(qmsg, APIQueryPolicyReply.class, creator.getAccountSession());
Assert.assertEquals(1, r.getInventories().size());
PolicyVO consolePolicy = CollectionUtils.find(ps, new Function<PolicyVO, PolicyVO>() {
@Override
public PolicyVO call(PolicyVO arg) {
return "VM.CONSOLE".equals(arg.getName()) ? arg : null;
}
});
Assert.assertNotNull(consolePolicy);
api.attachPolicesToUser(user.getUuid(), list(consolePolicy.getUuid()), creator.getAccountSession());
Map<String, String> pret = api.checkUserPolicy(list(APIRequestConsoleAccessMsg.class.getName()), user.getUuid(), creator.getAccountSession());
Assert.assertEquals(1, pret.size());
String decision = pret.get(APIRequestConsoleAccessMsg.class.getName());
Assert.assertEquals("Allow", decision);
}
}
|
package net.ossrs.yasea;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.widget.Toast;
import com.seu.magicfilter.base.MagicCameraInputFilter;
import com.seu.magicfilter.base.gpuimage.GPUImageFilter;
import com.seu.magicfilter.utils.MagicFilterFactory;
import com.seu.magicfilter.utils.MagicFilterType;
import com.seu.magicfilter.utils.OpenGlUtils;
import com.seu.magicfilter.utils.Rotation;
import com.seu.magicfilter.utils.TextureRotationUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class SrsCameraView extends GLSurfaceView implements GLSurfaceView.Renderer, Camera.PreviewCallback {
private GPUImageFilter filter;
private MagicCameraInputFilter cameraInputFilter;
private SurfaceTexture surfaceTexture;
private int textureId = OpenGlUtils.NO_TEXTURE;
private final FloatBuffer gLCubeBuffer;
private final FloatBuffer gLTextureBuffer;
private int surfaceWidth, surfaceHeight;
private int previewWidth, previewHeight;
private Camera mCamera;
private IntBuffer mGLPreviewIntBuffer;
private ByteBuffer mGLPreviewByteBuffer;
private byte[] mYuvPreviewBuffer;
private int mCamId = Camera.CameraInfo.CAMERA_FACING_FRONT;
private int mPreviewRotation = 90;
private Thread worker;
private final Object writeLock = new Object();
private ConcurrentLinkedQueue<IntBuffer> mGLIntBufferCache = new ConcurrentLinkedQueue<>();
private PreviewCallback mPrevCb;
public SrsCameraView(Context context) {
this(context, null);
}
public SrsCameraView(Context context, AttributeSet attrs) {
super(context, attrs);
gLCubeBuffer = ByteBuffer.allocateDirect(TextureRotationUtil.CUBE.length * 4)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
gLCubeBuffer.put(TextureRotationUtil.CUBE).position(0);
gLTextureBuffer = ByteBuffer.allocateDirect(TextureRotationUtil.TEXTURE_NO_ROTATION.length * 4)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
gLTextureBuffer.put(TextureRotationUtil.getRotation(Rotation.NORMAL, false, true)).position(0);
setEGLContextClientVersion(2);
setRenderer(this);
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
MagicFilterFactory.initContext(context.getApplicationContext());
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glDisable(GL10.GL_DITHER);
GLES20.glClearColor(0, 0, 0, 0);
cameraInputFilter = new MagicCameraInputFilter();
cameraInputFilter.init();
cameraInputFilter.initCameraFrameBuffer(previewWidth, previewHeight);
cameraInputFilter.onInputSizeChanged(previewWidth, previewHeight);
textureId = OpenGlUtils.getExternalOESTextureID();
surfaceTexture = new SurfaceTexture(textureId);
surfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {
@Override
public void onFrameAvailable(SurfaceTexture surfaceTexture) {
requestRender();
}
});
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glViewport(0,0,width, height);
surfaceWidth = width;
surfaceHeight = height;
cameraInputFilter.onDisplaySizeChanged(surfaceWidth, surfaceHeight);
}
@Override
public void onDrawFrame(GL10 gl) {
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
surfaceTexture.updateTexImage();
float[] mtx = new float[16];
surfaceTexture.getTransformMatrix(mtx);
cameraInputFilter.setTextureTransformMatrix(mtx);
if (filter == null) {
cameraInputFilter.onDrawFrame(textureId, gLCubeBuffer, gLTextureBuffer);
} else {
int fboTextureId = cameraInputFilter.onDrawToTexture(textureId);
// Read under off-screen FBO mode
GLES20.glReadPixels(0, 0, previewWidth, previewHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, mGLPreviewIntBuffer);
// Recover to window-specific FBO
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
filter.onDrawFrame(fboTextureId, gLCubeBuffer, gLTextureBuffer);
mGLIntBufferCache.add(mGLPreviewIntBuffer);
synchronized (writeLock) {
writeLock.notifyAll();
}
}
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
mPrevCb.onGetYuvFrame(data);
camera.addCallbackBuffer(mYuvPreviewBuffer);
}
public void setPreviewCallback(PreviewCallback cb) {
mPrevCb = cb;
}
public void setPreviewResolution(int width, int height) {
previewWidth = width;
previewHeight = height;
}
public void setFilter(final MagicFilterType type) {
queueEvent(new Runnable() {
@Override
public void run() {
if (filter != null) {
filter.destroy();
}
filter = MagicFilterFactory.initFilters(type);
if (filter != null) {
filter.init();
filter.onDisplaySizeChanged(surfaceWidth, surfaceHeight);
filter.onInputSizeChanged(previewWidth, previewHeight);
mCamera.setPreviewCallback(null);
}
}
});
requestRender();
}
private void deleteTextures() {
if(textureId != OpenGlUtils.NO_TEXTURE){
queueEvent(new Runnable() {
@Override
public void run() {
GLES20.glDeleteTextures(1, new int[]{ textureId }, 0);
textureId = OpenGlUtils.NO_TEXTURE;
}
});
}
}
public void setPreviewRotation(int rotation) {
mPreviewRotation = rotation;
}
public void setCameraId(int id) {
mCamId = id;
}
public int getCameraId() {
return mCamId;
}
public boolean startCamera() {
if (mCamera != null) {
return false;
}
if (mCamId > (Camera.getNumberOfCameras() - 1) || mCamId < 0) {
return false;
}
worker = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
while (!mGLIntBufferCache.isEmpty()) {
IntBuffer picture = mGLIntBufferCache.poll();
mGLPreviewByteBuffer.asIntBuffer().put(picture.array());
mPrevCb.onGetRgbaFrame(mGLPreviewByteBuffer.array(), previewWidth, previewHeight);
}
// Waiting for next frame
synchronized (writeLock) {
try {
// isEmpty() may take some time, so we set timeout to detect next frame
writeLock.wait(500);
} catch (InterruptedException ie) {
worker.interrupt();
}
}
}
}
});
worker.start();
mCamera = Camera.open(mCamId);
Camera.Parameters params = mCamera.getParameters();
Camera.Size size = mCamera.new Size(previewWidth, previewHeight);
if (!params.getSupportedPreviewSizes().contains(size) || !params.getSupportedPictureSizes().contains(size)) {
Toast.makeText(getContext(), String.format("Unsupported resolution %dx%d", size.width, size.height), Toast.LENGTH_SHORT).show();
stopCamera();
return false;
}
if (params.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
mYuvPreviewBuffer = new byte[previewWidth * previewHeight * 3 / 2];
mGLPreviewIntBuffer = IntBuffer.allocate(previewWidth * previewHeight);
mGLPreviewByteBuffer = ByteBuffer.allocate(previewWidth * previewHeight * 4);
//params.set("orientation", "portrait");
//params.set("orientation", "landscape");
//params.setRotation(90);
params.setPictureSize(previewWidth, previewHeight);
params.setPreviewSize(previewWidth, previewHeight);
int[] range = findClosestFpsRange(SrsEncoder.VFPS, params.getSupportedPreviewFpsRange());
params.setPreviewFpsRange(range[0], range[1]);
params.setPreviewFormat(ImageFormat.NV21);
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
params.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
if (!params.getSupportedFocusModes().isEmpty()) {
params.setFocusMode(params.getSupportedFocusModes().get(0));
}
mCamera.setParameters(params);
mCamera.setDisplayOrientation(mPreviewRotation);
if (filter == null) {
mCamera.addCallbackBuffer(mYuvPreviewBuffer);
mCamera.setPreviewCallbackWithBuffer(this);
} else {
mCamera.setPreviewCallback(null);
}
try {
mCamera.setPreviewTexture(surfaceTexture);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
return true;
}
public void stopCamera() {
if (worker != null) {
worker.interrupt();
try {
worker.join();
} catch (InterruptedException e) {
e.printStackTrace();
worker.interrupt();
}
mGLIntBufferCache.clear();
worker = null;
}
if (mCamera != null) {
// need to SET NULL CB before stop preview!!!
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
private int[] findClosestFpsRange(int expectedFps, List<int[]> fpsRanges) {
expectedFps *= 1000;
int[] closestRange = fpsRanges.get(0);
int measure = Math.abs(closestRange[0] - expectedFps) + Math.abs(closestRange[1] - expectedFps);
for (int[] range : fpsRanges) {
if (range[0] <= expectedFps && range[1] >= expectedFps) {
int curMeasure = Math.abs(range[0] - expectedFps) + Math.abs(range[1] - expectedFps);
if (curMeasure < measure) {
closestRange = range;
measure = curMeasure;
}
}
}
return closestRange;
}
public interface PreviewCallback {
void onGetYuvFrame(byte[] data);
void onGetRgbaFrame(byte[] data, int width, int height);
}
}
|
package odoo.controls;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.odoo.core.orm.ODataRow;
import com.odoo.core.orm.OM2ORecord;
import com.odoo.core.orm.OModel;
import com.odoo.core.orm.fields.OColumn;
import com.odoo.core.orm.fields.types.OSelection;
import com.odoo.core.utils.OControls;
import java.util.ArrayList;
import java.util.List;
public class OSelectionField extends LinearLayout implements IOControlData,
AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener, RadioGroup.OnCheckedChangeListener {
public static final String TAG = OSelectionField.class.getSimpleName();
private Context mContext;
private Object mValue = null;
private Boolean mEditable = false;
private OField.WidgetType mWidget = null;
private Integer mResourceArray = null;
private OColumn mCol;
private String mLabel;
private OModel mModel;
private List<ODataRow> items = new ArrayList<>();
private ValueUpdateListener mValueUpdateListener = null;
// Controls
private Spinner mSpinner = null;
private SpinnerAdapter mAdapter;
private RadioGroup mRadioGroup = null;
private TextView txvView = null;
private Boolean mReady = false;
private float textSize = -1;
private int appearance = -1;
private int textColor = Color.BLACK;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public OSelectionField(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
public OSelectionField(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr, 0);
}
public OSelectionField(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0, 0);
}
public OSelectionField(Context context) {
super(context);
init(context, null, 0, 0);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
mContext = context;
if (attrs != null) {
}
if (mContext.getClass().getSimpleName().contains("BridgeContext"))
initControl();
}
private void createRadioGroup() {
final LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
if (mRadioGroup == null) {
mRadioGroup = new RadioGroup(mContext);
mRadioGroup.setLayoutParams(params);
} else {
removeView(mRadioGroup);
}
mRadioGroup.removeAllViews();
mRadioGroup.setOnCheckedChangeListener(this);
for (ODataRow label : items) {
RadioButton rdoBtn = new RadioButton(mContext);
rdoBtn.setLayoutParams(params);
rdoBtn.setText(label.getString(mModel.getDefaultNameColumn()));
if (textSize > -1) {
rdoBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
if (appearance > -1) {
rdoBtn.setTextAppearance(mContext, appearance);
}
rdoBtn.setTextColor(textColor);
mRadioGroup.addView(rdoBtn);
}
addView(mRadioGroup);
}
@Override
public void initControl() {
final LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
removeAllViews();
setOrientation(VERTICAL);
createItems();
if (isEditable()) {
if (mWidget != null) {
switch (mWidget) {
case RadioGroup:
createRadioGroup();
return;
case SelectionDialog:
txvView = new TextView(mContext);
txvView.setLayoutParams(params);
mAdapter = new SpinnerAdapter(mContext,
android.R.layout.simple_list_item_1, items);
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog dialog = createSelectionDialog(
getPos(), items, params);
txvView.setTag(dialog);
dialog.show();
}
});
if (textSize > -1) {
txvView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
if (appearance > -1) {
txvView.setTextAppearance(mContext, appearance);
}
txvView.setTextColor(textColor);
addView(txvView);
return;
case Searchable:
case SearchableLive:
txvView = new TextView(mContext);
txvView.setLayoutParams(params);
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext,
SearchableItemActivity.class);
intent.putExtra("resource_id", mResourceArray);
intent.putExtra("selected_position", getPos());
intent.putExtra(OColumn.ROW_ID, getPos());
intent.putExtra("search_hint", getLabel());
if (mCol != null) {
intent.putExtra("column_name", mCol.getName());
}
/*
* FIXME: What about filter domain. Pass detail for
* filter domain
*/
intent.putExtra("model", mModel.getModelName());
intent.putExtra("live_search",
(mWidget == OField.WidgetType.SearchableLive));
try {
mContext.unregisterReceiver(valueReceiver);
} catch (Exception e) {
}
mContext.registerReceiver(valueReceiver,
new IntentFilter("searchable_value_select"));
mContext.startActivity(intent);
}
});
if (textSize > -1) {
txvView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
if (appearance > -1) {
txvView.setTextAppearance(mContext, appearance);
}
txvView.setTextColor(textColor);
addView(txvView);
return;
default:
break;
}
}
// Default View
mSpinner = new Spinner(mContext);
mSpinner.setLayoutParams(params);
mAdapter = new SpinnerAdapter(mContext,
android.R.layout.simple_list_item_1, items);
mSpinner.setAdapter(mAdapter);
mSpinner.setOnItemSelectedListener(this);
addView(mSpinner);
} else {
setOnClickListener(null);
txvView = new TextView(mContext);
if (textSize > -1) {
txvView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
if (appearance > -1) {
txvView.setTextAppearance(mContext, appearance);
}
txvView.setTextColor(textColor);
addView(txvView);
}
}
private void createItems() {
items.clear();
if (!mContext.getClass().getSimpleName().contains("BridgeContext")) {
if (mResourceArray != null && mResourceArray != -1) {
String[] items_list = mContext.getResources().getStringArray(
mResourceArray);
ODataRow row = new ODataRow();
row.put(OColumn.ROW_ID, -1);
row.put(mModel.getDefaultNameColumn(), "Nothing Selected");
items.add(row);
for (int i = 0; i < items_list.length; i++) {
row = new ODataRow();
row.put(OColumn.ROW_ID, i);
row.put(mModel.getDefaultNameColumn(), items_list[i]);
items.add(row);
}
} else if (mCol.getType().isAssignableFrom(OSelection.class)) {
List<ODataRow> rows = new ArrayList<>();
Object defaultVal = mCol.getDefaultValue();
for (String key : mCol.getSelectionMap().keySet()) {
String val = mCol.getSelectionMap().get(key);
ODataRow row = new ODataRow();
row.put("key", key);
row.put("name", val);
if (defaultVal != null && defaultVal.toString().equals(val)) {
rows.add(0, row);
} else {
rows.add(row);
}
}
items.addAll(rows);
} else {
items.addAll(getRecordItems(mModel, mCol));
}
}
}
private int getPos() {
if (mResourceArray != -1 && mValue != null) {
return Integer.parseInt(mValue.toString());
} else if (mCol.getType().isAssignableFrom(OSelection.class)) {
if (items.size() <= 0) {
createItems();
}
for (ODataRow item : items) {
int index = items.indexOf(item);
if (item.getString("key").equals(mValue.toString())) {
return index;
}
}
} else {
ODataRow rec = getValueForM2O();
if (rec != null) {
return rec.getInt(OColumn.ROW_ID);
}
}
return -1;
}
@Override
public void setValue(Object value) {
mValue = value;
if (mValue == null || mValue.toString().equals("false")) {
mValue = -1;
}
ODataRow row = new ODataRow();
if (isEditable()) {
if (mWidget != null) {
switch (mWidget) {
case RadioGroup:
if (mResourceArray != -1) {
((RadioButton) mRadioGroup.getChildAt(getPos()))
.setChecked(true);
row = items.get(getPos());
} else {
Integer row_id = null;
if (mValue instanceof OM2ORecord) {
row = ((OM2ORecord) mValue).browse();
row_id = row.getInt(OColumn.ROW_ID);
} else
row_id = (Integer) mValue;
int index = 0;
for (int i = 0; i < items.size(); i++) {
if (items.get(i).getInt(OColumn.ROW_ID) == row_id) {
index = i;
break;
}
}
row = items.get(index);
((RadioButton) mRadioGroup.getChildAt(index))
.setChecked(true);
}
break;
case Searchable:
case SearchableLive:
case SelectionDialog:
if (mResourceArray != -1) {
row = items.get(getPos());
} else {
if (mValue instanceof OM2ORecord)
row = ((OM2ORecord) mValue).browse();
else if (mValue instanceof Integer)
row = getRecordData((Integer) mValue);
}
txvView.setText(row.getString(mModel.getDefaultNameColumn()));
if (txvView.getTag() != null) {
AlertDialog dialog = (AlertDialog) txvView.getTag();
dialog.dismiss();
}
break;
default:
break;
}
} else {
if (mResourceArray != -1) {
mSpinner.setSelection(getPos());
row = items.get(getPos());
} else if (mCol.getType().isAssignableFrom(OSelection.class)) {
int pos = getPos();
mSpinner.setSelection(pos);
} else {
Integer row_id = null;
if (mValue instanceof OM2ORecord) {
row = ((OM2ORecord) mValue).browse();
row_id = row.getInt(OColumn.ROW_ID);
} else if (mValue instanceof Integer)
row_id = (Integer) mValue;
int index = 0;
for (int i = 0; i < items.size(); i++) {
if (items.get(i).getInt(OColumn.ROW_ID) == row_id) {
index = i;
break;
}
}
row = items.get(index);
mSpinner.setSelection(index);
}
}
} else {
if (mResourceArray != -1 || mCol.getType().isAssignableFrom(OSelection.class)) {
int position = getPos();
// Ignoring if default value not set for field.
if (position != -1)
row = items.get(position);
} else {
if (mValue instanceof OM2ORecord) {
row = ((OM2ORecord) mValue).browse();
if (row == null) {
row = new ODataRow();
}
} else {
if (!(mValue instanceof Boolean) && mValue != null && !mValue.toString().equals("false")) {
int row_id = (Integer) mValue;
row = getRecordData(row_id);
} else {
row = new ODataRow();
row.put(mModel.getDefaultNameColumn(), "No " + mCol.getLabel() + " selected");
}
}
}
if (!row.getString(mModel.getDefaultNameColumn()).equals("false"))
txvView.setText(row.getString(mModel.getDefaultNameColumn()));
}
if (isEditable() && mValueUpdateListener != null && (mValue instanceof Integer &&
(int) mValue != -1)) {
mValueUpdateListener.onValueUpdate(row);
}
}
@Override
public View getFieldView() {
return null;
}
@Override
public void setError(String error) {
if (error != null)
Toast.makeText(mContext, error, Toast.LENGTH_LONG).show();
}
private ODataRow getValueForM2O() {
if (getValue() != null) {
if (getValue() instanceof OM2ORecord)
return ((OM2ORecord) getValue()).browse();
else if (getValue() instanceof Integer)
return getRecordData((Integer) getValue());
}
return null;
}
@Override
public Object getValue() {
if (mValue instanceof OM2ORecord) {
return ((OM2ORecord) mValue).getId();
}
return mValue;
}
@Override
public void setEditable(Boolean editable) {
mEditable = editable;
initControl();
}
@Override
public Boolean isEditable() {
return mEditable;
}
public void setWidgetType(OField.WidgetType type) {
mWidget = type;
initControl();
}
public void setArrayResourceId(int res_id) {
mResourceArray = res_id;
}
public void setColumn(OColumn col) {
mCol = col;
if (mCol != null && mLabel == null) {
mLabel = mCol.getLabel();
}
}
private ODataRow getRecordData(int row_id) {
ODataRow row;
if (row_id > 0) {
OModel rel_model = mModel.createInstance(mCol.getType());
row = rel_model.browse(row_id);
} else {
row = items.get(0);
}
return row;
}
private class SpinnerAdapter extends ArrayAdapter<ODataRow> {
public SpinnerAdapter(Context context, int resource,
List<ODataRow> objects) {
super(context, resource, objects);
}
public View getView(int position, View convertView, ViewGroup parent) {
return generateView(position, convertView, parent);
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return generateView(position, convertView, parent);
}
private View generateView(int position, View convertView,
ViewGroup parent) {
View v = convertView;
if (v == null)
v = LayoutInflater.from(mContext).inflate(
android.R.layout.simple_list_item_1, parent, false);
ODataRow row = getItem(position);
OControls.setText(v, android.R.id.text1, row.getString(mModel.getDefaultNameColumn()));
return v;
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
if (mResourceArray != -1) {
mValue = position;
} else if (mCol.getType().isAssignableFrom(OSelection.class)) {
ODataRow row = mAdapter.getItem(position);
mValue = row.getString("key");
} else {
mValue = items.get(position).get(OColumn.ROW_ID);
}
setValue(mValue);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
mValue = null;
}
@Override
public void setLabelText(String label) {
mLabel = label;
}
@Override
public String getLabel() {
if (mLabel != null)
return mLabel;
if (mCol != null)
return mCol.getLabel();
return "unknown";
}
private AlertDialog createSelectionDialog(final int selected_position,
final List<ODataRow> items, LayoutParams params) {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
ListView dialogView = new ListView(mContext);
dialogView.setAdapter(mAdapter);
dialogView.setOnItemClickListener(this);
dialogView.setLayoutParams(params);
builder.setView(dialogView);
return builder.create();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
setValue(position);
}
BroadcastReceiver valueReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
setValue(intent.getIntExtra("selected_position", -1));
mContext.unregisterReceiver(valueReceiver);
}
};
public void setModel(OModel model) {
mModel = model;
}
public static List<ODataRow> getRecordItems(OModel model, OColumn column) {
List<ODataRow> items = new ArrayList<ODataRow>();
OModel rel_model = model.createInstance(column.getType());
StringBuffer whr = new StringBuffer();
List<Object> args_list = new ArrayList<Object>();
// Skipping onchange domain filter
if (!column.hasDomainFilterColumn()) {
for (String key : column.getDomains().keySet()) {
OColumn.ColumnDomain domain = column.getDomains().get(key);
if (domain.getConditionalOperator() != null) {
whr.append(domain.getConditionalOperator());
} else {
whr.append(" ");
whr.append(domain.getColumn());
whr.append(" ");
whr.append(domain.getOperator());
whr.append(" ? ");
args_list.add(domain.getValue().toString());
}
}
}
String where = null;
String[] args = null;
if (args_list.size() > 0) {
where = whr.toString();
args = args_list.toArray(new String[args_list.size()]);
}
List<ODataRow> rows = new ArrayList<>();
rows = rel_model.select(new String[]{rel_model.getDefaultNameColumn()}, where,
args, rel_model.getDefaultNameColumn());
ODataRow row = new ODataRow();
row.put(OColumn.ROW_ID, -1);
row.put(rel_model.getDefaultNameColumn(), "No " + column.getLabel() + " selected");
items.add(row);
items.addAll(rows);
return items;
}
@Override
public void setValueUpdateListener(ValueUpdateListener listener) {
mValueUpdateListener = listener;
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int index = mRadioGroup.indexOfChild(group.findViewById(checkedId));
ODataRow row = items.get(index);
setValue(row.getInt(OColumn.ROW_ID));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mReady = true;
}
@Override
public Boolean isControlReady() {
return mReady;
}
@Override
public void resetData() {
if (isEditable()) {
if (mWidget == null) {
if (mAdapter != null) {
createItems();
mAdapter.notifyDataSetChanged();
}
} else {
switch (mWidget) {
case SelectionDialog:
createItems();
break;
case RadioGroup:
createItems();
createRadioGroup();
break;
case Searchable:
case SearchableLive:
break;
default:
break;
}
}
}
}
public void setResource(float textSize, int appearance, int color) {
this.textSize = textSize;
this.appearance = appearance;
this.textColor = color;
}
}
|
package progen.roles.distributed;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import progen.context.ProGenContext;
import progen.roles.Dispatcher;
import progen.roles.standalone.ClientLocal;
/**
* @author jirsis
*
*/
public class ClientDistributed extends ClientLocal {
private static final int DISPATCHER_ADDRESS_DEFAULT_SIZE = 32;
public ClientDistributed() {
super();
}
@Override
public Dispatcher initDispatcher() {
DispatcherDistributed dispatcher = null;
try {
final DispatcherRemote remote = (DispatcherRemote) Naming.lookup(getDispatcherAddress());
dispatcher = new DispatcherDistributed(remote);
} catch (MalformedURLException e) {
throw new ProGenDistributedException(getDispatcherAddress(), e);
} catch (RemoteException e) {
throw new ProGenDistributedException(getDispatcherAddress(), e);
} catch (NotBoundException e) {
throw new ProGenDistributedException(getDispatcherAddress(), e);
}
return dispatcher;
}
private String getDispatcherAddress() {
final StringBuilder dispatcherAddress = new StringBuilder(DISPATCHER_ADDRESS_DEFAULT_SIZE);
dispatcherAddress.append("rmi:
dispatcherAddress.append(ProGenContext.getOptionalProperty("progen.role.client.dispatcher.bindAddress", "127.0.0.1"));
dispatcherAddress.append(":");
dispatcherAddress.append(ProGenContext.getOptionalProperty("progen.role.client.dispatcher.port", Registry.REGISTRY_PORT));
dispatcherAddress.append("/");
dispatcherAddress.append(ProGenContext.getOptionalProperty("progen.role.client.dispatcher.name", DispatcherDistributed.DISPATCHER_NAME));
return dispatcherAddress.toString();
}
}
|
package org.broadinstitute.sting.gatk.refdata;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.StingException;
import org.broadinstitute.sting.utils.genotype.DiploidGenotype;
import org.broadinstitute.sting.utils.genotype.Genotype;
import org.broadinstitute.sting.utils.genotype.VariantBackedByGenotype;
import org.broadinstitute.sting.utils.genotype.vcf.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
/**
* @author aaron
* <p/>
* Class RodVCF
* <p/>
* An implementation of the ROD for VCF.
*/
public class RodVCF extends BasicReferenceOrderedDatum implements VariationRod, VariantBackedByGenotype, Iterator<RodVCF> {
public VCFReader getReader() {
return mReader;
}
// our VCF related information
private VCFReader mReader;
public VCFRecord getRecord() {
return mCurrentRecord;
}
public VCFRecord mCurrentRecord;
public RodVCF(String name) {
super(name);
}
public RodVCF(String name, VCFRecord currentRecord, VCFReader reader) {
super(name);
mCurrentRecord = currentRecord;
mReader = reader;
}
public void assertNotNull() {
if ( mCurrentRecord == null ) {
throw new UnsupportedOperationException("The current Record is null");
}
}
@Override
public boolean parseLine(Object header, String[] parts) throws IOException {
throw new UnsupportedOperationException("RodVCF does not support the parseLine method");
}
public Object initialize(final File source) throws FileNotFoundException {
if ( mReader == null )
mReader = new VCFReader(source);
return mReader.getHeader();
}
@Override
public String toString() {
return (mCurrentRecord != null ? mCurrentRecord.toStringEncoding(mReader.getHeader()) : "");
}
public static RodVCF createIterator(String name, File file) {
RodVCF vcf = new RodVCF(name);
try {
vcf.initialize(file);
} catch (FileNotFoundException e) {
throw new StingException("Unable to find file " + file);
}
return vcf;
}
public boolean hasNonRefAlleleFrequency() {
assertNotNull();
return mCurrentRecord.getNonRefAlleleFrequency() > 0.0;
}
/**
* get the frequency of this variant
*
* @return VariantFrequency with the stored frequency
*/
public double getNonRefAlleleFrequency() {
assertNotNull();
return mCurrentRecord.getNonRefAlleleFrequency();
}
public boolean hasStrandBias() {
assertNotNull();
return this.mCurrentRecord.getInfoValues().containsKey(VCFRecord.STRAND_BIAS_KEY);
}
/**
* get the strand bias of this variant
*
* @return StrandBias with the stored slod
*/
public double getStrandBias() {
return hasStrandBias() ? Double.valueOf(this.mCurrentRecord.getInfoValues().get(VCFRecord.STRAND_BIAS_KEY)) : 0.0;
}
/** @return the VARIANT_TYPE of the current variant */
public VARIANT_TYPE getType() {
assertNotNull();
return mCurrentRecord.getType();
}
public String getID() {
assertNotNull();
return mCurrentRecord.getID();
}
/**
* are we a SNP? If not we're a Indel/deletion
*
* @return true if we're a SNP
*/
public boolean isSNP() {
assertNotNull();
return mCurrentRecord.isSNP();
}
/**
* are we an insertion?
*
* @return true if we are, false otherwise
*/
public boolean isInsertion() {
assertNotNull();
return mCurrentRecord.isInsertion();
}
/**
* are we an insertion?
*
* @return true if we are, false otherwise
*/
public boolean isDeletion() {
assertNotNull();
return mCurrentRecord.isDeletion();
}
@Override
public GenomeLoc getLocation() {
assertNotNull();
return mCurrentRecord.getLocation();
}
/**
* get the reference base(s) at this position
*
* @return the reference base or bases, as a string
*/
public String getReference() {
assertNotNull();
return mCurrentRecord.getReference();
}
/** are we bi-allelic? */
public boolean isBiallelic() {
assertNotNull();
return mCurrentRecord.isBiallelic();
}
/**
* get the -1 * (log 10 of the error value)
*
* @return the log based error estimate
*/
public double getNegLog10PError() {
assertNotNull();
return mCurrentRecord.getNegLog10PError();
}
public double getQual() {
assertNotNull();
return mCurrentRecord.getQual();
}
public boolean hasAlternateAllele() {
assertNotNull();
return mCurrentRecord.hasAlternateAllele();
}
/**
* gets the alternate alleles. This method should return all the alleles present at the location,
* NOT including the reference base. This is returned as a string list with no guarantee ordering
* of alleles (i.e. the first alternate allele is not always going to be the allele with the greatest
* frequency).
*
* @return an alternate allele list
*/
public List<String> getAlternateAlleleList() {
assertNotNull();
return mCurrentRecord.getAlternateAlleleList();
}
/**
* gets the alleles. This method should return all the alleles present at the location,
* including the reference base. The first allele should always be the reference allele, followed
* by an unordered list of alternate alleles.
*
* @return an alternate allele list
*/
public List<String> getAlleleList() {
assertNotNull();
return mCurrentRecord.getAlleleList();
}
/**
* are we truely a variant, given a reference
*
* @return false if we're a variant(indel, delete, SNP, etc), true if we're not
*/
public boolean isReference() {
assertNotNull();
return mCurrentRecord.isReference();
}
/**
* are we an insertion or a deletion? yes, then return true. No? Well, false then.
*
* @return true if we're an insertion or deletion
*/
public boolean isIndel() {
assertNotNull();
return mCurrentRecord.isIndel();
}
public char getAlternativeBaseForSNP() {
assertNotNull();
return mCurrentRecord.getAlternativeBaseForSNP();
}
public char getReferenceForSNP() {
assertNotNull();
return mCurrentRecord.getReferenceForSNP();
}
public boolean hasGenotypeData() {
assertNotNull();
return mCurrentRecord.hasGenotypeData();
}
/**
* get the genotype
*
* // todo -- WTF is this? This is a deeply unsafe call
*
* @return a map in lexigraphical order of the genotypes
*/
public Genotype getCalledGenotype() {
assertNotNull();
return mCurrentRecord.getCalledGenotype();
}
/**
* get the genotypes
*
* @return a list of the genotypes
*/
public List<Genotype> getGenotypes() {
assertNotNull();
return mCurrentRecord.getGenotypes();
}
/**
* get the genotypes
*
* @return a list of the genotypes
*/
public List<VCFGenotypeRecord> getVCFGenotypeRecords() {
assertNotNull();
return mCurrentRecord.getVCFGenotypeRecords();
}
/**
* Returns the genotype associated with sample, or null if the genotype is missing
*
* @param sampleName the name of the sample genotype to fetch
* @return
*/
public Genotype getGenotype(final String sampleName) {
return mCurrentRecord.getGenotype(sampleName);
}
/**
* do we have the specified genotype? not all backedByGenotypes
* have all the genotype data.
*
* @param x the genotype
*
* @return true if available, false otherwise
*/
public boolean hasGenotype(DiploidGenotype x) {
assertNotNull();
return mCurrentRecord.hasGenotype(x);
}
public String[] getSampleNames() {
assertNotNull();
return mCurrentRecord.getSampleNames();
}
// public Map<String, Genotype> getSampleGenotypes() {
// String[] samples = getSampleNames();
// List<Genotype> genotypes = getGenotypes();
// HashMap<String, Genotype> map = new HashMap<String, Genotype>();
// for ( int i = 0; i < samples.length; i++ ) {
// map.put(samples[i], genotypes.get(i));
// return map;
public Map<String, String> getInfoValues() {
assertNotNull();
return mCurrentRecord.getInfoValues();
}
public String[] getFilteringCodes() {
assertNotNull();
return mCurrentRecord.getFilteringCodes();
}
public boolean isFiltered() {
assertNotNull();
return mCurrentRecord.isFiltered();
}
// public boolean hasFilteringCodes() {
// assertNotNull();
// return mCurrentRecord.hasFilteringCodes();
public String getFilterString() {
assertNotNull();
return mCurrentRecord.getFilterString();
}
public VCFHeader getHeader() {
return mReader.getHeader();
}
public boolean hasNext() {
return mReader.hasNext();
}
/**
* @return the next element in the iteration.
* @throws NoSuchElementException - iterator has no more elements.
*/
public RodVCF next() {
if (!this.hasNext()) throw new NoSuchElementException("RodVCF next called on iterator with no more elements");
// get the next record
VCFRecord rec = mReader.next();
// make sure the next VCF record isn't before the current record (we'll accept at the same location, the
// spec doesn't indicate, and it seems like a valid use case)
GenomeLoc curPosition = null;
if (mCurrentRecord != null) curPosition = mCurrentRecord.getLocation();
if (curPosition != null && rec != null && curPosition.compareTo(rec.getLocation()) > 0)
throw new StingException("The next VCF record appears to be before the current (current location => " + curPosition.toString() +
", the next record position => " + rec.getLocation().toString() + " with line : " + rec.toStringEncoding(mReader.getHeader()) + "). " +
"Check to make sure the input VCF file is correctly sorted.");
// save off the previous record. This is needed given how iterators are used in the ROD system;
// we need to save off the last record
mCurrentRecord = rec;
return new RodVCF(name, rec, mReader);
}
public void remove() {
throw new UnsupportedOperationException("The remove operation is not supported for a VCF rod");
}
}
|
package com.semmle.js.extractor;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.semmle.extractor.html.HtmlPopulator;
import com.semmle.js.extractor.ExtractorConfig.Platform;
import com.semmle.js.extractor.ExtractorConfig.SourceType;
import com.semmle.js.extractor.FileExtractor.FileType;
import com.semmle.js.extractor.trapcache.DefaultTrapCache;
import com.semmle.js.extractor.trapcache.DummyTrapCache;
import com.semmle.js.extractor.trapcache.ITrapCache;
import com.semmle.js.parser.ParsedProject;
import com.semmle.ts.extractor.TypeExtractor;
import com.semmle.ts.extractor.TypeScriptParser;
import com.semmle.ts.extractor.TypeTable;
import com.semmle.util.data.StringUtil;
import com.semmle.util.data.UnitParser;
import com.semmle.util.exception.ResourceError;
import com.semmle.util.exception.UserError;
import com.semmle.util.extraction.ExtractorOutputConfig;
import com.semmle.util.files.FileUtil;
import com.semmle.util.files.PathMatcher;
import com.semmle.util.io.WholeIO;
import com.semmle.util.language.LegacyLanguage;
import com.semmle.util.process.ArgsParser;
import com.semmle.util.process.ArgsParser.FileMode;
import com.semmle.util.process.Env;
import com.semmle.util.process.Env.Var;
import com.semmle.util.trap.TrapWriter;
/** The main entry point of the JavaScript extractor. */
public class Main {
/**
* A version identifier that should be updated every time the extractor changes in such a way that
* it may produce different tuples for the same file under the same {@link ExtractorConfig}.
*/
public static final String EXTRACTOR_VERSION = "2021-05-31";
public static final Pattern NEWLINE = Pattern.compile("\n");
// symbolic constants for command line parameter names
private static final String P_ABORT_ON_PARSE_ERRORS = "--abort-on-parse-errors";
private static final String P_DEBUG_EXCLUSIONS = "--debug-exclusions";
private static final String P_DEFAULT_ENCODING = "--default-encoding";
private static final String P_EXCLUDE = "--exclude";
private static final String P_EXPERIMENTAL = "--experimental";
private static final String P_EXTERNS = "--externs";
private static final String P_EXTRACT_PROGRAM_TEXT = "--extract-program-text";
private static final String P_FILE_TYPE = "--file-type";
private static final String P_HTML = "--html";
private static final String P_INCLUDE = "--include";
private static final String P_PLATFORM = "--platform";
private static final String P_QUIET = "--quiet";
private static final String P_SOURCE_TYPE = "--source-type";
private static final String P_TRAP_CACHE = "--trap-cache";
private static final String P_TRAP_CACHE_BOUND = "--trap-cache-bound";
private static final String P_TYPESCRIPT = "--typescript";
private static final String P_TYPESCRIPT_FULL = "--typescript-full";
private static final String P_TYPESCRIPT_RAM = "--typescript-ram";
// symbolic constants for deprecated command line parameter names
private static final String P_EXCLUDE_PATH = "--exclude-path";
private static final String P_TOLERATE_PARSE_ERRORS = "--tolerate-parse-errors";
private static final String P_NODEJS = "--nodejs";
private static final String P_MOZ_EXTENSIONS = "--mozExtensions";
private static final String P_JSCRIPT = "--jscript";
private static final String P_HELP = "--help";
private static final String P_ECMA_VERSION = "--ecmaVersion";
private final ExtractorOutputConfig extractorOutputConfig;
private ExtractorConfig extractorConfig;
private PathMatcher includeMatcher, excludeMatcher;
private FileExtractor fileExtractor;
private ExtractorState extractorState;
private Set<File> projectFiles = new LinkedHashSet<>();
private Set<File> files = new LinkedHashSet<>();
private final Set<File> extractedFiles = new LinkedHashSet<>();
/* used to detect cyclic directory hierarchies */
private final Set<String> seenDirectories = new LinkedHashSet<>();
/**
* If true, the extractor state is shared with other extraction jobs.
*
* <p>This is used by the test runner.
*/
private boolean hasSharedExtractorState = false;
public Main(ExtractorOutputConfig extractorOutputConfig) {
this.extractorOutputConfig = extractorOutputConfig;
this.extractorState = new ExtractorState();
}
public Main(ExtractorOutputConfig extractorOutputConfig, ExtractorState extractorState) {
this.extractorOutputConfig = extractorOutputConfig;
this.extractorState = extractorState;
this.hasSharedExtractorState = true;
}
public void run(String[] args) {
ArgsParser ap = addArgs(new ArgsParser(args));
ap.parse();
extractorConfig = parseJSOptions(ap);
ITrapCache trapCache;
if (ap.has(P_TRAP_CACHE)) {
Long sizeBound = null;
if (ap.has(P_TRAP_CACHE_BOUND)) {
String tcb = ap.getString(P_TRAP_CACHE_BOUND);
sizeBound = DefaultTrapCache.asFileSize(tcb);
if (sizeBound == null) ap.error("Invalid TRAP cache size bound: " + tcb);
}
trapCache = new DefaultTrapCache(ap.getString(P_TRAP_CACHE), sizeBound, EXTRACTOR_VERSION);
} else {
if (ap.has(P_TRAP_CACHE_BOUND))
ap.error(
P_TRAP_CACHE_BOUND + " should only be specified together with " + P_TRAP_CACHE + ".");
trapCache = new DummyTrapCache();
}
fileExtractor = new FileExtractor(extractorConfig, extractorOutputConfig, trapCache);
setupMatchers(ap);
collectFiles(ap);
if (files.isEmpty()) {
verboseLog(ap, "Nothing to extract.");
return;
}
// Sort files for determinism
projectFiles = projectFiles.stream()
.sorted(AutoBuild.FILE_ORDERING)
.collect(Collectors.toCollection(() -> new LinkedHashSet<>()));
files = files.stream()
.sorted(AutoBuild.FILE_ORDERING)
.collect(Collectors.toCollection(() -> new LinkedHashSet<>()));
// Extract HTML files first, as they may contain embedded TypeScript code
for (File file : files) {
if (FileType.forFile(file, extractorConfig) == FileType.HTML) {
ensureFileIsExtracted(file, ap);
}
}
TypeScriptParser tsParser = extractorState.getTypeScriptParser();
tsParser.setTypescriptRam(extractorConfig.getTypeScriptRam());
if (containsTypeScriptFiles()) {
tsParser.verifyInstallation(!ap.has(P_QUIET));
}
for (File projectFile : projectFiles) {
long start = verboseLogStartTimer(ap, "Opening project " + projectFile);
ParsedProject project = tsParser.openProject(projectFile, DependencyInstallationResult.empty, extractorConfig.getVirtualSourceRoot());
verboseLogEndTimer(ap, start);
// Extract all files belonging to this project which are also matched
// by our include/exclude filters.
List<File> filesToExtract = new ArrayList<>();
for (File sourceFile : project.getOwnFiles()) {
File normalizedFile = normalizeFile(sourceFile);
if ((files.contains(normalizedFile) || extractorState.getSnippets().containsKey(normalizedFile.toPath()))
&& !extractedFiles.contains(sourceFile.getAbsoluteFile())
&& FileType.TYPESCRIPT.getExtensions().contains(FileUtil.extension(sourceFile))) {
filesToExtract.add(sourceFile);
}
}
tsParser.prepareFiles(filesToExtract);
for (int i = 0; i < filesToExtract.size(); ++i) {
ensureFileIsExtracted(filesToExtract.get(i), ap);
}
// Close the project to free memory. This does not need to be in a `finally` as
// the project is not a system resource.
tsParser.closeProject(projectFile);
}
if (!projectFiles.isEmpty()) {
// Extract all the types discovered when extracting the ASTs.
TypeTable typeTable = tsParser.getTypeTable();
extractTypeTable(projectFiles.iterator().next(), typeTable);
}
List<File> remainingTypescriptFiles = new ArrayList<>();
for (File f : files) {
if (!extractedFiles.contains(f.getAbsoluteFile())
&& FileType.forFileExtension(f) == FileType.TYPESCRIPT) {
remainingTypescriptFiles.add(f);
}
}
if (!remainingTypescriptFiles.isEmpty()) {
tsParser.prepareFiles(remainingTypescriptFiles);
for (File f : remainingTypescriptFiles) {
ensureFileIsExtracted(f, ap);
}
}
// The TypeScript compiler instance is no longer needed - free up some memory.
if (hasSharedExtractorState) {
tsParser.reset(); // This is called from a test runner, so keep the process alive.
} else {
tsParser.killProcess();
}
// Extract files that were not part of a project.
for (File f : files) {
if (isFileDerivedFromTypeScriptFile(f))
continue;
ensureFileIsExtracted(f, ap);
}
}
/**
* Returns true if the given path is likely the output of compiling a TypeScript file
* which we have already extracted.
*/
private boolean isFileDerivedFromTypeScriptFile(File path) {
String name = path.getName();
if (!name.endsWith(".js"))
return false;
String stem = name.substring(0, name.length() - ".js".length());
for (String ext : FileType.TYPESCRIPT.getExtensions()) {
if (new File(path.getParent(), stem + ext).exists()) {
return true;
}
}
return false;
}
private void extractTypeTable(File fileHandle, TypeTable table) {
TrapWriter trapWriter =
extractorOutputConfig
.getTrapWriterFactory()
.mkTrapWriter(
new File(
fileHandle.getParentFile(),
fileHandle.getName() + ".codeql-typescript-typetable"));
try {
new TypeExtractor(trapWriter, table).extract();
} finally {
FileUtil.close(trapWriter);
}
}
private void ensureFileIsExtracted(File f, ArgsParser ap) {
if (!extractedFiles.add(f.getAbsoluteFile())) {
// The file has already been extracted as part of a project.
return;
}
long start = verboseLogStartTimer(ap, "Extracting " + f);
try {
fileExtractor.extract(f.getAbsoluteFile(), extractorState);
verboseLogEndTimer(ap, start);
} catch (IOException e) {
throw new ResourceError("Extraction of " + f + " failed.", e);
}
}
private void verboseLog(ArgsParser ap, String message) {
if (!ap.has(P_QUIET)) {
System.out.println(message);
}
}
private long verboseLogStartTimer(ArgsParser ap, String message) {
if (!ap.has(P_QUIET)) {
System.out.print(message + "...");
System.out.flush();
}
return System.currentTimeMillis();
}
private void verboseLogEndTimer(ArgsParser ap, long start) {
long end = System.currentTimeMillis();
if (!ap.has(P_QUIET)) {
System.out.println(" done (" + (end - start) / 1000 + " seconds).");
}
}
/** Returns true if the project contains a TypeScript file to be extracted. */
private boolean containsTypeScriptFiles() {
for (File file : files) {
// The file headers have already been checked, so don't use I/O.
if (FileType.forFileExtension(file) == FileType.TYPESCRIPT) {
return true;
}
}
return false;
}
public void collectFiles(ArgsParser ap) {
for (File f : getFilesArg(ap))
collectFiles(f, true);
}
private List<File> getFilesArg(ArgsParser ap) {
return ap.getOneOrMoreFiles("files", FileMode.FILE_OR_DIRECTORY_MUST_EXIST);
}
public void setupMatchers(ArgsParser ap) {
Set<String> includes = new LinkedHashSet<>();
// only extract HTML and JS by default
addIncludesFor(includes, FileType.HTML);
addIncludesFor(includes, FileType.JS);
// extract TypeScript if `--typescript` or `--typescript-full` was specified
if (getTypeScriptMode(ap) != TypeScriptMode.NONE) addIncludesFor(includes, FileType.TYPESCRIPT);
// add explicit include patterns
for (String pattern : ap.getZeroOrMore(P_INCLUDE))
addPathPattern(includes, System.getProperty("user.dir"), pattern);
this.includeMatcher = new PathMatcher(includes);
// if we are extracting (potential) Node.js code, we also want to
// include package.json files, and files without extension
if (getPlatform(ap) != Platform.WEB) {
PathMatcher innerIncludeMatcher = this.includeMatcher;
this.includeMatcher =
new PathMatcher("**/package.json") {
@Override
public boolean matches(String path) {
// match files without extension
String basename = path.substring(path.lastIndexOf(File.separatorChar) + 1);
if (FileUtil.extension(basename).isEmpty()) return true;
// match package.json and anything matched by the inner matcher
return super.matches(path) || innerIncludeMatcher.matches(path);
}
};
}
Set<String> excludes = new LinkedHashSet<>();
for (String pattern : ap.getZeroOrMore(P_EXCLUDE))
addPathPattern(excludes, System.getProperty("user.dir"), pattern);
for (String excl : ap.getZeroOrMore(P_EXCLUDE_PATH)) {
File exclFile = new File(excl).getAbsoluteFile();
String base = exclFile.getParent();
for (String pattern : NEWLINE.split(new WholeIO().strictread(exclFile)))
addPathPattern(excludes, base, pattern);
}
this.excludeMatcher = new PathMatcher(excludes);
if (ap.has(P_DEBUG_EXCLUSIONS)) {
System.out.println("Inclusion patterns: " + this.includeMatcher);
System.out.println("Exclusion patterns: " + this.excludeMatcher);
}
}
private void addIncludesFor(Set<String> includes, FileType filetype) {
for (String extension : filetype.getExtensions()) includes.add("**/*" + extension);
}
private void addPathPattern(Set<String> patterns, String base, String pattern) {
pattern = pattern.trim();
if (pattern.isEmpty()) return;
if (!FileUtil.isAbsolute(pattern) && base != null) {
pattern = base + "/" + pattern;
}
if (pattern.endsWith("/")) pattern = pattern.substring(0, pattern.length() - 1);
patterns.add(pattern);
}
private ArgsParser addArgs(ArgsParser argsParser) {
argsParser.addDeprecatedFlag(
P_ECMA_VERSION, 1, "Files are now always extracted as ECMAScript 2017.");
argsParser.addFlag(
P_EXCLUDE, 1, "Do not extract files matching the given filename pattern.", true);
argsParser.addToleratedFlag(P_EXCLUDE_PATH, 1, true);
argsParser.addFlag(
P_EXPERIMENTAL,
0,
"Enable experimental support for pending ECMAScript proposals "
+ "(public class fields, function.sent, decorators, export extensions, function bind, "
+ "parameter-less catch, dynamic import, numeric separators, bigints, top-level await), "
+ "as well as other language extensions (E4X, JScript, Mozilla and v8-specific extensions) and full HTML extraction.");
argsParser.addFlag(
P_EXTERNS, 0, "Extract the given JavaScript files as Closure-style externs.");
argsParser.addFlag(
P_EXTRACT_PROGRAM_TEXT,
0,
"Extract a representation of the textual content of the program "
+ "(in addition to its syntactic structure).");
argsParser.addFlag(
P_FILE_TYPE,
1,
"Assume all files to be of the given type, regardless of extension; "
+ "the type must be one of "
+ StringUtil.glue(", ", FileExtractor.FileType.allNames)
+ ".");
argsParser.addFlag(P_HELP, 0, "Display this help.");
argsParser.addFlag(
P_HTML,
1,
"Control extraction of HTML files: "
+ "'scripts' extracts JavaScript code embedded inside HTML, but not the HTML itself; "
+ "'elements' additionally extracts HTML elements and their attributes, as well as HTML comments, but not textual content (default); "
+ "'all' extracts elements, embedded scripts, comments and text.");
argsParser.addFlag(
P_INCLUDE,
1,
"Extract files matching the given filename pattern (in addition to HTML and JavaScript files).",
true);
argsParser.addDeprecatedFlag(P_JSCRIPT, 0, "Use '" + P_EXPERIMENTAL + "' instead.");
argsParser.addDeprecatedFlag(P_MOZ_EXTENSIONS, 0, "Use '" + P_EXPERIMENTAL + "' instead.");
argsParser.addDeprecatedFlag(P_NODEJS, 0, "Use '" + P_PLATFORM + " node' instead.");
argsParser.addFlag(
P_PLATFORM,
1,
"Extract the given JavaScript files as code for the given platform: "
+ "'node' extracts them as Node.js modules; "
+ "'web' as plain JavaScript files; "
+ "'auto' uses heuristics to automatically detect "
+ "Node.js modules and extracts everything else as plain JavaScript files. "
+ "The default is 'auto'.");
argsParser.addFlag(P_QUIET, 0, "Produce less output.");
argsParser.addFlag(
P_SOURCE_TYPE,
1,
"The source type to use; must be one of 'script', 'module' or 'auto'. "
+ "The default is 'auto'.");
argsParser.addToleratedFlag(P_TOLERATE_PARSE_ERRORS, 0);
argsParser.addFlag(
P_ABORT_ON_PARSE_ERRORS, 0, "Abort extraction if a parse error is encountered.");
argsParser.addFlag(P_TRAP_CACHE, 1, "Use the given directory as the TRAP cache.");
argsParser.addFlag(
P_TRAP_CACHE_BOUND,
1,
"A (soft) upper limit on the size of the TRAP cache, "
+ "in standard size units (e.g., 'g' for gigabytes).");
argsParser.addFlag(P_DEFAULT_ENCODING, 1, "The encoding to use; default is UTF-8.");
argsParser.addFlag(P_TYPESCRIPT, 0, "Enable basic TypesScript support.");
argsParser.addFlag(
P_TYPESCRIPT_FULL, 0, "Enable full TypeScript support with static type information.");
argsParser.addFlag(
P_TYPESCRIPT_RAM,
1,
"Amount of memory allocated to the TypeScript compiler process. The default is 1G.");
argsParser.addToleratedFlag(P_DEBUG_EXCLUSIONS, 0);
argsParser.addTrailingParam("files", "Files and directories to extract.");
return argsParser;
}
private boolean enableExperimental(ArgsParser ap) {
return ap.has(P_EXPERIMENTAL) || ap.has(P_JSCRIPT) || ap.has(P_MOZ_EXTENSIONS);
}
private static TypeScriptMode getTypeScriptMode(ArgsParser ap) {
if (ap.has(P_TYPESCRIPT_FULL)) return TypeScriptMode.FULL;
if (ap.has(P_TYPESCRIPT)) return TypeScriptMode.BASIC;
return TypeScriptMode.NONE;
}
private Path inferSourceRoot(ArgsParser ap) {
List<File> files = getFilesArg(ap);
Path sourceRoot = files.iterator().next().toPath().toAbsolutePath().getParent();
for (File file : files) {
Path path = file.toPath().toAbsolutePath().getParent();
for (int i = 0; i < sourceRoot.getNameCount(); ++i) {
if (!(i < path.getNameCount() && path.getName(i).equals(sourceRoot.getName(i)))) {
sourceRoot = sourceRoot.subpath(0, i);
break;
}
}
}
return sourceRoot;
}
private ExtractorConfig parseJSOptions(ArgsParser ap) {
ExtractorConfig cfg =
new ExtractorConfig(enableExperimental(ap))
.withExterns(ap.has(P_EXTERNS))
.withPlatform(getPlatform(ap))
.withTolerateParseErrors(
ap.has(P_TOLERATE_PARSE_ERRORS) || !ap.has(P_ABORT_ON_PARSE_ERRORS))
.withHtmlHandling(
ap.getEnum(
P_HTML,
HtmlPopulator.Config.class,
ap.has(P_EXPERIMENTAL) ? HtmlPopulator.Config.ALL : HtmlPopulator.Config.ELEMENTS))
.withFileType(getFileType(ap))
.withSourceType(ap.getEnum(P_SOURCE_TYPE, SourceType.class, SourceType.AUTO))
.withExtractLines(ap.has(P_EXTRACT_PROGRAM_TEXT))
.withTypeScriptMode(getTypeScriptMode(ap))
.withTypeScriptRam(
ap.has(P_TYPESCRIPT_RAM)
? UnitParser.parseOpt(ap.getString(P_TYPESCRIPT_RAM), UnitParser.MEGABYTES)
: 0);
if (ap.has(P_DEFAULT_ENCODING)) cfg = cfg.withDefaultEncoding(ap.getString(P_DEFAULT_ENCODING));
// Make a usable virtual source root mapping.
// The concept of source root and scratch directory do not exist in the legacy extractor,
// so we construct these based on what we have.
String odasaDbDir = Env.systemEnv().getNonEmpty(Var.ODASA_DB);
VirtualSourceRoot virtualSourceRoot =
odasaDbDir == null
? VirtualSourceRoot.none
: new VirtualSourceRoot(inferSourceRoot(ap), Paths.get(odasaDbDir, "working"));
cfg = cfg.withVirtualSourceRoot(virtualSourceRoot);
return cfg;
}
private String getFileType(ArgsParser ap) {
String fileType = null;
if (ap.has(P_FILE_TYPE)) {
fileType = StringUtil.uc(ap.getString(P_FILE_TYPE));
if (!FileExtractor.FileType.allNames.contains(fileType))
ap.error("Invalid file type " + ap.getString(P_FILE_TYPE));
}
return fileType;
}
private Platform getPlatform(ArgsParser ap) {
if (ap.has(P_NODEJS)) return Platform.NODE;
return ap.getEnum(P_PLATFORM, Platform.class, Platform.AUTO);
}
/**
* Collect files to extract under a given root, which may be either a file or a directory. The
* {@code explicit} flag indicates whether {@code root} was explicitly passed to the extractor as
* a command line argument, or whether it is examined as part of a recursive traversal.
*/
private void collectFiles(File root, boolean explicit) {
if (!root.exists()) {
System.err.println("Skipping " + root + ", which does not exist.");
return;
}
if (root.isDirectory()) {
// exclude directories we've seen before
if (seenDirectories.add(FileUtil.tryMakeCanonical(root).getPath()))
// apply exclusion filters for directories
if (!excludeMatcher.matches(root.getAbsolutePath())) {
File[] gs = root.listFiles();
if (gs == null) System.err.println("Skipping " + root + ", which cannot be listed.");
else for (File g : gs) collectFiles(g, false);
}
} else {
String path = root.getAbsolutePath();
// extract files that are supported, match the layout (if any), pass the includeMatcher,
// and do not pass the excludeMatcher
if (fileExtractor.supports(root)
&& extractorOutputConfig.shouldExtract(root)
&& (explicit || includeMatcher.matches(path) && !excludeMatcher.matches(path))) {
files.add(normalizeFile(root));
}
if (extractorConfig.getTypeScriptMode() == TypeScriptMode.FULL
&& root.getName().equals("tsconfig.json")
&& !excludeMatcher.matches(path)) {
projectFiles.add(root);
}
}
}
private File normalizeFile(File root) {
return root.getAbsoluteFile().toPath().normalize().toFile();
}
public static void main(String[] args) {
try {
new Main(new ExtractorOutputConfig(LegacyLanguage.JAVASCRIPT)).run(args);
} catch (UserError e) {
System.err.println(e.getMessage());
if (!e.reportAsInfoMessage()) System.exit(1);
}
}
}
|
package org.ccnx.ccn.impl.repo;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.config.SystemConfiguration.DEBUGGING_FLAGS;
import org.ccnx.ccn.impl.repo.PolicyXML.PolicyObject;
import org.ccnx.ccn.impl.security.keys.BasicKeyManager;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.content.CCNStringObject;
import org.ccnx.ccn.io.content.ContentDecodingException;
import org.ccnx.ccn.io.content.ContentEncodingException;
import org.ccnx.ccn.profiles.CCNProfile;
import org.ccnx.ccn.profiles.context.ServiceDiscoveryProfile;
import org.ccnx.ccn.profiles.nameenum.NameEnumerationResponse;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.KeyLocator;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
/**
* Implements a log-structured RepositoryStore on a filesystem using sequential data files with an index for queries
*/
public class LogStructRepoStore extends RepositoryStoreBase implements RepositoryStore, ContentTree.ContentGetter {
public final static String CURRENT_VERSION = "1.4";
public static class LogStructRepoStoreProfile implements CCNProfile {
public final static String META_DIR = ".meta";
public final static String NORMAL_COMPONENT = "0";
public final static String SPLIT_COMPONENT = "1";
private static String DEFAULT_LOCAL_NAME = "Repository";
private static String DEFAULT_GLOBAL_NAME = "/parc.com/csl/ccn/Repos";
private static final String REPO_PRIVATE = "private";
private static final String VERSION = "version";
private static final String REPO_LOCALNAME = "local";
private static final String REPO_GLOBALPREFIX = "global";
public static final char [] KEYSTORE_PASSWORD = "Th1s 1s n0t 8 g00d R3p0s1t0ry p8ssw0rd!".toCharArray();
public static final String KEYSTORE_FILE = "ccnx_repository_keystore";
public static final String REPOSITORY_USER = "Repository";
// OS dependencies -- some OSes seem to ignore case in keystore aliases
public static final String REPOSITORY_KEYSTORE_ALIAS = REPOSITORY_USER.toLowerCase();
private static String CONTENT_FILE_PREFIX = "repoFile";
private static String DEBUG_TREEDUMP_FILE = "debugNamesTree";
private static String DIAG_NAMETREE = "nametree"; // Diagnostic/signal to dump name tree to debug file
private static String DIAG_NAMETREEWIDE = "nametreewide"; // Same as DIAG_NAMETREE but with wide names per node
private static ContentName PRIVATE_DATA_PREFIX = ContentName.fromNative(new String[]{META_DIR, REPO_PRIVATE});
}
protected String _repositoryRoot = null;
protected File _repositoryFile;
Map<Integer,RepoFile> _files;
RepoFile _activeWriteFile;
ContentTree _index;
public class RepoFile {
File file;
RandomAccessFile openFile;
long nextWritePos;
}
protected class FileRef extends ContentRef {
int id;
long offset;
}
/**
* Gets content matching the given interest
*
* @param interest the given interest
* @return the closest matching ContentObject or null if no match
*/
public ContentObject getContent(Interest interest)
throws RepositoryException {
return _index.get(interest, this);
}
/**
* Gets all names matching the given NameEnumeration interest
*
* @param i the interest
* @returns the data as a NameEnumerationResponse
*/
public NameEnumerationResponse getNamesWithPrefix(Interest i, ContentName responseName) {
return _index.getNamesWithPrefix(i, responseName);
}
/**
* Gets the current policy for this repository
* @returns the policy
*/
public Policy getPolicy() {
return _policy;
}
/**
* Gets the current version of this RepositoryStore
*
* @return the version as a String
*/
public String getVersion() {
return CURRENT_VERSION;
}
/**
* Read the current repository file(s) for this repository and create an index for them.
* WARNING: multiple files are not well tested
*
* @return the number of files making up the repository
*/
protected Integer createIndex() {
int max = 0;
_index = new ContentTree();
assert(null != _repositoryFile);
assert(_repositoryFile.isDirectory());
String[] filenames = _repositoryFile.list();
for (int i = 0; i < filenames.length; i++) {
if (filenames[i].startsWith(LogStructRepoStoreProfile.CONTENT_FILE_PREFIX)) {
String indexPart = filenames[i].substring(LogStructRepoStoreProfile.CONTENT_FILE_PREFIX.length());
if (null != indexPart && indexPart.length() > 0) {
try {
Integer index = Integer.parseInt(indexPart);
if (index > max) {
max = index.intValue();
}
RepoFile rfile = new RepoFile();
rfile.file = new File(_repositoryFile,filenames[i]);
rfile.openFile = new RandomAccessFile(rfile.file, "r");
InputStream is = new BufferedInputStream(new RandomAccessInputStream(rfile.openFile),8196);
if (Log.isLoggable(Log.FAC_REPO, Level.FINE)) {
Log.fine(Log.FAC_REPO, "Creating index for {0}", filenames[i]);
}
while (true) {
FileRef ref = new FileRef();
ref.id = index.intValue();
ref.offset = rfile.openFile.getFilePointer();
if(ref.offset > 0)
ref.offset = ref.offset - is.available();
ContentObject tmp = new ContentObject();
try {
if (rfile.openFile.getFilePointer()<rfile.openFile.length() || is.available()!=0) {
//tmp.decode(is);
tmp.decode(is);
}
else{
if (Log.isLoggable(Log.FAC_REPO, Level.INFO)) {
Log.info(Log.FAC_REPO, "at the end of the file");
}
rfile.openFile.close();
rfile.openFile = null;
break;
}
} catch (ContentDecodingException e) {
Log.logStackTrace(Level.WARNING, e);
e.printStackTrace();
// Failed to decode, must be end of this one
//added check for end of file above
rfile.openFile.close();
rfile.openFile = null;
break;
}
_index.insert(tmp, ref, rfile.file.lastModified(), this, null);
}
_files.put(index, rfile);
} catch (NumberFormatException e) {
// Not valid file
Log.warning("Invalid file name " + filenames[i]);
} catch (FileNotFoundException e) {
Log.warning("Unable to open file to create index: " + filenames[i]);
} catch (IOException e) {
Log.warning("IOException reading file to create index: " + filenames[i]);
}
}
}
}
return new Integer(max);
}
/**
* Initialize the repository
*
* @param repositoryRoot the directory containing the files to store a repository. A new directory is created if this doesn't yet exist
* @param policyFile a file containing policy data to define the initial repository policy (see BasicPolicy)
* @param localName the local name for this repository as a slash separated String (defaults if null)
* @param globalPrefix the global prefix for this repository as a slash separated String (defaults if null)
* @param An initial namespace (defaults to namespace stored in repository, or / if none)
* @throws RepositoryException if the policyFile, localName, or globalName are improperly formatted
* @param handle optional CCNHandle if caller wants to override the
* default connection/identity behavior of the repository -- this
* provides a KeyManager and handle for the repository to use to
* obtain its keys and communicate with ccnd. If null, the repository
* will configure its own based on policy, or if none, create one
* using the executing user's defaults.
*/
public void initialize(String repositoryRoot, File policyFile, String localName, String globalPrefix,
String namespace, CCNHandle handle) throws RepositoryException {
PolicyXML pxml = null;
boolean nameFromArgs = (null != localName);
boolean globalFromArgs = (null != globalPrefix);
if (null == localName)
localName = LogStructRepoStoreProfile.DEFAULT_LOCAL_NAME;
if (null == globalPrefix)
globalPrefix = LogStructRepoStoreProfile.DEFAULT_GLOBAL_NAME;
pxml = startInitPolicy(policyFile, namespace);
if (repositoryRoot == null) {
throw new InvalidParameterException();
} else {
_repositoryRoot = repositoryRoot;
}
_repositoryFile = new File(_repositoryRoot);
_repositoryFile.mkdirs();
if (Log.isLoggable(Level.WARNING)){
Log.warning("Starting repository; repository root is: {0}", _repositoryFile.getAbsolutePath());
}
// DKS -- we probably don't want to encrypt startWrites and other messages,
// as the repository doesn't likely have write privileges (or read privileges)
// for data. Without a fully public-key system, have to go for unencrypted writes.
// Have to determine the best way to handle this, for now disable access control
// for the repository write side.
SystemConfiguration.setAccessControlDisabled(true);
// Build our handle
if (null == handle) {
// Load our keystore. Make one if none exists; use the
// default kestore type and key algorithm.
try {
_km =
new BasicKeyManager(LogStructRepoStoreProfile.REPOSITORY_USER,
_repositoryRoot, null, LogStructRepoStoreProfile.KEYSTORE_FILE,
null, LogStructRepoStoreProfile.REPOSITORY_KEYSTORE_ALIAS,
LogStructRepoStoreProfile.KEYSTORE_PASSWORD);
_km.initialize();
if( Log.isLoggable(Level.FINEST))
Log.finest("Initialized repository key store.");
handle = CCNHandle.open(_km);
if( Log.isLoggable(Level.FINEST))
Log.finest("Opened repository handle.");
// Let's use our key manager as the default. That will make us less
// prone to accidentally loading the user's key manager. If we close it more than
// once, that's ok.
KeyManager.setDefaultKeyManager(_km);
// Serve our key using the localhost key discovery protocol
ServiceDiscoveryProfile.publishLocalServiceKey(ServiceDiscoveryProfile.REPOSITORY_SERVICE_NAME,
null, _km);
} catch (ConfigurationException e) {
Log.warning("ConfigurationException loading repository key store: " + e.getMessage());
throw new RepositoryException("ConfigurationException loading repository key store!", e);
} catch (IOException e) {
Log.warning("IOException loading repository key store: " + e.getMessage());
throw new RepositoryException("IOException loading repository key store!", e);
} catch (InvalidKeyException e) {
Log.warning("InvalidKeyException loading repository key store: " + e.getMessage());
throw new RepositoryException("InvalidKeyException loading repository key store!", e);
}
}
_handle = handle;
// Internal initialization
_files = new HashMap<Integer, RepoFile>();
int maxFileIndex = createIndex();
// Internal initialization
//moved the following... getContent depends on having an index
//_files = new HashMap<Integer, RepoFile>();
//int maxFileIndex = createIndex();
try {
if (maxFileIndex == 0) {
maxFileIndex = 1; // the index of a file we will actually write
RepoFile rfile = new RepoFile();
rfile.file = new File(_repositoryFile, LogStructRepoStoreProfile.CONTENT_FILE_PREFIX+"1");
rfile.openFile = new RandomAccessFile(rfile.file, "rw");
rfile.nextWritePos = 0;
_files.put(new Integer(maxFileIndex), rfile);
_activeWriteFile = rfile;
} else {
RepoFile rfile = _files.get(new Integer(maxFileIndex));
long cursize = rfile.file.length();
rfile.openFile = new RandomAccessFile(rfile.file, "rw");
rfile.nextWritePos = cursize;
_activeWriteFile = rfile;
}
} catch (FileNotFoundException e) {
Log.warning("Error opening content output file index " + maxFileIndex);
}
// Verify stored policy info
// TODO - we shouldn't do this if the user has specified a policy file which already has
// this information
String version = checkFile(LogStructRepoStoreProfile.VERSION, CURRENT_VERSION, false);
if (version != null && !version.trim().equals(CURRENT_VERSION))
throw new RepositoryException("Bad repository version: " + version);
String checkName = checkFile(LogStructRepoStoreProfile.REPO_LOCALNAME, localName, nameFromArgs);
localName = checkName != null ? checkName : localName;
try {
_policy.setLocalName(localName);
} catch (MalformedContentNameStringException e3) {
throw new RepositoryException(e3.getMessage());
}
checkName = checkFile(LogStructRepoStoreProfile.REPO_GLOBALPREFIX, globalPrefix, globalFromArgs);
globalPrefix = checkName != null ? checkName : globalPrefix;
if (Log.isLoggable(Log.FAC_REPO, Level.INFO)) {
Log.info(Log.FAC_REPO, "REPO: initializing repository: global prefix {0}, local name {1}", globalPrefix, localName);
}
try {
_policy.setGlobalPrefix(globalPrefix);
if (Log.isLoggable(Log.FAC_REPO, Level.INFO)) {
Log.info(Log.FAC_REPO, "REPO: initializing policy location: {0} for global prefix {1} and local name {2}", localName, globalPrefix, localName);
}
} catch (MalformedContentNameStringException e2) {
throw new RepositoryException(e2.getMessage());
}
/**
* Try to read policy from storage if we don't have full policy source yet
*/
if (null == pxml) {
try {
readPolicy(localName, _km);
} catch (ContentDecodingException e) {
throw new RepositoryException(e.getMessage());
}
} else { // If we didn't read in our policy from a previous saved policy file, save the policy now
pxml = _policy.getPolicyXML();
ContentName policyName = BasicPolicy.getPolicyName(_policy.getGlobalPrefix(), _policy.getLocalName());
try {
PolicyObject po = new PolicyObject(policyName, pxml, null, null, new RepositoryInternalFlowControl(this, handle));
po.save();
} catch (IOException e) {
throw new RepositoryException(e.getMessage());
}
}
try {
finishInitPolicy(globalPrefix, localName);
} catch (MalformedContentNameStringException e) {
throw new RepositoryException(e.getMessage());
}
}
/**
* Save the given content in the repository store
*
* @param content the content to save
* @throws RepositoryException it the content can not be written or encoded
* @returns NameEnumerationResponse if this satisfies an outstanding NameEnumeration request
*/
public NameEnumerationResponse saveContent(ContentObject content) throws RepositoryException {
// Make sure content is within allowable nameSpace
boolean nameSpaceOK = false;
synchronized (_policy) {
for (ContentName name : _policy.getNamespace()) {
if (name.isPrefixOf(content.name())) {
nameSpaceOK = true;
break;
}
}
}
if (!nameSpaceOK) {
if (Log.isLoggable(Log.FAC_REPO, Level.INFO)) {
if( Log.isLoggable(Level.INFO))
Log.info("Repo rejecting content: {0}, not in registered namespace.", content.name());
}
return null;
}
try {
NameEnumerationResponse ner = new NameEnumerationResponse();
synchronized(_activeWriteFile) {
assert(null != _activeWriteFile.openFile);
FileRef ref = new FileRef();
ref.id = Integer.parseInt(_activeWriteFile.file.getName().substring(LogStructRepoStoreProfile.CONTENT_FILE_PREFIX.length()));
ref.offset = _activeWriteFile.nextWritePos;
_activeWriteFile.openFile.seek(_activeWriteFile.nextWritePos);
OutputStream os = new RandomAccessOutputStream(_activeWriteFile.openFile);
content.encode(os);
_activeWriteFile.nextWritePos = _activeWriteFile.openFile.getFilePointer();
_index.insert(content, ref, System.currentTimeMillis(), this, ner);
if (ner==null || ner.getPrefix()==null) {
if (Log.isLoggable(Log.FAC_REPO, Level.FINE)) {
Log.fine(Log.FAC_REPO, "new content did not trigger an interest flag");
}
} else {
if (Log.isLoggable(Log.FAC_REPO, Level.FINE)) {
Log.fine(Log.FAC_REPO, "new content was added where there was a name enumeration response interest flag");
}
}
return ner;
}
} catch (ContentEncodingException e) {
throw new RepositoryException("Failed to encode content: " + e.getMessage());
} catch (IOException e) {
throw new RepositoryException("Failed to write content: " + e.getMessage());
}
}
/**
* Get content for the given reference from the storage files. Used to retrieve content for
* comparison operations.
*
* @param ref the reference
* @return ContentObject at the referenced slot in the storage files
*/
public ContentObject get(ContentRef ref) {
// This is a call back based on what we put in ContentTree, so it must be
// using our subtype of ContentRef
FileRef fref = (FileRef)ref;
try {
RepoFile file = _files.get(fref.id);
if (null == file)
return null;
synchronized (file) {
if (null == file.openFile) {
file.openFile = new RandomAccessFile(file.file, "r");
}
file.openFile.seek(fref.offset);
ContentObject content = new ContentObject();
InputStream is = new BufferedInputStream(new RandomAccessInputStream(file.openFile), 8196);
content.decode(is);
return content;
}
} catch (IndexOutOfBoundsException e) {
return null;
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) { // handles ContentDecodingException
return null;
}
}
private ContentName getPrivateContentName(String fileName) {
return ContentName.fromNative(LogStructRepoStoreProfile.PRIVATE_DATA_PREFIX, fileName);
}
/**
* Check data "file" - create new one if none exists or "forceWrite" is set.
* Files are always versioned so we can find the latest one.
* @throws RepositoryException
* @throws IOException
* @throws ConfigurationException
*/
private String checkFile(String fileName, String contents, boolean forceWrite) throws RepositoryException {
ContentName name = getPrivateContentName(fileName);
RepositoryInternalInputHandler riih = null;
RepositoryInternalFlowControl rifc = null;
CCNStringObject so = null;
try {
riih = new RepositoryInternalInputHandler(this, _km);
rifc = new RepositoryInternalFlowControl(this, riih);
if (!forceWrite) {
try {
so = new CCNStringObject(name, riih);
if (null != so) {
String ret = so.string();
so.close();
return ret;
}
} catch (Exception ioe) {}
if (null != so)
so.close();
}
PublisherPublicKeyDigest publisher = _km.getDefaultKeyID();
PrivateKey signingKey = _km.getSigningKey(publisher);
KeyLocator locator = _km.getKeyLocator(signingKey);
so = new CCNStringObject(name, contents, publisher, locator, rifc);
so.update();
} catch (Exception e) {
Log.logStackTrace(Level.WARNING, e);
e.printStackTrace();
}
if (null != so)
so.close();
if (null != rifc)
rifc.close();
if (null != riih)
riih.close();
return null;
}
protected void dumpNames(int nodelen) {
// Debug: dump names tree to file
File namesFile = new File(_repositoryFile, LogStructRepoStoreProfile.DEBUG_TREEDUMP_FILE);
try {
if (Log.isLoggable(Log.FAC_REPO, Level.INFO)) {
Log.info(Log.FAC_REPO, "Dumping names to " + namesFile.getAbsolutePath() + " (len " + nodelen + ")");
}
PrintStream namesOut = new PrintStream(namesFile);
if (null != _index) {
_index.dumpNamesTree(namesOut, nodelen);
}
} catch (FileNotFoundException ex) {
Log.warning("Unable to dump names to " + namesFile.getAbsolutePath());
}
}
/**
* Dump all names of data stored in the repository into a special file within the repository
* on diagnostic request from higher level code
*
* @param name "nametree" or "nametreewide" to decide whether to limit the printout length of components
*/
public boolean diagnostic(String name) {
if (0 == name.compareToIgnoreCase(LogStructRepoStoreProfile.DIAG_NAMETREE)) {
dumpNames(35);
return true;
} else if (0 == name.compareToIgnoreCase(LogStructRepoStoreProfile.DIAG_NAMETREEWIDE)) {
dumpNames(-1);
return true;
}
return false;
}
/**
* Cleanup on shutdown
*/
public void shutDown() {
super.shutDown();
if (null != _km)
_km.close();
if (null != _activeWriteFile && null != _activeWriteFile.openFile) {
try {
_activeWriteFile.openFile.close();
_activeWriteFile.openFile = null;
} catch (IOException e) {}
}
if (SystemConfiguration.checkDebugFlag(DEBUGGING_FLAGS.REPO_EXITDUMP)) {
Log.warning("Debug flag ({0}) is set: dumping nametree now (on shutdown)", DEBUGGING_FLAGS.REPO_EXITDUMP.toString());
dumpNames(-1);
}
}
public Object getStatus(String type) {
return type.equals(RepositoryStore.REPO_SIMPLE_STATUS_REQUEST)
? ((null == _activeWriteFile.openFile) ? null : "running") : null;
}
}
|
package org.pentaho.ui.xul.gwt.tags;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.Vector;
import org.pentaho.gwt.widgets.client.listbox.CustomListBox;
import org.pentaho.gwt.widgets.client.table.BaseTable;
import org.pentaho.gwt.widgets.client.table.ColumnComparators.BaseColumnComparator;
import org.pentaho.gwt.widgets.client.utils.StringUtils;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulEventSource;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.binding.Binding;
import org.pentaho.ui.xul.binding.BindingConvertor;
import org.pentaho.ui.xul.binding.InlineBindingExpression;
import org.pentaho.ui.xul.components.XulTreeCell;
import org.pentaho.ui.xul.components.XulTreeCol;
import org.pentaho.ui.xul.containers.XulTree;
import org.pentaho.ui.xul.containers.XulTreeChildren;
import org.pentaho.ui.xul.containers.XulTreeCols;
import org.pentaho.ui.xul.containers.XulTreeItem;
import org.pentaho.ui.xul.containers.XulTreeRow;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.gwt.AbstractGwtXulContainer;
import org.pentaho.ui.xul.gwt.GwtXulHandler;
import org.pentaho.ui.xul.gwt.GwtXulParser;
import org.pentaho.ui.xul.gwt.binding.GwtBinding;
import org.pentaho.ui.xul.gwt.binding.GwtBindingContext;
import org.pentaho.ui.xul.gwt.binding.GwtBindingMethod;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.TreeListener;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.widgetideas.client.ResizableWidgetCollection;
import com.google.gwt.widgetideas.table.client.SourceTableSelectionEvents;
import com.google.gwt.widgetideas.table.client.TableSelectionListener;
import com.google.gwt.widgetideas.table.client.SelectionGrid.SelectionPolicy;
public class GwtTree extends AbstractGwtXulContainer implements XulTree {
/**
* Cached elements.
*/
private Collection elements;
public static void register() {
GwtXulParser.registerHandler("tree",
new GwtXulHandler() {
public Element newInstance() {
return new GwtTree();
}
});
}
XulTreeCols columns = null;
XulTreeChildren rootChildren = null;
private XulDomContainer domContainer;
private Tree tree;
private boolean suppressEvents = false;
private boolean editable = false;
private boolean visible = true;
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
if(simplePanel != null) {
simplePanel.setVisible(visible);
}
}
/**
* Used when this widget is a tree. Not used when this widget is a table.
*/
private ScrollPanel scrollPanel = new ScrollPanel();
/**
* The managed object. If this widget is a tree, then the tree is added to the scrollPanel, which is added to this
* simplePanel. If this widget is a table, then the table is added directly to this simplePanel.
*/
private SimplePanel simplePanel = new SimplePanel();
/**
* Clears the parent panel and adds the given widget.
* @param widget tree or table to set in parent panel
*/
protected void setWidgetInPanel(final Widget widget) {
if (isHierarchical()) {
scrollPanel.clear();
simplePanel.add(scrollPanel);
scrollPanel.add(widget);
} else {
simplePanel.clear();
simplePanel.add(widget);
}
}
public GwtTree() {
super("tree");
// managedObject is neither a native GWT tree nor a table since the entire native GWT object is thrown away each
// time we call setup{Tree|Table}; because the widget is thrown away, we need to reconnect the new widget to the
// simplePanel, which is the managedObject
managedObject = simplePanel;
}
public void init(com.google.gwt.xml.client.Element srcEle, XulDomContainer container) {
super.init(srcEle, container);
setOnselect(srcEle.getAttribute("onselect"));
setOnedit(srcEle.getAttribute("onedit"));
setSeltype(srcEle.getAttribute("seltype"));
this.setEditable("true".equals(srcEle.getAttribute("editable")));
this.domContainer = container;
}
public void addChild(Element element) {
super.addChild(element);
if (element.getName().equals("treecols")) {
columns = (XulTreeCols)element;
} else if (element.getName().equals("treechildren")) {
rootChildren = (XulTreeChildren)element;
}
}
public void addTreeRow(XulTreeRow row) {
GwtTreeItem item = new GwtTreeItem();
item.setRow(row);
this.rootChildren.addItem(item);
// update UI
updateUI();
}
private BaseTable table;
private boolean isHierarchical = false;
private boolean firstLayout = true;
// need to handle layouting
public void layout() {
if(this.getRootChildren() == null){
//most likely an overlay
return;
}
if(firstLayout){
XulTreeItem item = (XulTreeItem) this.getRootChildren().getFirstChild();
if(item != null && item.getAttributeValue("container") != null && item.getAttributeValue("container").equals("true")){
isHierarchical = true;
}
firstLayout = false;
}
if(isHierarchical()){
setupTree();
} else {
setupTable();
}
setVisible(visible);
}
private int prevSelectionPos = -1;
private void setupTree(){
if(tree == null){
tree = new Tree();
setWidgetInPanel(tree);
}
scrollPanel.setWidth("100%"); //$NON-NLS-1$
scrollPanel.setHeight("100%"); //$NON-NLS-1$
scrollPanel.getElement().getStyle().setProperty("backgroundColor", "white"); //$NON-NLS-1$//$NON-NLS-2$
if (getWidth() > 0){
scrollPanel.setWidth(getWidth()+"px"); //$NON-NLS-1$
}
if (getHeight() > 0) {
scrollPanel.setHeight(getHeight()+"px"); //$NON-NLS-1$
}
tree.addTreeListener(new TreeListener(){
public void onTreeItemSelected(TreeItem arg0) {
int pos = -1;
int curPos = 0;
for(int i=0; i < tree.getItemCount(); i++){
TreeItem tItem = tree.getItem(i);
TreeCursor cursor = GwtTree.this.findPosition(tItem, arg0, curPos);
pos = cursor.foundPosition;
curPos = cursor.curPos+1;
if(pos > -1){
break;
}
}
if(pos > -1 && GwtTree.this.suppressEvents == false && prevSelectionPos != pos){
GwtTree.this.changeSupport.firePropertyChange("selectedRows",null,new int[]{pos});
}
prevSelectionPos = pos;
}
public void onTreeItemStateChanged(TreeItem arg0) {
}
});
updateUI();
}
private class TreeCursor{
int foundPosition = -1;
int curPos;
TreeItem itemToFind;
public TreeCursor(int curPos, TreeItem itemToFind, int foundPosition){
this.foundPosition = foundPosition;
this.curPos = curPos;
this.itemToFind = itemToFind;
}
}
private TreeCursor findPosition(TreeItem curItem, TreeItem itemToFind, int curPos){
if(curItem == itemToFind){
TreeCursor p = new TreeCursor(curPos, itemToFind, curPos);
return p;
} else if(curItem.getChildIndex(itemToFind) > -1) {
curPos = curPos+1;
return new TreeCursor(curPos, itemToFind, curItem.getChildIndex(itemToFind)+curPos);
} else {
for(int i=0; i<curItem.getChildCount(); i++){
TreeCursor p;
if((p = findPosition(curItem.getChild(i), itemToFind, curPos +i)).foundPosition > -1){
return p;
}
}
curPos += curItem.getChildCount() ;
return new TreeCursor(curPos, itemToFind, -1);
}
}
private void populateTree(){
tree.removeItems();
TreeItem topNode = new TreeItem("placeholder");
if(this.rootChildren == null){
this.rootChildren = (XulTreeChildren) this.getChildNodes().get(1);
}
for (XulComponent c : this.rootChildren.getChildNodes()){
XulTreeItem item = (XulTreeItem) c;
TreeItem node = createNode(item);
tree.addItem(node);
}
}
private void populateTable(){
Object data[][] = new Object[getRootChildren().getItemCount()][getColumns().getColumnCount()];
for (int i = 0; i < getRootChildren().getItemCount(); i++) {
for (int j = 0; j < getColumns().getColumnCount(); j++) {
// String label = getRootChildren().getItem(i).getRow().getCell(j).getLabel();
// if(label == null || label.equals("")){
// label = " ";
data[i][j] = getColumnEditor(j,i);
}
}
if (getHeight() != 0) {
table.setTableHeight(getHeight() + "px");
}
if (getWidth() != 0) {
table.setTableWidth(getWidth() + "px");
}
table.populateTable(data);
ResizableWidgetCollection.get().setResizeCheckingEnabled(false);
}
private TreeItem createNode(XulTreeItem item){
TreeItem node = new TreeItem(item.getRow().getCell(0).getLabel());
if(item.getChildNodes().size() > 1){
//has children
//TODO: make this more defensive
XulTreeChildren children = (XulTreeChildren) item.getChildNodes().get(1);
for(XulComponent c : children.getChildNodes()){
TreeItem childNode = createNode((XulTreeItem) c);
node.addItem(childNode);
}
}
return node;
}
private String extractDynamicColType(Object row, int columnPos) {
GwtBindingMethod method = GwtBindingContext.typeController.findGetMethod(row, this.columns.getColumn(columnPos).getColumntypebinding());
try{
return (String) method.invoke(row, new Object[]{});
} catch (Exception e){
System.out.println("Could not extract column type from binding");
}
return "text"; // default //$NON-NLS-1$
}
private Widget getColumnEditor(final int x, final int y){
final XulTreeCol column = this.columns.getColumn(x);
String colType = this.columns.getColumn(x).getType();
String val = getRootChildren().getItem(y).getRow().getCell(x).getLabel();
final GwtTreeCell cell = (GwtTreeCell) getRootChildren().getItem(y).getRow().getCell(x);
if(StringUtils.isEmpty(colType) == false && colType.equalsIgnoreCase("dynamic")){
Object row = elements.toArray()[y];
colType = extractDynamicColType(row, x);
}
if(StringUtils.isEmpty(colType) || !column.isEditable()){
return new HTML(val);
} else if(colType.equalsIgnoreCase("text")){
try{
GwtTextbox b = (GwtTextbox) this.domContainer.getDocumentRoot().createElement("textbox");
b.setDisabled(!column.isEditable());
b.layout();
b.setValue(val);
GwtBinding bind = new GwtBinding(cell, "label", b, "value");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
bind = new GwtBinding(cell, "disabled", b, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return (Widget) b.getManagedObject();
} catch(Exception e){
System.out.println("error creating textbox, fallback");
e.printStackTrace();
final TextBox b = new TextBox();
b.addKeyboardListener(new KeyboardListener(){
public void onKeyDown(Widget arg0, char arg1, int arg2) {}
public void onKeyPress(Widget arg0, char arg1, int arg2) {}
public void onKeyUp(Widget arg0, char arg1, int arg2) {
getRootChildren().getItem(y).getRow().getCell(x).setLabel(b.getText());
}
});
b.setText(val);
return b;
}
} else if(colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox")){
final CustomListBox lb = new CustomListBox();
lb.setWidth("100%");
Vector vals = (Vector) cell.getValue();
lb.setSuppressLayout(true);
for(Object label : vals){
lb.addItem(label.toString());
}
lb.setSuppressLayout(false);
lb.addChangeListener(new ChangeListener(){
public void onChange(Widget arg0) {
if(column.getType().equalsIgnoreCase("editablecombobox")){
cell.setLabel(lb.getValue());
} else {
cell.setSelectedIndex(lb.getSelectedIndex());
}
}
});
int idx = cell.getSelectedIndex();
if(idx < 0){
idx = 0;
}
if(idx < vals.size()){
lb.setSelectedIndex(idx);
}
if(colType.equalsIgnoreCase("editablecombobox")){
lb.setEditable(true);
}
return lb;
} else {
if(val == null || val.equals("")){
return new HTML(" ");
}
return new HTML(val);
}
}
private void setupTable(){
String cols[] = new String[getColumns().getColumnCount()];
int len[] = new int[cols.length];
// for each column
int totalFlex = 0;
for (int i = 0; i < cols.length; i++) {
totalFlex += getColumns().getColumn(i).getFlex();
}
for (int i = 0; i < cols.length; i++) {
cols[i] = getColumns().getColumn(i).getLabel();
if(totalFlex > 0 && getWidth() > 0){
len[i] = (int) (getWidth() * ((double) getColumns().getColumn(i).getFlex() / totalFlex)) - 15;
}
}
// use base table from pentaho widgets library for now
SelectionPolicy policy = SelectionPolicy.DISABLED;
if ("single".equals(getSeltype())) {
policy = SelectionPolicy.ONE_ROW;
} else if ("multiple".equals(getSeltype())) {
policy = SelectionPolicy.MULTI_ROW;
}
int[] colWidths = (getWidth() > 0 && totalFlex > 0) ? len : null;
table = new BaseTable(cols, colWidths, new BaseColumnComparator[cols.length], policy);
table.addTableSelectionListener(new TableSelectionListener() {
public void onAllRowsDeselected(SourceTableSelectionEvents sender) {
}
public void onCellHover(SourceTableSelectionEvents sender, int row, int cell) {
}
public void onCellUnhover(SourceTableSelectionEvents sender, int row, int cell) {
}
public void onRowDeselected(SourceTableSelectionEvents sender, int row) {
}
public void onRowHover(SourceTableSelectionEvents sender, int row) {
}
public void onRowUnhover(SourceTableSelectionEvents sender, int row) {
}
public void onRowsSelected(SourceTableSelectionEvents sender, int firstRow, int numRows) {
try {
if (getOnselect() != null && getOnselect().trim().length() > 0) {
getXulDomContainer().invoke(getOnselect(), new Object[]{});
}
Integer[] selectedRows = table.getSelectedRows().toArray(new Integer[table.getSelectedRows().size()]);
//set.toArray(new Integer[]) doesn't unwrap ><
int[] rows = new int[selectedRows.length];
for(int i=0; i<selectedRows.length; i++){
rows[i] = selectedRows[i];
}
GwtTree.this.setSelectedRows(rows);
} catch (XulException e) {
e.printStackTrace();
}
}
});
setWidgetInPanel(table);
table.setTableWidth("100%"); //$NON-NLS-1$
table.setTableHeight("100%"); //$NON-NLS-1$
if (getWidth() > 0){
table.setTableWidth(getWidth()+"px"); //$NON-NLS-1$
}
if (getHeight() > 0) {
table.setTableHeight(getHeight()+"px"); //$NON-NLS-1$
}
updateUI();
}
public void updateUI() {
if(this.isHierarchical()){
populateTree();
} else {
populateTable();
};
// if(this.suppressEvents == false){
// changeSupport.firePropertyChange("selectedRows", null, getSelectedRows());
}
public void afterLayout() {
updateUI();
}
public void clearSelection() {
// TODO Auto-generated method stub
}
public int[] getActiveCellCoordinates() {
// TODO Auto-generated method stub
return null;
}
public XulTreeCols getColumns() {
return columns;
}
public Object getData() {
// TODO Auto-generated method stub
return null;
}
public <T> Collection<T> getElements() {
// TODO Auto-generated method stub
return null;
}
public String getOnedit() {
return getAttributeValue("onedit");
}
public String getOnselect() {
return getAttributeValue("onselect");
}
public XulTreeChildren getRootChildren() {
return rootChildren;
}
public int getRows() {
if (rootChildren == null) {
return 0;
} else {
return rootChildren.getItemCount();
}
}
public int[] getSelectedRows() {
if(this.isHierarchical()){
TreeItem item = tree.getSelectedItem();
for(int i=0; i <tree.getItemCount(); i++){
if(tree.getItem(i) == item){
return new int[]{i};
}
}
return new int[]{};
} else {
if (table == null) {
return new int[0];
}
Set<Integer> rows = table.getSelectedRows();
int rarr[] = new int[rows.size()];
int i = 0;
for (Integer v : rows) {
rarr[i++] = v;
}
return rarr;
}
}
private int[] selectedRows;
public void setSelectedRows(int[] rows) {
if (table == null) {
// this only works after the table has been materialized
return;
}
int[] prevSelected = selectedRows;
selectedRows = rows;;
for (int r : rows) {
table.selectRow(r);
}
if(this.suppressEvents == false && Arrays.equals(selectedRows, prevSelected) == false){
this.changeSupport.firePropertyChange("selectedRows", prevSelected, rows);
}
}
public String getSeltype() {
return getAttributeValue("seltype");
}
public Object[][] getValues() {
// TODO Auto-generated method stub
return null;
}
public boolean isEditable() {
return editable;
}
public boolean isEnableColumnDrag() {
// TODO Auto-generated method stub
return false;
}
public boolean isHierarchical() {
return isHierarchical;
}
public void removeTreeRows(int[] rows) {
// sort the rows high to low
ArrayList<Integer> rowArray = new ArrayList<Integer>();
for (int i = 0; i < rows.length; i++) {
rowArray.add(rows[i]);
}
Collections.sort(rowArray, Collections.reverseOrder());
// remove the items in that order
for (int i = 0; i < rowArray.size(); i++) {
int item = rowArray.get(i);
if (item >= 0 && item < rootChildren.getItemCount()) {
this.rootChildren.removeItem(item);
}
}
updateUI();
}
public void setActiveCellCoordinates(int row, int column) {
// TODO Auto-generated method stub
}
public void setColumns(XulTreeCols columns) {
if (getColumns() != null) {
this.removeChild(getColumns());
}
addChild(columns);
}
public void setData(Object data) {
// TODO Auto-generated method stub
}
public void setEditable(boolean edit) {
this.editable = edit;
}
public <T> void setElements(Collection<T> elements) {
try{
this.elements = elements;
suppressEvents = true;
this.getRootChildren().removeAll();
if(elements == null || elements.size() == 0){
updateUI();
return;
}
try {
if(table != null){
for (T o : elements) {
XulTreeRow row = this.getRootChildren().addNewRow();
for (int x=0; x< this.getColumns().getChildNodes().size(); x++) {
XulComponent col = this.getColumns().getColumn(x);
XulTreeCol column = ((XulTreeCol) col);
final XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell");
for (InlineBindingExpression exp : column.getBindingExpressions()) {
String colType = column.getType();
if(StringUtils.isEmpty(colType) == false && colType.equalsIgnoreCase("dynamic")){
colType = extractDynamicColType(o, x);
}
if(colType != null && (colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox"))){
GwtBinding binding = new GwtBinding(o, column.getCombobinding(), cell, "value");
binding.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(binding);
binding.fireSourceChanged();
binding = new GwtBinding(o, ((XulTreeCol) col).getBinding(), cell, "selectedIndex");
binding.setConversion(new BindingConvertor<Object, Integer>(){
@Override
public Integer sourceToTarget(Object value) {
int index = ((Vector) cell.getValue()).indexOf(value);
return index > -1 ? index : 0;
}
@Override
public Object targetToSource(Integer value) {
return ((Vector)cell.getValue()).get(value);
}
});
domContainer.addBinding(binding);
binding.fireSourceChanged();
if(colType.equalsIgnoreCase("editablecombobox")){
binding = new GwtBinding(o, exp.getModelAttr(), cell, exp.getXulCompAttr());
if (!this.editable) {
binding.setBindingType(Binding.Type.ONE_WAY);
} else {
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
}
domContainer.addBinding(binding);
}
} else if(o instanceof XulEventSource && StringUtils.isEmpty(exp.getModelAttr()) == false){
GwtBinding binding = new GwtBinding(o, exp.getModelAttr(), cell, exp.getXulCompAttr());
if(column.isEditable() == false){
binding.setBindingType(Binding.Type.ONE_WAY);
}
domContainer.addBinding(binding);
binding.fireSourceChanged();
} else {
cell.setLabel(o.toString());
}
}
if(StringUtils.isEmpty(column.getDisabledbinding()) == false){
String prop = column.getDisabledbinding();
GwtBinding bind = new GwtBinding(o, column.getDisabledbinding(), cell, "disabled");
bind.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(bind);
bind.fireSourceChanged();
}
row.addCell(cell);
}
}
} else { //tree
for (T o : elements) {
XulTreeRow row = this.getRootChildren().addNewRow();
addTreeChild(o, row);
}
}
//treat as a selection change
} catch (XulException e) {
Window.alert("error adding elements "+e);
System.out.println(e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Window.alert("error adding elements "+e);
System.out.println(e.getMessage());
e.printStackTrace();
}
suppressEvents = false;
updateUI();
} catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private <T> void addTreeChild(T element, XulTreeRow row){
try{
XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell");
for (InlineBindingExpression exp : ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getBindingExpressions()) {
GwtBinding binding = new GwtBinding(element, exp.getModelAttr(), cell, exp.getXulCompAttr());
binding.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(binding);
binding.fireSourceChanged();
}
row.addCell(cell);
//find children
String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding();
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(element, property);
Collection<T> children = (Collection<T>) childrenMethod.invoke(element, new Object[]{});
XulTreeChildren treeChildren = null;
if(children != null && children.size() > 0){
treeChildren = (XulTreeChildren) getDocument().createElement("treechildren");
row.getParent().addChild(treeChildren);
}
for(T child : children){
row = treeChildren.addNewRow();
addTreeChild(child, row);
}
} catch (Exception e) {
Window.alert("error adding elements "+e.getMessage());
e.printStackTrace();
}
}
public void setEnableColumnDrag(boolean drag) {
// TODO Auto-generated method stub
}
public void setOnedit(String onedit) {
this.setAttribute("onedit", onedit);
}
public void setOnselect(String select) {
this.setAttribute("onselect", select);
}
public void setRootChildren(XulTreeChildren rootChildren) {
if (getRootChildren() != null) {
this.removeChild(getRootChildren());
}
addChild(rootChildren);
}
public void setRows(int rows) {
// TODO Auto-generated method stub
}
public void setSeltype(String type) {
// TODO Auto-generated method stub
// SINGLE, CELL, MULTIPLE, NONE
this.setAttribute("seltype", type);
}
public void update() {
updateUI();
layout();
}
public void adoptAttributes(XulComponent component) {
super.adoptAttributes(component);
}
public Object getSelectedItem() {
// TODO Auto-generated method stub
return null;
}
}
|
package org.pentaho.ui.xul.gwt.tags;
import com.allen_sauer.gwt.dnd.client.DragContext;
import com.allen_sauer.gwt.dnd.client.VetoDragException;
import com.allen_sauer.gwt.dnd.client.drop.AbstractPositioningDropController;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.widgetideas.table.client.SelectionGrid.SelectionPolicy;
import com.google.gwt.widgetideas.table.client.SourceTableSelectionEvents;
import com.google.gwt.widgetideas.table.client.TableSelectionListener;
import org.pentaho.gwt.widgets.client.buttons.ImageButton;
import org.pentaho.gwt.widgets.client.listbox.CustomListBox;
import org.pentaho.gwt.widgets.client.table.BaseTable;
import org.pentaho.gwt.widgets.client.table.ColumnComparators.BaseColumnComparator;
import org.pentaho.gwt.widgets.client.ui.Draggable;
import org.pentaho.gwt.widgets.client.utils.string.StringUtils;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulEventSource;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.binding.Binding;
import org.pentaho.ui.xul.binding.BindingConvertor;
import org.pentaho.ui.xul.binding.InlineBindingExpression;
import org.pentaho.ui.xul.components.XulTreeCell;
import org.pentaho.ui.xul.components.XulTreeCol;
import org.pentaho.ui.xul.containers.*;
import org.pentaho.ui.xul.dnd.DataTransfer;
import org.pentaho.ui.xul.dnd.DropEvent;
import org.pentaho.ui.xul.dnd.DropPosition;
import org.pentaho.ui.xul.dom.Document;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.gwt.AbstractGwtXulContainer;
import org.pentaho.ui.xul.gwt.GwtXulHandler;
import org.pentaho.ui.xul.gwt.GwtXulParser;
import org.pentaho.ui.xul.gwt.binding.GwtBinding;
import org.pentaho.ui.xul.gwt.binding.GwtBindingContext;
import org.pentaho.ui.xul.gwt.binding.GwtBindingMethod;
import org.pentaho.ui.xul.gwt.tags.util.TreeItemWidget;
import org.pentaho.ui.xul.gwt.util.Resizable;
import org.pentaho.ui.xul.gwt.util.XulDragController;
import org.pentaho.ui.xul.impl.XulEventHandler;
import org.pentaho.ui.xul.stereotype.Bindable;
import org.pentaho.ui.xul.util.TreeCellEditor;
import org.pentaho.ui.xul.util.TreeCellEditorCallback;
import org.pentaho.ui.xul.util.TreeCellRenderer;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class GwtTree extends AbstractGwtXulContainer implements XulTree, Resizable {
/**
* Cached elements.
*/
private Collection elements;
private GwtBindingMethod dropVetoerMethod;
private XulEventHandler dropVetoerController;
public static void register() {
GwtXulParser.registerHandler("tree",
new GwtXulHandler() {
public Element newInstance() {
return new GwtTree();
}
});
}
XulTreeCols columns = null;
XulTreeChildren rootChildren = null;
private XulDomContainer domContainer;
private Tree tree;
private boolean suppressEvents = false;
private boolean editable = false;
private boolean visible = true;
private String command;
private Map<String, TreeCellEditor> customEditors = new HashMap<String, TreeCellEditor>();
private Map<String, TreeCellRenderer> customRenderers = new HashMap<String, TreeCellRenderer>();
private List<Binding> elementBindings = new ArrayList<Binding>();
private List<Binding> expandBindings = new ArrayList<Binding>();
private DropPositionIndicator dropPosIndicator = new DropPositionIndicator();
private boolean showAllEditControls = true;
@Bindable
public boolean isVisible() {
return visible;
}
@Bindable
public void setVisible(boolean visible) {
this.visible = visible;
if(simplePanel != null) {
simplePanel.setVisible(visible);
}
}
/**
* Used when this widget is a tree. Not used when this widget is a table.
*/
private FlowPanel scrollPanel = new FlowPanel();
{
scrollPanel.setStylePrimaryName("scroll-panel");
}
/**
* The managed object. If this widget is a tree, then the tree is added to the scrollPanel, which is added to this
* simplePanel. If this widget is a table, then the table is added directly to this simplePanel.
*/
private SimplePanel simplePanel = new SimplePanel();
/**
* Clears the parent panel and adds the given widget.
* @param widget tree or table to set in parent panel
*/
protected void setWidgetInPanel(final Widget widget) {
if (isHierarchical()) {
scrollPanel.clear();
simplePanel.add(scrollPanel);
scrollPanel.add(widget);
scrollPanel.add(dropPosIndicator);
} else {
simplePanel.clear();
simplePanel.add(widget);
}
}
public GwtTree() {
super("tree");
// managedObject is neither a native GWT tree nor a table since the entire native GWT object is thrown away each
// time we call setup{Tree|Table}; because the widget is thrown away, we need to reconnect the new widget to the
// simplePanel, which is the managedObject
setManagedObject(simplePanel);
}
public void init(com.google.gwt.xml.client.Element srcEle, XulDomContainer container) {
super.init(srcEle, container);
setOnselect(srcEle.getAttribute("onselect"));
setOnedit(srcEle.getAttribute("onedit"));
setSeltype(srcEle.getAttribute("seltype"));
setOndrop(srcEle.getAttribute("pen:ondrop"));
setOndrag(srcEle.getAttribute("pen:ondrag"));
setDrageffect(srcEle.getAttribute("pen:drageffect"));
setDropvetoer(srcEle.getAttribute("pen:dropvetoer"));
if(StringUtils.isEmpty(srcEle.getAttribute("pen:showalleditcontrols")) == false){
this.setShowalleditcontrols(srcEle.getAttribute("pen:showalleditcontrols").equals("true"));
}
this.setEditable("true".equals(srcEle.getAttribute("editable")));
this.domContainer = container;
}
private List<TreeItemDropController> dropHandlers = new ArrayList<TreeItemDropController>();
public void addChild(Element element) {
super.addChild(element);
if (element.getName().equals("treecols")) {
columns = (XulTreeCols)element;
} else if (element.getName().equals("treechildren")) {
rootChildren = (XulTreeChildren)element;
}
}
public void addTreeRow(XulTreeRow row) {
GwtTreeItem item = new GwtTreeItem();
item.setRow(row);
this.rootChildren.addItem(item);
// update UI
updateUI();
}
private BaseTable table;
private boolean isHierarchical = false;
private boolean firstLayout = true;
private Object[][] currentData;
// need to handle layouting
public void layout() {
if(this.getRootChildren() == null){
//most likely an overlay
return;
}
if(firstLayout){
XulTreeItem item = (XulTreeItem) this.getRootChildren().getFirstChild();
if(item != null && item.getAttributeValue("container") != null && item.getAttributeValue("container").equals("true")){
isHierarchical = true;
}
firstLayout = false;
}
if(isHierarchical()){
setupTree();
} else {
setupTable();
}
setVisible(visible);
}
private int prevSelectionPos = -1;
private void setupTree(){
if(tree == null){
tree = new Tree();
setWidgetInPanel(tree);
}
scrollPanel.setWidth("100%"); //$NON-NLS-1$
scrollPanel.setHeight("100%"); //$NON-NLS-1$
scrollPanel.getElement().getStyle().setProperty("backgroundColor", "white"); //$NON-NLS-1$//$NON-NLS-2$
if (getWidth() > 0){
scrollPanel.setWidth(getWidth()+"px"); //$NON-NLS-1$
}
if (getHeight() > 0) {
scrollPanel.setHeight(getHeight()+"px"); //$NON-NLS-1$
}
tree.addTreeListener(new TreeListener(){
public void onTreeItemSelected(TreeItem arg0) {
int pos = -1;
int curPos = 0;
for(int i=0; i < tree.getItemCount(); i++){
TreeItem tItem = tree.getItem(i);
TreeCursor cursor = GwtTree.this.findPosition(tItem, arg0, curPos);
pos = cursor.foundPosition;
curPos = cursor.curPos+1;
if(pos > -1){
break;
}
}
if(pos > -1 && GwtTree.this.suppressEvents == false && prevSelectionPos != pos){
GwtTree.this.changeSupport.firePropertyChange("selectedRows",null,new int[]{pos});
GwtTree.this.changeSupport.firePropertyChange("absoluteSelectedRows",null,new int[]{pos});
GwtTree.this.fireSelectedItems();
}
prevSelectionPos = pos;
}
public void onTreeItemStateChanged(TreeItem item) {
((TreeItemWidget) item.getWidget()).getTreeItem().setExpanded(item.getState());
}
});
updateUI();
}
private class TreeCursor{
int foundPosition = -1;
int curPos;
TreeItem itemToFind;
public TreeCursor(int curPos, TreeItem itemToFind, int foundPosition){
this.foundPosition = foundPosition;
this.curPos = curPos;
this.itemToFind = itemToFind;
}
}
private TreeCursor findPosition(TreeItem curItem, TreeItem itemToFind, int curPos){
if(curItem == itemToFind){
TreeCursor p = new TreeCursor(curPos, itemToFind, curPos);
return p;
// } else if(curItem.getChildIndex(itemToFind) > -1) {
// curPos = curPos+1;
// return new TreeCursor(curPos+curItem.getChildIndex(itemToFind) , itemToFind, curPos+curItem.getChildIndex(itemToFind));
} else {
for(int i=1; i-1<curItem.getChildCount(); i++){
TreeCursor p = findPosition(curItem.getChild(i-1), itemToFind, curPos +1);
curPos = p.curPos;
if(p.foundPosition > -1){
return p;
}
}
//curPos += curItem.getChildCount() ;
return new TreeCursor(curPos, itemToFind, -1);
}
}
private void populateTree(){
tree.removeItems();
TreeItem topNode = new TreeItem("placeholder");
if(this.rootChildren == null){
this.rootChildren = (XulTreeChildren) this.children.get(1);
}
for (XulComponent c : this.rootChildren.getChildNodes()){
XulTreeItem item = (XulTreeItem) c;
TreeItem node = createNode(item);
tree.addItem(node);
}
if(StringUtils.isEmpty(this.ondrag) == false){
for (int i = 0; i < tree.getItemCount(); i++) {
madeDraggable(tree.getItem(i));
}
}
}
private void madeDraggable(TreeItem item){
XulDragController.getInstance().makeDraggable(item.getWidget());
for (int i = 0; i < item.getChildCount(); i++) {
madeDraggable(item.getChild(i));
}
}
private List<XulComponent> colCollection = new ArrayList<XulComponent>();
private void populateTable(){
int rowCount = getRootChildren().getItemCount();
// Getting column editors ends up calling getChildNodes several times. we're going to cache the column collections
// for the duration of the operation then clear it out.
colCollection = getColumns().getChildNodes();
int colCount = colCollection.size();
currentData = new Object[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
currentData[i][j] = getColumnEditor(j,i);
}
}
table.populateTable(currentData);
int totalFlex = 0;
for (int i = 0; i < colCount; i++) {
totalFlex += colCollection.get(i).getFlex();
}
if(totalFlex > 0){
table.fillWidth();
}
colCollection = new ArrayList<XulComponent>();
if(this.selectedRows != null && this.selectedRows.length > 0){
for(int i=0; i<this.selectedRows.length; i++){
int idx = this.selectedRows[i];
if(idx > -1 && idx < currentData.length){
table.selectRow(idx);
}
}
}
}
private TreeItem createNode(final XulTreeItem item){
TreeItem node = new TreeItem("empty"){
@Override
public void setSelected( boolean selected ) {
super.setSelected(selected);
if(selected){
this.getWidget().addStyleDependentName("selected");
} else {
this.getWidget().removeStyleDependentName("selected");
}
}
};
item.setManagedObject(node);
if(item == null || item.getRow() == null || item.getRow().getChildNodes().size() == 0){
return node;
}
final TreeItemWidget tWidget = new TreeItemWidget(item);
PropertyChangeListener listener = new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("image") && item.getImage() != null){
tWidget.setImage(new Image(GWT.getModuleBaseURL() + item.getImage()));
} else if(evt.getPropertyName().equals("label")){
tWidget.setLabel(item.getRow().getCell(0).getLabel());
}
}
};
((GwtTreeItem) item).addPropertyChangeListener("image", listener);
((GwtTreeCell) item.getRow().getCell(0)).addPropertyChangeListener("label", listener);;
if (item.getImage() != null) {
tWidget.setImage(new Image(GWT.getModuleBaseURL() + item.getImage()));
}
tWidget.setLabel(item.getRow().getCell(0).getLabel());
if(this.ondrop != null){
TreeItemDropController controller = new TreeItemDropController(item, tWidget);
XulDragController.getInstance().registerDropController(controller);
this.dropHandlers.add(controller);
}
node.setWidget(tWidget);
if(item.getChildNodes().size() > 1){
//has children
//TODO: make this more defensive
XulTreeChildren children = (XulTreeChildren) item.getChildNodes().get(1);
for(XulComponent c : children.getChildNodes()){
TreeItem childNode = createNode((XulTreeItem) c);
node.addItem(childNode);
}
}
return node;
}
private String extractDynamicColType(Object row, int columnPos) {
GwtBindingMethod method = GwtBindingContext.typeController.findGetMethod(row, this.columns.getColumn(columnPos).getColumntypebinding());
try{
return (String) method.invoke(row, new Object[]{});
} catch (Exception e){
System.out.println("Could not extract column type from binding");
}
return "text"; // default //$NON-NLS-1$
}
private Binding createBinding(XulEventSource source, String prop1, XulEventSource target, String prop2){
if(bindingProvider != null){
return bindingProvider.getBinding(source, prop1, target, prop2);
}
return new GwtBinding(source, prop1, target, prop2);
}
private Widget getColumnEditor(final int x, final int y){
final XulTreeCol column = (XulTreeCol) colCollection.get(x);
String colType = ((XulTreeCol) colCollection.get(x)).getType();
final GwtTreeCell cell = (GwtTreeCell) getRootChildren().getItem(y).getRow().getCell(x);
String val = cell.getLabel();
// If collection bound, bindings may need to be updated for runtime changes in column types.
if(this.elements != null){
try {
this.addBindings(column, cell, this.elements.toArray()[y]);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (XulException e) {
e.printStackTrace();
}
}
if(StringUtils.isEmpty(colType) == false && colType.equalsIgnoreCase("dynamic")){
Object row = elements.toArray()[y];
colType = extractDynamicColType(row, x);
}
int[] selectedRows = getSelectedRows();
if((StringUtils.isEmpty(colType) || !column.isEditable()) || ((showAllEditControls == false && (selectedRows.length != 1 || selectedRows[0] != y)) && !colType.equals("checkbox"))){
if(colType != null && (colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox"))){
Vector vals = (Vector) cell.getValue();
int idx = cell.getSelectedIndex();
if(colType.equalsIgnoreCase("editablecombobox")){
return new HTML(cell.getLabel());
} else if(idx < vals.size()){
return new HTML(""+vals.get(idx));
} else {
return new HTML("");
}
} else {
return new HTML(val);
}
} else if(colType.equalsIgnoreCase("text")){
try{
GwtTextbox b = (GwtTextbox) this.domContainer.getDocumentRoot().createElement("textbox");
b.setDisabled(!column.isEditable());
b.layout();
b.setValue(val);
Binding bind = createBinding(cell, "label", b, "value");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
bind = createBinding(cell, "disabled", b, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return (Widget) b.getManagedObject();
} catch(Exception e){
System.out.println("error creating textbox, fallback");
e.printStackTrace();
final TextBox b = new TextBox();
b.addKeyboardListener(new KeyboardListener(){
public void onKeyDown(Widget arg0, char arg1, int arg2) {}
public void onKeyPress(Widget arg0, char arg1, int arg2) {}
public void onKeyUp(Widget arg0, char arg1, int arg2) {
getRootChildren().getItem(y).getRow().getCell(x).setLabel(b.getText());
}
});
b.setText(val);
return b;
}
} else if (colType.equalsIgnoreCase("checkbox")) {
try {
GwtCheckbox checkBox = (GwtCheckbox) this.domContainer.getDocumentRoot().createElement("checkbox");
checkBox.setDisabled(!column.isEditable());
checkBox.layout();
checkBox.setChecked(Boolean.parseBoolean(val));
Binding bind = createBinding(cell, "value", checkBox, "checked");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
bind = createBinding(cell, "disabled", checkBox, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return (Widget)checkBox.getManagedObject();
} catch (Exception e) {
final CheckBox cb = new CheckBox();
return cb;
}
} else if(colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox")){
try{
final GwtMenuList glb = (GwtMenuList) this.domContainer.getDocumentRoot().createElement("menulist");
final CustomListBox lb = glb.getNativeListBox();
lb.setWidth("100%");
final String fColType = colType;
// Binding to elements of listbox not giving us the behavior we want. Menulists select the first available
// item by default. We don't want anything selected by default in these cell editors
PropertyChangeListener listener = new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent evt) {
Vector vals = (Vector) cell.getValue();
lb.clear();
lb.setSuppressLayout(true);
for(Object label : vals){
lb.addItem(label.toString());
}
lb.setSuppressLayout(false);
int idx = cell.getSelectedIndex();
if(idx < 0){
idx = 0;
}
if(idx < vals.size()){
lb.setSelectedIndex(idx);
}
if(fColType.equalsIgnoreCase("editablecombobox")){
lb.setValue("");
}
}
};
listener.propertyChange(null);
cell.addPropertyChangeListener("value", listener);
lb.addChangeListener(new ChangeListener(){
public void onChange(Widget arg0) {
if(fColType.equalsIgnoreCase("editablecombobox")){
cell.setLabel(lb.getValue());
} else {
cell.setSelectedIndex(lb.getSelectedIndex());
}
}
});
if(colType.equalsIgnoreCase("editablecombobox")){
lb.setEditable(true);
Binding bind = createBinding(cell, "selectedIndex", glb, "selectedIndex");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
if(cell.getLabel() == null){
bind.fireSourceChanged();
}
bind = createBinding(cell, "label", glb, "value");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
} else {
Binding bind = createBinding(cell, "selectedIndex", glb, "selectedIndex");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
}
Binding bind = createBinding(cell, "disabled", glb, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return lb;
} catch(Exception e){
System.out.println("error creating menulist, fallback");
final String fColType = colType;
e.printStackTrace();
final CustomListBox lb = new CustomListBox();
lb.setWidth("100%");
Vector vals = (Vector) cell.getValue();
lb.setSuppressLayout(true);
for(Object label : vals){
lb.addItem(label.toString());
}
lb.setSuppressLayout(false);
lb.addChangeListener(new ChangeListener(){
public void onChange(Widget arg0) {
if(fColType.equalsIgnoreCase("editablecombobox")){
cell.setLabel(lb.getValue());
} else {
cell.setSelectedIndex(lb.getSelectedIndex());
}
}
});
int idx = cell.getSelectedIndex();
if(idx < 0){
idx = 0;
}
if(idx < vals.size()){
lb.setSelectedIndex(idx);
}
if(fColType.equalsIgnoreCase("editablecombobox")){
lb.setEditable(true);
}
lb.setValue(cell.getLabel());
return lb;
}
} else if (colType != null && customEditors.containsKey(colType)){
if(this.customRenderers.containsKey(colType)){
return new CustomCellEditorWrapper(cell, customEditors.get(colType), customRenderers.get(colType));
} else {
return new CustomCellEditorWrapper(cell, customEditors.get(colType));
}
} else {
if(val == null || val.equals("")){
return new HTML(" ");
}
return new HTML(val);
}
}
private int curSelectedRow = -1;
private void setupTable(){
List<XulComponent> colCollection = getColumns().getChildNodes();
String cols[] = new String[colCollection.size()];
SelectionPolicy selectionPolicy = null;
if ("single".equals(getSeltype())) {
selectionPolicy = SelectionPolicy.ONE_ROW;
} else if ("multiple".equals(getSeltype())) {
selectionPolicy = SelectionPolicy.MULTI_ROW;
}
int[] widths = new int[cols.length];
int totalFlex = 0;
for (int i = 0; i < cols.length; i++) {
totalFlex += colCollection.get(i).getFlex();
}
for (int i = 0; i < cols.length; i++) {
cols[i] = ((XulTreeCol) colCollection.get(i)).getLabel();
if(totalFlex > 0 && getWidth() > 0){
widths[i] = (int) (getWidth() * ((double) colCollection.get(i).getFlex() / totalFlex));
} else if(getColumns().getColumn(i).getWidth() > 0){
widths[i] = getColumns().getColumn(i).getWidth();
}
}
table = new BaseTable(cols, widths, new BaseColumnComparator[cols.length], selectionPolicy);
if (getHeight() != 0) {
table.setHeight(getHeight() + "px");
} else {
table.setHeight("100%");
}
if (getWidth() != 0) {
table.setWidth(getWidth() + "px");
} else {
table.setWidth("100%");
}
table.addTableSelectionListener(new TableSelectionListener() {
public void onAllRowsDeselected(SourceTableSelectionEvents sender) {
}
public void onCellHover(SourceTableSelectionEvents sender, int row, int cell) {
}
public void onCellUnhover(SourceTableSelectionEvents sender, int row, int cell) {
}
public void onRowDeselected(SourceTableSelectionEvents sender, int row) {
}
public void onRowHover(SourceTableSelectionEvents sender, int row) {
}
public void onRowUnhover(SourceTableSelectionEvents sender, int row) {
}
public void onRowsSelected(SourceTableSelectionEvents sender, int firstRow, int numRows) {
try {
if (getOnselect() != null && getOnselect().trim().length() > 0) {
getXulDomContainer().invoke(getOnselect(), new Object[]{});
}
Integer[] selectedRows = table.getSelectedRows().toArray(new Integer[table.getSelectedRows().size()]);
//set.toArray(new Integer[]) doesn't unwrap ><
int[] rows = new int[selectedRows.length];
for(int i=0; i<selectedRows.length; i++){
rows[i] = selectedRows[i];
}
GwtTree.this.setSelectedRows(rows);
GwtTree.this.colCollection = getColumns().getChildNodes();
if(GwtTree.this.isShowalleditcontrols() == false){
if(curSelectedRow > -1){
Object[] curSelectedRowOriginal = new Object[getColumns().getColumnCount()];
for (int j = 0; j < getColumns().getColumnCount(); j++) {
curSelectedRowOriginal[j] = getColumnEditor(j,curSelectedRow);
}
table.replaceRow(curSelectedRow, curSelectedRowOriginal);
}
curSelectedRow = rows[0];
Object[] newRow = new Object[getColumns().getColumnCount()];
for (int j = 0; j < getColumns().getColumnCount(); j++) {
newRow[j] = getColumnEditor(j,rows[0]);
}
table.replaceRow(rows[0], newRow);
}
} catch (XulException e) {
e.printStackTrace();
}
}
});
setWidgetInPanel(table);
updateUI();
}
public void updateUI() {
if(this.suppressLayout) {
return;
}
if(this.isHierarchical()){
populateTree();
for(Binding expBind : expandBindings){
try {
expBind.fireSourceChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
// expandBindings.clear();
} else {
populateTable();
};
}
public void afterLayout() {
updateUI();
}
public void clearSelection() {
this.setSelectedRows(new int[]{});
}
public int[] getActiveCellCoordinates() {
// TODO Auto-generated method stub
return null;
}
public XulTreeCols getColumns() {
return columns;
}
public Object getData() {
// TODO Auto-generated method stub
return null;
}
@Bindable
public <T> Collection<T> getElements() {
return this.elements;
}
public String getOnedit() {
return getAttributeValue("onedit");
}
public String getOnselect() {
return getAttributeValue("onselect");
}
public XulTreeChildren getRootChildren() {
return rootChildren;
}
@Bindable
public int getRows() {
if (rootChildren == null) {
return 0;
} else {
return rootChildren.getItemCount();
}
}
@Bindable
public int[] getSelectedRows() {
if(this.isHierarchical()){
TreeItem item = tree.getSelectedItem();
for(int i=0; i <tree.getItemCount(); i++){
if(tree.getItem(i) == item){
return new int[]{i};
}
}
return new int[]{};
} else {
if (table == null) {
return new int[0];
}
Set<Integer> rows = table.getSelectedRows();
int rarr[] = new int[rows.size()];
int i = 0;
for (Integer v : rows) {
rarr[i++] = v;
}
return rarr;
}
}
public int[] getAbsoluteSelectedRows() {
return getSelectedRows();
}
private int[] selectedRows;
public void setSelectedRows(int[] rows) {
if (table == null || Arrays.equals(selectedRows, rows)) {
// this only works after the table has been materialized
return;
}
int[] prevSelected = selectedRows;
selectedRows = rows;
table.deselectRows();
for (int r : rows) {
if(this.rootChildren.getChildNodes().size() > r){
table.selectRow(r);
}
}
if(this.suppressEvents == false && Arrays.equals(selectedRows, prevSelected) == false){
this.changeSupport.firePropertyChange("selectedRows", prevSelected, rows);
this.changeSupport.firePropertyChange("absoluteSelectedRows", prevSelected, rows);
}
}
public String getSeltype() {
return getAttributeValue("seltype");
}
public Object[][] getValues() {
Object[][] data = new Object[getRootChildren().getChildNodes().size()][getColumns().getColumnCount()];
int y = 0;
for (XulComponent component : getRootChildren().getChildNodes()) {
XulTreeItem item = (XulTreeItem)component;
for (XulComponent childComp : item.getChildNodes()) {
XulTreeRow row = (XulTreeRow)childComp;
for (int x = 0; x < getColumns().getColumnCount(); x++) {
XulTreeCell cell = row.getCell(x);
switch (columns.getColumn(x).getColumnType()) {
case CHECKBOX:
Boolean flag = (Boolean) cell.getValue();
if (flag == null) {
flag = Boolean.FALSE;
}
data[y][x] = flag;
break;
case COMBOBOX:
Vector values = (Vector) cell.getValue();
int idx = cell.getSelectedIndex();
data[y][x] = values.get(idx);
break;
default: //label
data[y][x] = cell.getLabel();
break;
}
}
y++;
}
}
return data;
}
@Bindable
public boolean isEditable() {
return editable;
}
public boolean isEnableColumnDrag() {
return false;
}
public boolean isHierarchical() {
return isHierarchical;
}
public void removeTreeRows(int[] rows) {
// sort the rows high to low
ArrayList<Integer> rowArray = new ArrayList<Integer>();
for (int i = 0; i < rows.length; i++) {
rowArray.add(rows[i]);
}
Collections.sort(rowArray, Collections.reverseOrder());
// remove the items in that order
for (int i = 0; i < rowArray.size(); i++) {
int item = rowArray.get(i);
if (item >= 0 && item < rootChildren.getItemCount()) {
this.rootChildren.removeItem(item);
}
}
updateUI();
}
public void setActiveCellCoordinates(int row, int column) {
// TODO Auto-generated method stub
}
public void setColumns(XulTreeCols columns) {
if (getColumns() != null) {
this.removeChild(getColumns());
}
addChild(columns);
}
public void setData(Object data) {
// TODO Auto-generated method stub
}
@Bindable
public void setEditable(boolean edit) {
this.editable = edit;
}
@Bindable
public <T> void setElements(Collection<T> elements) {
try{
this.elements = elements;
suppressEvents = true;
prevSelectionPos = -1;
this.getRootChildren().removeAll();
for(Binding b : expandBindings){
b.destroyBindings();
}
this.expandBindings.clear();
for(TreeItemDropController d : this.dropHandlers){
XulDragController.getInstance().unregisterDropController(d);
}
dropHandlers.clear();
if(elements == null || elements.size() == 0){
suppressEvents = false;
updateUI();
return;
}
try {
if(table != null){
for (T o : elements) {
XulTreeRow row = this.getRootChildren().addNewRow();
int colSize = this.getColumns().getChildNodes().size();
for (int x=0; x< colSize; x++) {
XulComponent col = this.getColumns().getColumn(x);
XulTreeCol column = ((XulTreeCol) col);
final XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell");
addBindings(column, (GwtTreeCell) cell, o);
row.addCell(cell);
}
}
} else { //tree
for (T o : elements) {
XulTreeRow row = this.getRootChildren().addNewRow();
((XulTreeItem) row.getParent()).setBoundObject(o);
addTreeChild(o, row);
}
}
//treat as a selection change
} catch (XulException e) {
Window.alert("error adding elements "+e);
System.out.println(e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Window.alert("error adding elements "+e);
System.out.println(e.getMessage());
e.printStackTrace();
}
suppressEvents = false;
this.clearSelection();
updateUI();
} catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private <T> void addTreeChild(T element, XulTreeRow row){
try{
GwtTreeCell cell = (GwtTreeCell) getDocument().createElement("treecell");
for (InlineBindingExpression exp : ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getBindingExpressions()) {
Binding binding = createBinding((XulEventSource) element, exp.getModelAttr(), cell, exp.getXulCompAttr());
binding.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(binding);
binding.fireSourceChanged();
}
XulTreeCol column = (XulTreeCol) this.getColumns().getChildNodes().get(0);
String expBind = column.getExpandedbinding();
if(expBind != null){
Binding binding = createBinding((XulEventSource) element, expBind, row.getParent(), "expanded");
elementBindings.add(binding);
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
expandBindings.add(binding);
}
String imgBind = column.getImagebinding();
if(imgBind != null){
Binding binding = createBinding((XulEventSource) element, imgBind, row.getParent(), "image");
elementBindings.add(binding);
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
}
row.addCell(cell);
//find children
String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding();
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(element, property);
Collection<T> children = null;
if(childrenMethod != null){
children = (Collection<T>) childrenMethod.invoke(element, new Object[] {});
} else if(element instanceof Collection ){
children = (Collection<T>) element;
}
XulTreeChildren treeChildren = null;
if(children != null && children.size() > 0){
treeChildren = (XulTreeChildren) getDocument().createElement("treechildren");
row.getParent().addChild(treeChildren);
}
if (children == null) {
return;
}
for(T child : children){
row = treeChildren.addNewRow();
((XulTreeItem) row.getParent()).setBoundObject(child);
addTreeChild(child, row);
}
} catch (Exception e) {
Window.alert("error adding elements "+e.getMessage());
e.printStackTrace();
}
}
public void setEnableColumnDrag(boolean drag) {
// TODO Auto-generated method stub
}
public void setOnedit(String onedit) {
this.setAttribute("onedit", onedit);
}
public void setOnselect(String select) {
this.setAttribute("onselect", select);
}
public void setRootChildren(XulTreeChildren rootChildren) {
if (getRootChildren() != null) {
this.removeChild(getRootChildren());
}
addChild(rootChildren);
}
public void setRows(int rows) {
// TODO Auto-generated method stub
}
public void setSeltype(String type) {
// TODO Auto-generated method stub
// SINGLE, CELL, MULTIPLE, NONE
this.setAttribute("seltype", type);
}
public void update() {
layout();
}
public void adoptAttributes(XulComponent component) {
super.adoptAttributes(component);
layout();
}
public void registerCellEditor(String key, TreeCellEditor editor){
customEditors.put(key, editor);
}
public void registerCellRenderer(String key, TreeCellRenderer renderer) {
customRenderers.put(key, renderer);
}
private void addBindings(final XulTreeCol col, final GwtTreeCell cell, final Object o) throws InvocationTargetException, XulException{
for (InlineBindingExpression exp : col.getBindingExpressions()) {
String colType = col.getType();
if(StringUtils.isEmpty(colType) == false && colType.equalsIgnoreCase("dynamic")){
colType = extractDynamicColType(o, col.getParent().getChildNodes().indexOf(col));
}
if(colType != null && (colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox"))){
// Only add bindings if they haven't been already applied.
if(cell.valueBindingsAdded() == false){
Binding binding = createBinding((XulEventSource) o, col.getCombobinding(), cell, "value");
binding.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
}
if(cell.selectedIndexBindingsAdded() == false){
Binding binding = createBinding((XulEventSource) o, ((XulTreeCol) col).getBinding(), cell, "selectedIndex");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
binding.setConversion(new BindingConvertor<Object, Integer>(){
@Override
public Integer sourceToTarget(Object value) {
int index = ((Vector) cell.getValue()).indexOf(value);
return index > -1 ? index : 0;
}
@Override
public Object targetToSource(Integer value) {
return ((Vector)cell.getValue()).get(value);
}
});
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setSelectedIndexBindingsAdded(true);
}
if(cell.labelBindingsAdded() == false && colType.equalsIgnoreCase("editablecombobox")){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "label");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setLabelBindingsAdded(true);
}
} else if(colType != null && this.customEditors.containsKey(colType)){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "value");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
} else if(colType != null && colType.equalsIgnoreCase("checkbox")) {
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "value");
if(col.isEditable() == false){
binding.setBindingType(Binding.Type.ONE_WAY);
} else {
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
}
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
} else if(o instanceof XulEventSource && StringUtils.isEmpty(exp.getModelAttr()) == false){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, exp.getXulCompAttr());
if(col.isEditable() == false){
binding.setBindingType(Binding.Type.ONE_WAY);
} else {
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
}
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setLabelBindingsAdded(true);
} else {
cell.setLabel(o.toString());
}
}
if(StringUtils.isEmpty(col.getDisabledbinding()) == false){
String prop = col.getDisabledbinding();
Binding bind = createBinding((XulEventSource) o, col.getDisabledbinding(), cell, "disabled");
bind.setBindingType(Binding.Type.ONE_WAY);
// the default string to string was causing issues, this is really a boolean to boolean, no conversion necessary
bind.setConversion(null);
domContainer.addBinding(bind);
bind.fireSourceChanged();
}
}
@Deprecated
public void onResize() {
// if(table != null){
// table.onResize();
}
public class CustomCellEditorWrapper extends SimplePanel implements TreeCellEditorCallback{
private TreeCellEditor editor;
private TreeCellRenderer renderer;
private Label label = new Label();
private XulTreeCell cell;
public CustomCellEditorWrapper(XulTreeCell cell, TreeCellEditor editor){
super();
this.sinkEvents(Event.MOUSEEVENTS);
this.editor = editor;
this.cell = cell;
HorizontalPanel hPanel = new HorizontalPanel();
hPanel.setStylePrimaryName("slimTable");
SimplePanel labelWrapper = new SimplePanel();
labelWrapper.getElement().getStyle().setProperty("overflow", "hidden");
labelWrapper.setWidth("100%");
labelWrapper.add(label);
hPanel.add(labelWrapper);
hPanel.setCellWidth(labelWrapper, "100%");
ImageButton btn = new ImageButton(GWT.getModuleBaseURL() + "/images/open_new.png", GWT.getModuleBaseURL() + "/images/open_new.png", "", 29, 24);
btn.getElement().getStyle().setProperty("margin", "0px");
hPanel.add(btn);
hPanel.setSpacing(0);
hPanel.setBorderWidth(0);
hPanel.setWidth("100%");
labelWrapper.getElement().getParentElement().getStyle().setProperty("padding", "0px");
labelWrapper.getElement().getParentElement().getStyle().setProperty("border", "0px");
btn.getElement().getParentElement().getStyle().setProperty("padding", "0px");
btn.getElement().getParentElement().getStyle().setProperty("border", "0px");
this.add( hPanel );
if(cell.getValue() != null) {
this.label.setText((cell.getValue() != null) ? cell.getValue().toString() : " ");
}
}
public CustomCellEditorWrapper(XulTreeCell cell, TreeCellEditor editor, TreeCellRenderer renderer){
this(cell, editor);
this.renderer = renderer;
if(this.renderer.supportsNativeComponent()){
this.clear();
this.add((Widget) this.renderer.getNativeComponent());
} else {
this.label.setText((this.renderer.getText(cell.getValue()) != null) ? this.renderer.getText(cell.getValue()) : " ");
}
}
public void onCellEditorClosed(Object value) {
cell.setValue(value);
if(this.renderer == null){
this.label.setText(value.toString());
} else if(this.renderer.supportsNativeComponent()){
this.clear();
this.add((Widget) this.renderer.getNativeComponent());
} else {
this.label.setText((this.renderer.getText(cell.getValue()) != null) ? this.renderer.getText(cell.getValue()) : " ");
}
}
@Override
public void onBrowserEvent(Event event) {
int code = event.getTypeInt();
switch(code){
case Event.ONMOUSEUP:
editor.setValue(cell.getValue());
int col = cell.getParent().getChildNodes().indexOf(cell);
XulTreeItem item = (XulTreeItem) cell.getParent().getParent();
int row = item.getParent().getChildNodes().indexOf(item);
Object boundObj = (GwtTree.this.getElements() != null) ? GwtTree.this.getElements().toArray()[row] : null;
String columnBinding = GwtTree.this.getColumns().getColumn(col).getBinding();
editor.show(row, col, boundObj, columnBinding, this);
default:
break;
}
super.onBrowserEvent(event);
}
}
public void setBoundObjectExpanded(Object o, boolean expanded) {
throw new UnsupportedOperationException("not implemented");
}
public void setTreeItemExpanded(XulTreeItem item, boolean expanded) {
((TreeItem) item.getManagedObject()).setState(expanded);
}
public void collapseAll() {
if (this.isHierarchical()){
//TODO: Not yet implemented
}
}
public void expandAll() {
if (this.isHierarchical()){
//TODO: not implemented yet
}
}
@Bindable
public <T> Collection<T> getSelectedItems() {
// TODO Auto-generated method stub
return null;
}
@Bindable
public <T> void setSelectedItems(Collection<T> items) {
// TODO Auto-generated method stub
}
public boolean isHiddenrootnode() {
// TODO Auto-generated method stub
return false;
}
public void setHiddenrootnode(boolean hidden) {
// TODO Auto-generated method stub
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public boolean isPreserveexpandedstate() {
return false;
}
public void setPreserveexpandedstate(boolean preserve) {
}
public boolean isSortable() {
// TODO Auto-generated method stub
return false;
}
public void setSortable(boolean sort) {
// TODO Auto-generated method stub
}
public boolean isTreeLines() {
// TODO Auto-generated method stub
return false;
}
public void setTreeLines(boolean visible) {
// TODO Auto-generated method stub
}
public void setNewitembinding(String binding){
}
public String getNewitembinding(){
return null;
}
public void setAutocreatenewrows(boolean auto){
}
public boolean getAutocreatenewrows(){
return false;
}
public boolean isPreserveselection() {
// TODO This method is not fully implemented. We need to completely implement this in this class
return false;
}
public void setPreserveselection(boolean preserve) {
// TODO This method is not fully implemented. We need to completely implement this in this class
}
private void fireSelectedItems( ) {
Object selected = getSelectedItem();
this.changeSupport.firePropertyChange("selectedItem", null, selected);
}
@Bindable
public Object getSelectedItem() {
if (this.isHierarchical && this.elements != null) {
int pos = -1;
int curPos = 0;
for(int i=0; i < tree.getItemCount(); i++){
TreeItem tItem = tree.getItem(i);
TreeCursor cursor = GwtTree.this.findPosition(tItem, tree.getSelectedItem(), curPos);
pos = cursor.foundPosition;
curPos = cursor.curPos+1;
if(pos > -1){
break;
}
}
int[] vals = new int[]{pos};
String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding();
FindSelectedItemTuple tuple = findSelectedItem(this.elements, property, new FindSelectedItemTuple(vals[0]));
return tuple != null ? tuple.selectedItem : null;
}
return null;
}
private static class FindSelectedItemTuple {
Object selectedItem = null;
int curpos = -1; // ignores first element (root)
int selectedIndex;
public FindSelectedItemTuple(int selectedIndex) {
this.selectedIndex = selectedIndex;
}
}
private FindSelectedItemTuple findSelectedItem(Object parent, String childrenMethodProperty,
FindSelectedItemTuple tuple) {
if (tuple.curpos == tuple.selectedIndex) {
tuple.selectedItem = parent;
return tuple;
}
Collection children = getChildCollection(parent, childrenMethodProperty);
if (children == null || children.size() == 0) {
return null;
}
for (Object child : children) {
tuple.curpos++;
findSelectedItem(child, childrenMethodProperty, tuple);
if (tuple.selectedItem != null) {
return tuple;
}
}
return null;
}
private static Collection getChildCollection(Object obj, String childrenMethodProperty) {
Collection children = null;
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(obj, childrenMethodProperty);
try {
if (childrenMethod != null) {
children = (Collection) childrenMethod.invoke(obj, new Object[] {});
} else if(obj instanceof Collection ){
children = (Collection) obj;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return children;
}
public boolean isShowalleditcontrols() {
return showAllEditControls;
}
public void setShowalleditcontrols(boolean showAllEditControls) {
this.showAllEditControls = showAllEditControls;
}
@Override
public void setOndrag(String ondrag) {
super.setOndrag(ondrag);
}
@Override
public void setOndrop(String ondrop) {
super.setOndrop(ondrop);
}
@Override
public void setDropvetoer(String dropVetoMethod) {
if(StringUtils.isEmpty(dropVetoMethod)){
return;
}
super.setDropvetoer(dropVetoMethod);
}
private void resolveDropVetoerMethod(){
if(dropVetoerMethod == null){
String id = getDropvetoer().substring(0, getDropvetoer().indexOf("."));
try {
XulEventHandler controller = getXulDomContainer().getEventHandler(id);
this.dropVetoerMethod = GwtBindingContext.typeController.findMethod(controller, getDropvetoer().substring(getDropvetoer().indexOf(".")+1, getDropvetoer().indexOf("(")));
this.dropVetoerController = controller;
} catch (XulException e) {
e.printStackTrace();
}
}
}
private class TreeItemDropController extends AbstractPositioningDropController {
private XulTreeItem xulItem;
private TreeItemWidget item;
private DropPosition curPos;
private long lasPositionPoll = 0;
public TreeItemDropController(XulTreeItem xulItem, TreeItemWidget item){
super(item);
this.xulItem = xulItem;
this.item = item;
}
@Override
public void onEnter(DragContext context) {
super.onEnter(context);
resolveDropVetoerMethod();
if(dropVetoerMethod != null){
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
event.setDropPosition(curPos);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
try {
// Consult Vetoer method to see if this is a valid drop operation
dropVetoerMethod.invoke(dropVetoerController, new Object[]{event});
//Check to see if this drop candidate should be rejected.
if(event.isAccepted() == false){
return;
}
} catch (XulException e) {
e.printStackTrace();
}
}
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(true);
}
@Override
public void onLeave(DragContext context) {
super.onLeave(context);
item.getElement().getStyle().setProperty("border", "");
item.highLightDrop(false);
dropPosIndicator.setVisible(false);
Widget proxy = XulDragController.getInstance().getProxy();
if(proxy != null){
((Draggable) proxy).setDropValid(false);
}
}
@Override
public void onMove(DragContext context) {
super.onMove(context);
int scrollPanelX = 0;
int scrollPanelY = 0;
int scrollPanelScrollTop = 0;
int scrollPanelScrollLeft = 0;
if(System.currentTimeMillis() > lasPositionPoll+3000){
scrollPanelX = scrollPanel.getElement().getAbsoluteLeft();
scrollPanelScrollLeft = scrollPanel.getElement().getScrollLeft();
scrollPanelY = scrollPanel.getElement().getAbsoluteTop();
scrollPanelScrollTop = scrollPanel.getElement().getScrollTop();
}
int x = item.getAbsoluteLeft();
int y = item.getAbsoluteTop();
int height = item.getOffsetHeight();
int middleGround = height/4;
if(context.mouseY < (y+height/2)-middleGround){
curPos = DropPosition.ABOVE;
} else if(context.mouseY > (y+height/2)+middleGround){
curPos = DropPosition.BELOW;
} else {
curPos = DropPosition.MIDDLE;
}
resolveDropVetoerMethod();
if(dropVetoerMethod != null){
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
event.setDropPosition(curPos);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
try {
// Consult Vetoer method to see if this is a valid drop operation
dropVetoerMethod.invoke(dropVetoerController, new Object[]{event});
//Check to see if this drop candidate should be rejected.
if(event.isAccepted() == false){
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(false);
dropPosIndicator.setVisible(false);
return;
}
} catch (XulException e) {
e.printStackTrace();
}
}
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(true);
switch (curPos) {
case ABOVE:
item.highLightDrop(false);
int posX = item.getElement().getAbsoluteLeft()
- scrollPanelX
+ scrollPanelScrollLeft;
int posY = item.getElement().getAbsoluteTop()
- scrollPanelY
+ scrollPanelScrollTop
-4;
dropPosIndicator.setPosition(posX, posY, item.getOffsetWidth());
break;
case MIDDLE:
item.highLightDrop(true);
dropPosIndicator.setVisible(false);
break;
case BELOW:
item.highLightDrop(false);
posX = item.getElement().getAbsoluteLeft()
- scrollPanelX
+ scrollPanelScrollLeft;
posY = item.getElement().getAbsoluteTop()
+ item.getElement().getOffsetHeight()
- scrollPanelY
+ scrollPanelScrollTop
-4;
dropPosIndicator.setPosition(posX, posY, item.getOffsetWidth());
break;
}
}
@Override
public void onPreviewDrop(DragContext context) throws VetoDragException {
int i=0;
}
@Override
public void onDrop(DragContext context) {
super.onDrop(context);
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
//event.setDropIndex(index);
final String method = getOndrop();
if (method != null) {
try{
Document doc = getDocument();
XulRoot window = (XulRoot) doc.getRootElement();
final XulDomContainer con = window.getXulDomContainer();
con.invoke(method, new Object[]{event});
} catch (XulException e){
e.printStackTrace();
System.out.println("Error calling ondrop event: "+ method); //$NON-NLS-1$
}
}
if (!event.isAccepted()) {
return;
}
((Draggable) context.draggable).notifyDragFinished();
if(curPos == DropPosition.MIDDLE){
String property = ((XulTreeCol) GwtTree.this.getColumns().getChildNodes().get(0)).getChildrenbinding();
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(xulItem.getBoundObject(), property);
Collection children = null;
try {
if(childrenMethod != null){
children = (Collection) childrenMethod.invoke(xulItem.getBoundObject(), new Object[] {});
} else if(xulItem.getBoundObject() instanceof Collection ){
children = (Collection) xulItem.getBoundObject();
}
for(Object o : event.getDataTransfer().getData()){
children.add(o);
}
} catch (XulException e) {
e.printStackTrace();
}
} else {
XulComponent parent = xulItem.getParent().getParent();
List parentList;
if(parent instanceof GwtTree){
parentList = (List) GwtTree.this.elements;
} else {
parentList = (List) ((XulTreeItem) parent).getBoundObject();
}
int idx = parentList.indexOf(xulItem.getBoundObject());
if (curPos == DropPosition.BELOW){
idx++;
}
for(Object o : event.getDataTransfer().getData()){
parentList.add(idx, o);
}
}
}
}
public void notifyDragFinished(XulTreeItem xulItem){
if(this.drageffect.equalsIgnoreCase("copy")){
return;
}
XulComponent parent = xulItem.getParent().getParent();
List parentList;
if(parent instanceof GwtTree){
parentList = (List) GwtTree.this.elements;
} else {
parentList = (List) ((XulTreeItem) parent).getBoundObject();
}
parentList.remove(xulItem.getBoundObject());
}
private class DropPositionIndicator extends SimplePanel{
public DropPositionIndicator(){
setStylePrimaryName("tree-drop-indicator-symbol");
SimplePanel line = new SimplePanel();
line.setStylePrimaryName("tree-drop-indicator");
add(line);
setVisible(false);
}
public void setPosition(int scrollLeft, int scrollTop, int offsetWidth) {
this.setVisible(true);
setWidth(offsetWidth+"px");
getElement().getStyle().setProperty("top", scrollTop+"px");
getElement().getStyle().setProperty("left", (scrollLeft -4)+"px");
}
}
}
|
<#function callLoader entity>
<#assign ret="//Load "+entity.name+" fixtures\r\t\t" />
<#assign ret=ret+entity.name?cap_first+"DataLoader "+entity.name?uncap_first+"Loader = new "+entity.name?cap_first+"DataLoader(this.context);\r\t\t" />
<#assign ret=ret+entity.name?uncap_first+"Loader.getModelFixtures("+entity.name?cap_first+"DataLoader.MODE_BASE);\r\t\t" />
<#assign ret=ret+entity.name?uncap_first+"Loader.load(manager);\r\r" />
<#return ret />
</#function>
<#function getZeroRelationsEntities>
<#assign ret = [] />
<#list entities?values as entity>
<#if entity.relations?size==0>
<#assign ret = ret + [entity.name]>
</#if>
</#list>
<#return ret />
</#function>
<#function isInArray array val>
<#list array as val_ref>
<#if val_ref==val>
<#return true />
</#if>
</#list>
<#return false />
</#function>
<#function isOnlyDependantOf entity entity_list>
<#list entity.relations as rel>
<#if rel.relation.type=="ManyToOne">
<#if !isInArray(entity_list, rel.relation.targetEntity)>
<#return false />
</#if>
</#if>
</#list>
<#return true />
</#function>
<#function orderEntitiesByRelation>
<#assign ret = getZeroRelationsEntities() />
<#assign maxLoop = entities?size />
<#list 1..maxLoop as i>
<#list entities?values as entity>
<#if !isInArray(ret, entity.name)>
<#if isOnlyDependantOf(entity, ret)>
<#assign ret = ret + [entity.name] />
</#if>
</#if>
</#list>
</#list>
<#return ret>
</#function>
package ${data_namespace}.base;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import ${data_namespace}.*;
import ${project_namespace}.${project_name?cap_first}Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
<#if options.fixture?? && options.fixture.enabled>
import ${fixture_namespace}.*;
</#if>
/**
* This class makes it easy for ContentProvider implementations to defer opening and upgrading the database until first use, to avoid blocking application startup with long-running database upgrades.
* @see android.database.sqlite.SQLiteOpenHelper
*/
public class ${project_name?cap_first}SQLiteOpenHelperBase extends SQLiteOpenHelper {
protected String TAG = "DatabaseHelper";
protected Context context;
// Android's default system path of the database.
private static String DB_PATH;
private static String DB_NAME;
private static boolean assetsExist = false;
public ${project_name?cap_first}SQLiteOpenHelperBase(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
this.context = context;
DB_NAME = name;
DB_PATH = context.getDatabasePath(DB_NAME).getAbsolutePath();
try {
this.context.getAssets().open(DB_NAME);
assetsExist = true;
} catch (IOException e) {
assetsExist = false;
}
}
/**
* @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
@Override
public void onCreate(SQLiteDatabase db) {
if (${project_name?cap_first}Application.DEBUG)
Log.d(TAG, "Create database..");
if (!assetsExist) {
/// Create Schema
<#list entities?values as entity>
<#if (entity.fields?? && (entity.fields?size>0))>
db.execSQL( ${entity.name}SQLiteAdapter.getSchema() );
<#list entity["relations"] as relation>
<#if (relation.type=="ManyToMany")>
db.execSQL( ${entity.name}SQLiteAdapter.get${relation.name?cap_first}RelationSchema() );
</#if>
</#list>
</#if>
</#list>
<#if options.fixture?? && options.fixture.enabled>
this.loadData(db);
</#if>
}
}
/**
* Clear the database given in parameters
* @param db The database to clear
*/
public static void clearDatabase(SQLiteDatabase db){
<#list entities?values as entity>
<#if (entity.fields?? && (entity.fields?size>0))>
db.delete(${entity.name?cap_first}SQLiteAdapter.TABLE_NAME, null, null);
</#if>
</#list>
}
/**
* @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (${project_name?cap_first}Application.DEBUG)
Log.d(TAG, "Update database..");
//if (SqliteAdapter.BASE_VERSION < 0) {
Log.i(TAG, "Upgrading database from version " + oldVersion +
" to " + newVersion + ", which will destroy all old data");
<#list entities?values as entity>
<#if (entity.fields?? && (entity.fields?size>0))>
db.execSQL("DROP TABLE IF EXISTS "+ ${entity.name}SQLiteAdapter.TABLE_NAME);
<#list entity['relations'] as relation>
<#if (relation.type=="ManyToMany")>
db.execSQL("DROP TABLE IF EXISTS "+${entity.name}SQLiteAdapter.RELATION_${relation.name?upper_case}_TABLE_NAME );
</#if>
</#list>
</#if>
</#list>
this.onCreate(db);
}
<#if options.fixture?? && options.fixture.enabled>
//@SuppressWarnings("rawtypes")
private void loadData(SQLiteDatabase db){
// Sample of data
DataManager manager = new DataManager(this.context, db);
<#assign entitiesOrder = orderEntitiesByRelation() />
<#list entitiesOrder as entityName>
<#assign entity = entities[entityName]>
<#if (entity.fields?size>0)>
${callLoader(entity)}
</#if>
</#list>
}
</#if>
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {
if (assetsExist && !checkDataBase()){
// By calling this method and empty database will be created into
// the default system path
// so we're gonna be able to overwrite that database with ours
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
// NOTE : the system throw error message : "Database is locked" when
// the Database is not found (incorrect path)
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database doesn't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = this.context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
}
|
package com.markjmind.jwtools.net;
import android.util.Log;
import com.markjmind.jwtools.log.Loger;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class OkWeb{
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private OkHttpClient client;
private HashMap<String, String> param;
private HashMap<String, String> header;
private String host;
private String uri;
private String paramString;
protected boolean debug = false;
private Call call;
public OkWeb(String host) {
client = new OkHttpClient();
header = new HashMap<>();
param = new HashMap<>();
uri = "";
paramString = "";
this.setHost(host);
}
public OkWeb setDebug(boolean debug) {
this.debug = debug;
return this;
}
public String getHost() {
return host;
}
protected <ResultType extends ResultAdapter> ResultType getResult(Response response, Class<ResultType> type) throws IOException {
try {
Constructor<ResultType> constructor = type.getConstructor();
ResultType obj = constructor.newInstance();
obj.response = response;
obj.bodyString = response.body().string();
return obj;
} catch (NoSuchMethodException e) {
throw new RuntimeException(type.getName()+" class does not implement Constructor(Response)", e);
} catch (InvocationTargetException e) {
throw new RuntimeException(type.getName()+" class does not implement Constructor InvocationTargetException", e);
} catch (InstantiationException e) {
throw new RuntimeException(type.getName()+" class can not make instance Constructor(Response)", e);
} catch (IllegalAccessException e) {
throw new RuntimeException(type.getName()+" class illegalAccess Constructor(Response)", e);
}
}
public <ResultType extends ResultAdapter>ResultType get(Class<ResultType> resultType) throws IOException, WebException {
HttpUrl.Builder builder = HttpUrl.parse(new URL(new URL(host), uri).toString()+ paramString).newBuilder();
String[] keys = getParamKeys();
for (String key : keys) {
builder.addEncodedQueryParameter(key, param.get(key));
}
HttpUrl httpUrl = builder.build();
Request.Builder reqestBuilder = new Request.Builder().url(httpUrl);
String[] headerKeys = getHeaderKeys();
for (String key : headerKeys) {
reqestBuilder.addHeader(key, header.get(key));
}
Request request = reqestBuilder.build();
debugRequest("GET", paramString);
call = client.newCall(request);
Response response = call.execute();
ResultType result = getResult(response, resultType);
debugResponse(result.getBodyString(), response);
unexpectedCode(response);
return result;
}
public <ResultType extends ResultAdapter>ResultType form(Class<ResultType> resultType) throws WebException, IOException {
Request.Builder reqestBuilder = new Request.Builder()
.url(new URL(new URL(host), uri).toString()+ paramString)
.cacheControl(new CacheControl.Builder().noCache().build());
FormEncodingBuilder body = new FormEncodingBuilder();
String[] keys = getParamKeys();
for (String key : keys) {
body.add(key, param.get(key));
}
String[] headerKeys = getHeaderKeys();
for (String key : headerKeys) {
reqestBuilder.addHeader(key, header.get(key));
}
Request request = reqestBuilder
.post(body.build())
.build();
debugRequest("FORM", paramString);
call = client.newCall(request);
Response response = call.execute();
ResultType result = getResult(response, resultType);
debugResponse(result.getBodyString(), response);
unexpectedCode(response);
return result;
}
public <ResultType extends ResultAdapter>ResultType post(String text, Class<ResultType> resultType) throws IOException, WebException {
Request.Builder reqestBuilder = new Request.Builder();
String[] headerKeys = getHeaderKeys();
for (String key : headerKeys) {
reqestBuilder.addHeader(key, header.get(key));
}
RequestBody body = RequestBody.create(JSON, text);
Request request = reqestBuilder.url(new URL(new URL(host), uri).toString() + paramString)
.post(body)
.build();
debugRequest("POST", text);
call = client.newCall(request);
Response response = call.execute();
ResultType result = getResult(response, resultType);
debugResponse(result.getBodyString(), response);
unexpectedCode(response);
return result;
}
public String[] getHeaderKeys() {
if (header.size() == 0) {
return new String[0];
}
String keys[] = header.keySet().toArray(new String[0]);
if (keys == null) {
return new String[0];
}
return keys;
}
public static String sha1(String s) {
try {
// Create MD5 Hash
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return "0x" + hexString.toString().toUpperCase();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
protected void debugRequest(String method, String text) throws MalformedURLException {
if (debug) {
Log.i(this.getClass().getSimpleName(), " ");
Log.w(this.getClass().getSimpleName(), "");
Log.d(this.getClass().getSimpleName(), " API Call : " + Loger.callLibrary(this.getClass())+" ");
Log.i(this.getClass().getSimpleName(), " [Request] " + method + " : " + new URL(new URL(host), uri).toString());
String[] headerKeys = getHeaderKeys();
if (headerKeys.length > 0) {
Log.i(this.getClass().getSimpleName(), "- Header");
for (String key : headerKeys) {
Log.d(this.getClass().getSimpleName(), "" + key + ":" + header.get(key));
}
}
if (text != null && !"".equals(text)) {
Log.i(this.getClass().getSimpleName(), "- Text");
Log.d(this.getClass().getSimpleName(), text);
}
String[] paramKeys = getParamKeys();
if (paramKeys.length > 0) {
Log.i(this.getClass().getSimpleName(), "- Parameter");
for (int i = paramKeys.length-1; i>=0; i
String key = paramKeys[i];
Log.d(this.getClass().getSimpleName(), key + ":" + param.get(key));
}
}
}
}
protected void debugResponse(String bodyResult, Response response) {
if (debug) {
Log.i(this.getClass().getSimpleName(), " [Response] Code : " + response.code());
Log.i(this.getClass().getSimpleName(), "- body");
Log.d(this.getClass().getSimpleName(), bodyResult.replaceAll("\\r", ""));
Log.i(this.getClass().getSimpleName(), " ");
}
}
private void unexpectedCode(Response response) throws WebException {
if (!response.isSuccessful()) {
Log.e(this.getClass().getSimpleName(), "Server Response Error Unexpected code:" + response.code());
Log.e(this.getClass().getSimpleName(), response.message());
throw new WebException("Unexpected code " + response);
}
}
public OkWeb setHost(String host) {
this.host = host;
return this;
}
public OkWeb setUri(String uri){
if(uri!=null) {
this.uri = uri;
}
return this;
}
public OkWeb clearHeader() {
header.clear();
return this;
}
public OkWeb addHeader(String key, String value) {
header.put(key, value);
return this;
}
public OkWeb removeHeader(String key){
header.remove(key);
return this;
}
public OkWeb clearParam() {
param.clear();
return this;
}
public OkWeb addParam(String key, String value) {
param.put(key, value);
return this;
}
public OkWeb removeParam(String key){
param.remove(key);
return this;
}
public String[] getParamKeys() {
if (param.size() == 0) {
return new String[0];
}
String keys[] = param.keySet().toArray(new String[0]);
if (keys == null) {
return new String[0];
}
return keys;
}
public OkWeb addParamString(String paramString){
if (paramString == null) {
paramString = "";
} else {
paramString = "/?" + paramString;
}
this.paramString = paramString;
return this;
}
public OkWeb ignoreVerify() {
try {
final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}};
// SSL
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts,
new java.security.SecureRandom());
// SSL
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
client.setSslSocketFactory(sslSocketFactory);
} catch (Exception e) {
e.printStackTrace();
}
client.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return this;
}
public void cancel(){
if(call!=null && !call.isCanceled()){
call.cancel();
}
}
public OkHttpClient getOkHttpClient(){
return this.client;
}
}
|
package com.fsck.k9.activity;
import java.util.Collection;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.Account.SortType;
import com.fsck.k9.K9;
import com.fsck.k9.K9.SplitViewMode;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.compose.MessageActions;
import com.fsck.k9.activity.misc.SwipeGestureDetector.OnSwipeGestureListener;
import com.fsck.k9.activity.setup.AccountSettings;
import com.fsck.k9.activity.setup.FolderSettings;
import com.fsck.k9.activity.setup.Prefs;
import com.fsck.k9.fragment.MessageListFragment;
import com.fsck.k9.fragment.MessageListFragment.MessageListFragmentListener;
import com.fsck.k9.mailstore.StorageManager;
import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.search.LocalSearch;
import com.fsck.k9.search.SearchAccount;
import com.fsck.k9.search.SearchSpecification;
import com.fsck.k9.search.SearchSpecification.Attribute;
import com.fsck.k9.search.SearchSpecification.SearchCondition;
import com.fsck.k9.search.SearchSpecification.SearchField;
import com.fsck.k9.ui.messageview.MessageViewFragment;
import com.fsck.k9.ui.messageview.MessageViewFragment.MessageViewFragmentListener;
import com.fsck.k9.view.MessageHeader;
import com.fsck.k9.view.MessageTitleView;
import com.fsck.k9.view.ViewSwitcher;
import com.fsck.k9.view.ViewSwitcher.OnSwitchCompleteListener;
import de.cketti.library.changelog.ChangeLog;
/**
* MessageList is the primary user interface for the program. This Activity
* shows a list of messages.
* From this Activity the user can perform all standard message operations.
*/
public class MessageList extends K9Activity implements MessageListFragmentListener,
MessageViewFragmentListener, OnBackStackChangedListener, OnSwipeGestureListener,
OnSwitchCompleteListener {
// for this activity
private static final String EXTRA_SEARCH = "search";
private static final String EXTRA_NO_THREADING = "no_threading";
private static final String ACTION_SHORTCUT = "shortcut";
private static final String EXTRA_SPECIAL_FOLDER = "special_folder";
private static final String EXTRA_MESSAGE_REFERENCE = "message_reference";
// used for remote search
public static final String EXTRA_SEARCH_ACCOUNT = "com.fsck.k9.search_account";
private static final String EXTRA_SEARCH_FOLDER = "com.fsck.k9.search_folder";
private static final String STATE_DISPLAY_MODE = "displayMode";
private static final String STATE_MESSAGE_LIST_WAS_DISPLAYED = "messageListWasDisplayed";
private static final String STATE_FIRST_BACK_STACK_ID = "firstBackstackId";
// Used for navigating to next/previous message
private static final int PREVIOUS = 1;
private static final int NEXT = 2;
public static final int REQUEST_MASK_PENDING_INTENT = 1 << 16;
public static void actionDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask) {
actionDisplaySearch(context, search, noThreading, newTask, true);
}
public static void actionDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask, boolean clearTop) {
context.startActivity(
intentDisplaySearch(context, search, noThreading, newTask, clearTop));
}
public static Intent intentDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask, boolean clearTop) {
Intent intent = new Intent(context, MessageList.class);
intent.putExtra(EXTRA_SEARCH, search);
intent.putExtra(EXTRA_NO_THREADING, noThreading);
if (clearTop) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
if (newTask) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
return intent;
}
public static Intent shortcutIntent(Context context, String specialFolder) {
Intent intent = new Intent(context, MessageList.class);
intent.setAction(ACTION_SHORTCUT);
intent.putExtra(EXTRA_SPECIAL_FOLDER, specialFolder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
public static Intent actionDisplayMessageIntent(Context context,
MessageReference messageReference) {
Intent intent = new Intent(context, MessageList.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference);
return intent;
}
private enum DisplayMode {
MESSAGE_LIST,
MESSAGE_VIEW,
SPLIT_VIEW
}
private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation();
private ActionBar mActionBar;
private View mActionBarMessageList;
private View mActionBarMessageView;
private MessageTitleView mActionBarSubject;
private TextView mActionBarTitle;
private TextView mActionBarSubTitle;
private TextView mActionBarUnread;
private Menu mMenu;
private ViewGroup mMessageViewContainer;
private View mMessageViewPlaceHolder;
private MessageListFragment mMessageListFragment;
private MessageViewFragment mMessageViewFragment;
private int mFirstBackStackId = -1;
private Account mAccount;
private String mFolderName;
private LocalSearch mSearch;
private boolean mSingleFolderMode;
private boolean mSingleAccountMode;
private ProgressBar mActionBarProgress;
private MenuItem mMenuButtonCheckMail;
private View mActionButtonIndeterminateProgress;
private int mLastDirection = (K9.messageViewShowNext()) ? NEXT : PREVIOUS;
/**
* {@code true} if the message list should be displayed as flat list (i.e. no threading)
* regardless whether or not message threading was enabled in the settings. This is used for
* filtered views, e.g. when only displaying the unread messages in a folder.
*/
private boolean mNoThreading;
private DisplayMode mDisplayMode;
private MessageReference mMessageReference;
/**
* {@code true} when the message list was displayed once. This is used in
* {@link #onBackPressed()} to decide whether to go from the message view to the message list or
* finish the activity.
*/
private boolean mMessageListWasDisplayed = false;
private ViewSwitcher mViewSwitcher;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) {
finish();
return;
}
if (useSplitView()) {
setContentView(R.layout.split_message_list);
} else {
setContentView(R.layout.message_list);
mViewSwitcher = (ViewSwitcher) findViewById(R.id.container);
mViewSwitcher.setFirstInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_left));
mViewSwitcher.setFirstOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_right));
mViewSwitcher.setSecondInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right));
mViewSwitcher.setSecondOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_left));
mViewSwitcher.setOnSwitchCompleteListener(this);
}
initializeActionBar();
// Enable gesture detection for MessageLists
setupGestureDetector(this);
if (!decodeExtras(getIntent())) {
return;
}
findFragments();
initializeDisplayMode(savedInstanceState);
initializeLayout();
initializeFragments();
displayViews();
ChangeLog cl = new ChangeLog(this);
if (cl.isFirstRun()) {
cl.getLogDialog().show();
}
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (isFinishing()) {
return;
}
setIntent(intent);
if (mFirstBackStackId >= 0) {
getFragmentManager().popBackStackImmediate(mFirstBackStackId,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
mFirstBackStackId = -1;
}
removeMessageListFragment();
removeMessageViewFragment();
mMessageReference = null;
mSearch = null;
mFolderName = null;
if (!decodeExtras(intent)) {
return;
}
initializeDisplayMode(null);
initializeFragments();
displayViews();
}
/**
* Get references to existing fragments if the activity was restarted.
*/
private void findFragments() {
FragmentManager fragmentManager = getFragmentManager();
mMessageListFragment = (MessageListFragment) fragmentManager.findFragmentById(
R.id.message_list_container);
mMessageViewFragment = (MessageViewFragment) fragmentManager.findFragmentById(
R.id.message_view_container);
}
/**
* Create fragment instances if necessary.
*
* @see #findFragments()
*/
private void initializeFragments() {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
boolean hasMessageListFragment = (mMessageListFragment != null);
if (!hasMessageListFragment) {
FragmentTransaction ft = fragmentManager.beginTransaction();
mMessageListFragment = MessageListFragment.newInstance(mSearch, false,
(K9.isThreadedViewEnabled() && !mNoThreading));
ft.add(R.id.message_list_container, mMessageListFragment);
ft.commit();
}
// Check if the fragment wasn't restarted and has a MessageReference in the arguments. If
// so, open the referenced message.
if (!hasMessageListFragment && mMessageViewFragment == null &&
mMessageReference != null) {
openMessage(mMessageReference);
}
}
/**
* Set the initial display mode (message list, message view, or split view).
*
* <p><strong>Note:</strong>
* This method has to be called after {@link #findFragments()} because the result depends on
* the availability of a {@link MessageViewFragment} instance.
* </p>
*
* @param savedInstanceState
* The saved instance state that was passed to the activity as argument to
* {@link #onCreate(Bundle)}. May be {@code null}.
*/
private void initializeDisplayMode(Bundle savedInstanceState) {
if (useSplitView()) {
mDisplayMode = DisplayMode.SPLIT_VIEW;
return;
}
if (savedInstanceState != null) {
DisplayMode savedDisplayMode =
(DisplayMode) savedInstanceState.getSerializable(STATE_DISPLAY_MODE);
if (savedDisplayMode != DisplayMode.SPLIT_VIEW) {
mDisplayMode = savedDisplayMode;
return;
}
}
if (mMessageViewFragment != null || mMessageReference != null) {
mDisplayMode = DisplayMode.MESSAGE_VIEW;
} else {
mDisplayMode = DisplayMode.MESSAGE_LIST;
}
}
private boolean useSplitView() {
SplitViewMode splitViewMode = K9.getSplitViewMode();
int orientation = getResources().getConfiguration().orientation;
return (splitViewMode == SplitViewMode.ALWAYS ||
(splitViewMode == SplitViewMode.WHEN_IN_LANDSCAPE &&
orientation == Configuration.ORIENTATION_LANDSCAPE));
}
private void initializeLayout() {
mMessageViewContainer = (ViewGroup) findViewById(R.id.message_view_container);
LayoutInflater layoutInflater = getLayoutInflater();
mMessageViewPlaceHolder = layoutInflater.inflate(R.layout.empty_message_view, mMessageViewContainer, false);
}
private void displayViews() {
switch (mDisplayMode) {
case MESSAGE_LIST: {
showMessageList();
break;
}
case MESSAGE_VIEW: {
showMessageView();
break;
}
case SPLIT_VIEW: {
mMessageListWasDisplayed = true;
if (mMessageViewFragment == null) {
showMessageViewPlaceHolder();
} else {
MessageReference activeMessage = mMessageViewFragment.getMessageReference();
if (activeMessage != null) {
mMessageListFragment.setActiveMessage(activeMessage);
}
}
break;
}
}
}
private boolean decodeExtras(Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action) && intent.getData() != null) {
Uri uri = intent.getData();
List<String> segmentList = uri.getPathSegments();
String accountId = segmentList.get(0);
Collection<Account> accounts = Preferences.getPreferences(this).getAvailableAccounts();
for (Account account : accounts) {
if (String.valueOf(account.getAccountNumber()).equals(accountId)) {
String folderName = segmentList.get(1);
String messageUid = segmentList.get(2);
mMessageReference = new MessageReference(account.getUuid(), folderName, messageUid, null);
break;
}
}
} else if (ACTION_SHORTCUT.equals(action)) {
// Handle shortcut intents
String specialFolder = intent.getStringExtra(EXTRA_SPECIAL_FOLDER);
if (SearchAccount.UNIFIED_INBOX.equals(specialFolder)) {
mSearch = SearchAccount.createUnifiedInboxAccount(this).getRelatedSearch();
} else if (SearchAccount.ALL_MESSAGES.equals(specialFolder)) {
mSearch = SearchAccount.createAllMessagesAccount(this).getRelatedSearch();
}
} else if (intent.getStringExtra(SearchManager.QUERY) != null) {
// check if this intent comes from the system search ( remote )
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
//Query was received from Search Dialog
String query = intent.getStringExtra(SearchManager.QUERY).trim();
mSearch = new LocalSearch(getString(R.string.search_results));
mSearch.setManualSearch(true);
mNoThreading = true;
mSearch.or(new SearchCondition(SearchField.SENDER, Attribute.CONTAINS, query));
mSearch.or(new SearchCondition(SearchField.SUBJECT, Attribute.CONTAINS, query));
mSearch.or(new SearchCondition(SearchField.MESSAGE_CONTENTS, Attribute.CONTAINS, query));
Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
if (appData != null) {
mSearch.addAccountUuid(appData.getString(EXTRA_SEARCH_ACCOUNT));
// searches started from a folder list activity will provide an account, but no folder
if (appData.getString(EXTRA_SEARCH_FOLDER) != null) {
mSearch.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER));
}
} else {
mSearch.addAccountUuid(LocalSearch.ALL_ACCOUNTS);
}
}
} else {
// regular LocalSearch object was passed
mSearch = intent.getParcelableExtra(EXTRA_SEARCH);
mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false);
}
if (mMessageReference == null) {
mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE);
}
if (mMessageReference != null) {
mSearch = new LocalSearch();
mSearch.addAccountUuid(mMessageReference.getAccountUuid());
mSearch.addAllowedFolder(mMessageReference.getFolderName());
}
if (mSearch == null) {
// We've most likely been started by an old unread widget
String accountUuid = intent.getStringExtra("account");
String folderName = intent.getStringExtra("folder");
mSearch = new LocalSearch(folderName);
mSearch.addAccountUuid((accountUuid == null) ? "invalid" : accountUuid);
if (folderName != null) {
mSearch.addAllowedFolder(folderName);
}
}
Preferences prefs = Preferences.getPreferences(getApplicationContext());
String[] accountUuids = mSearch.getAccountUuids();
if (mSearch.searchAllAccounts()) {
List<Account> accounts = prefs.getAccounts();
mSingleAccountMode = (accounts.size() == 1);
if (mSingleAccountMode) {
mAccount = accounts.get(0);
}
} else {
mSingleAccountMode = (accountUuids.length == 1);
if (mSingleAccountMode) {
mAccount = prefs.getAccount(accountUuids[0]);
}
}
mSingleFolderMode = mSingleAccountMode && (mSearch.getFolderNames().size() == 1);
if (mSingleAccountMode && (mAccount == null || !mAccount.isAvailable(this))) {
Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account");
onAccountUnavailable();
return false;
}
if (mSingleFolderMode) {
mFolderName = mSearch.getFolderNames().get(0);
}
// now we know if we are in single account mode and need a subtitle
mActionBarSubTitle.setVisibility((!mSingleFolderMode) ? View.GONE : View.VISIBLE);
return true;
}
@Override
public void onPause() {
super.onPause();
StorageManager.getInstance(getApplication()).removeListener(mStorageListener);
}
@Override
public void onResume() {
super.onResume();
if (!(this instanceof Search)) {
//necessary b/c no guarantee Search.onStop will be called before MessageList.onResume
//when returning from search results
Search.setActive(false);
}
if (mAccount != null && !mAccount.isAvailable(this)) {
onAccountUnavailable();
return;
}
StorageManager.getInstance(getApplication()).addListener(mStorageListener);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(STATE_DISPLAY_MODE, mDisplayMode);
outState.putBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED, mMessageListWasDisplayed);
outState.putInt(STATE_FIRST_BACK_STACK_ID, mFirstBackStackId);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
mMessageListWasDisplayed = savedInstanceState.getBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED);
mFirstBackStackId = savedInstanceState.getInt(STATE_FIRST_BACK_STACK_ID);
}
private void initializeActionBar() {
mActionBar = getActionBar();
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setCustomView(R.layout.actionbar_custom);
View customView = mActionBar.getCustomView();
mActionBarMessageList = customView.findViewById(R.id.actionbar_message_list);
mActionBarMessageView = customView.findViewById(R.id.actionbar_message_view);
mActionBarSubject = (MessageTitleView) customView.findViewById(R.id.message_title_view);
mActionBarTitle = (TextView) customView.findViewById(R.id.actionbar_title_first);
mActionBarSubTitle = (TextView) customView.findViewById(R.id.actionbar_title_sub);
mActionBarUnread = (TextView) customView.findViewById(R.id.actionbar_unread_count);
mActionBarProgress = (ProgressBar) customView.findViewById(R.id.actionbar_progress);
mActionButtonIndeterminateProgress = getActionButtonIndeterminateProgress();
mActionBar.setDisplayHomeAsUpEnabled(true);
}
@SuppressLint("InflateParams")
private View getActionButtonIndeterminateProgress() {
return getLayoutInflater().inflate(R.layout.actionbar_indeterminate_progress_actionview, null);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean ret = false;
if (KeyEvent.ACTION_DOWN == event.getAction()) {
ret = onCustomKeyDown(event.getKeyCode(), event);
}
if (!ret) {
ret = super.dispatchKeyEvent(event);
}
return ret;
}
@Override
public void onBackPressed() {
if (mDisplayMode == DisplayMode.MESSAGE_VIEW && mMessageListWasDisplayed) {
showMessageList();
} else {
super.onBackPressed();
}
}
/**
* Handle hotkeys
*
* <p>
* This method is called by {@link #dispatchKeyEvent(KeyEvent)} before any view had the chance
* to consume this key event.
* </p>
*
* @param keyCode
* The value in {@code event.getKeyCode()}.
* @param event
* Description of the key event.
*
* @return {@code true} if this event was consumed.
*/
public boolean onCustomKeyDown(final int keyCode, final KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP: {
if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST &&
K9.useVolumeKeysForNavigationEnabled()) {
showPreviousMessage();
return true;
} else if (mDisplayMode != DisplayMode.MESSAGE_VIEW &&
K9.useVolumeKeysForListNavigationEnabled()) {
mMessageListFragment.onMoveUp();
return true;
}
break;
}
case KeyEvent.KEYCODE_VOLUME_DOWN: {
if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST &&
K9.useVolumeKeysForNavigationEnabled()) {
showNextMessage();
return true;
} else if (mDisplayMode != DisplayMode.MESSAGE_VIEW &&
K9.useVolumeKeysForListNavigationEnabled()) {
mMessageListFragment.onMoveDown();
return true;
}
break;
}
case KeyEvent.KEYCODE_C: {
mMessageListFragment.onCompose();
return true;
}
case KeyEvent.KEYCODE_Q: {
if (mMessageListFragment != null && mMessageListFragment.isSingleAccountMode()) {
onShowFolderList();
}
return true;
}
case KeyEvent.KEYCODE_O: {
mMessageListFragment.onCycleSort();
return true;
}
case KeyEvent.KEYCODE_I: {
mMessageListFragment.onReverseSort();
return true;
}
case KeyEvent.KEYCODE_DEL:
case KeyEvent.KEYCODE_D: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onDelete();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onDelete();
}
return true;
}
case KeyEvent.KEYCODE_S: {
mMessageListFragment.toggleMessageSelect();
return true;
}
case KeyEvent.KEYCODE_G: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onToggleFlagged();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onToggleFlagged();
}
return true;
}
case KeyEvent.KEYCODE_M: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onMove();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onMove();
}
return true;
}
case KeyEvent.KEYCODE_V: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onArchive();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onArchive();
}
return true;
}
case KeyEvent.KEYCODE_Y: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onCopy();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onCopy();
}
return true;
}
case KeyEvent.KEYCODE_Z: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onToggleRead();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onToggleRead();
}
return true;
}
case KeyEvent.KEYCODE_F: {
if (mMessageViewFragment != null) {
mMessageViewFragment.onForward();
}
return true;
}
case KeyEvent.KEYCODE_A: {
if (mMessageViewFragment != null) {
mMessageViewFragment.onReplyAll();
}
return true;
}
case KeyEvent.KEYCODE_R: {
if (mMessageViewFragment != null) {
mMessageViewFragment.onReply();
}
return true;
}
case KeyEvent.KEYCODE_J:
case KeyEvent.KEYCODE_P: {
if (mMessageViewFragment != null) {
showPreviousMessage();
}
return true;
}
case KeyEvent.KEYCODE_N:
case KeyEvent.KEYCODE_K: {
if (mMessageViewFragment != null) {
showNextMessage();
}
return true;
}
/* FIXME
case KeyEvent.KEYCODE_Z: {
mMessageViewFragment.zoom(event);
return true;
}*/
case KeyEvent.KEYCODE_H: {
Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG);
toast.show();
return true;
}
case KeyEvent.KEYCODE_DPAD_LEFT: {
if (mMessageViewFragment != null && mDisplayMode == DisplayMode.MESSAGE_VIEW) {
return showPreviousMessage();
}
return false;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
if (mMessageViewFragment != null && mDisplayMode == DisplayMode.MESSAGE_VIEW) {
return showNextMessage();
}
return false;
}
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// Swallow these events too to avoid the audible notification of a volume change
if (K9.useVolumeKeysForListNavigationEnabled()) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Swallowed key up.");
return true;
}
}
return super.onKeyUp(keyCode, event);
}
private void onAccounts() {
Accounts.listAccounts(this);
finish();
}
private void onShowFolderList() {
FolderList.actionHandleAccount(this, mAccount);
finish();
}
private void onEditPrefs() {
Prefs.actionPrefs(this);
}
private void onEditAccount() {
AccountSettings.actionSettings(this, mAccount);
}
@Override
public boolean onSearchRequested() {
return mMessageListFragment.onSearchRequested();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home: {
goBack();
return true;
}
case R.id.compose: {
mMessageListFragment.onCompose();
return true;
}
case R.id.toggle_message_view_theme: {
onToggleTheme();
return true;
}
// MessageList
case R.id.check_mail: {
mMessageListFragment.checkMail();
return true;
}
case R.id.set_sort_date: {
mMessageListFragment.changeSort(SortType.SORT_DATE);
return true;
}
case R.id.set_sort_arrival: {
mMessageListFragment.changeSort(SortType.SORT_ARRIVAL);
return true;
}
case R.id.set_sort_subject: {
mMessageListFragment.changeSort(SortType.SORT_SUBJECT);
return true;
}
case R.id.set_sort_sender: {
mMessageListFragment.changeSort(SortType.SORT_SENDER);
return true;
}
case R.id.set_sort_flag: {
mMessageListFragment.changeSort(SortType.SORT_FLAGGED);
return true;
}
case R.id.set_sort_unread: {
mMessageListFragment.changeSort(SortType.SORT_UNREAD);
return true;
}
case R.id.set_sort_attach: {
mMessageListFragment.changeSort(SortType.SORT_ATTACHMENT);
return true;
}
case R.id.select_all: {
mMessageListFragment.selectAll();
return true;
}
case R.id.app_settings: {
onEditPrefs();
return true;
}
case R.id.account_settings: {
onEditAccount();
return true;
}
case R.id.search: {
mMessageListFragment.onSearchRequested();
return true;
}
case R.id.search_remote: {
mMessageListFragment.onRemoteSearch();
return true;
}
case R.id.mark_all_as_read: {
mMessageListFragment.confirmMarkAllAsRead();
return true;
}
case R.id.show_folder_list: {
onShowFolderList();
return true;
}
// MessageView
case R.id.next_message: {
showNextMessage();
return true;
}
case R.id.previous_message: {
showPreviousMessage();
return true;
}
case R.id.delete: {
mMessageViewFragment.onDelete();
return true;
}
case R.id.reply: {
mMessageViewFragment.onReply();
return true;
}
case R.id.reply_all: {
mMessageViewFragment.onReplyAll();
return true;
}
case R.id.forward: {
mMessageViewFragment.onForward();
return true;
}
case R.id.share: {
mMessageViewFragment.onSendAlternate();
return true;
}
case R.id.toggle_unread: {
mMessageViewFragment.onToggleRead();
return true;
}
case R.id.archive:
case R.id.refile_archive: {
mMessageViewFragment.onArchive();
return true;
}
case R.id.spam:
case R.id.refile_spam: {
mMessageViewFragment.onSpam();
return true;
}
case R.id.move:
case R.id.refile_move: {
mMessageViewFragment.onMove();
return true;
}
case R.id.copy:
case R.id.refile_copy: {
mMessageViewFragment.onCopy();
return true;
}
case R.id.select_text: {
mMessageViewFragment.onSelectText();
return true;
}
case R.id.show_headers:
case R.id.hide_headers: {
mMessageViewFragment.onToggleAllHeadersView();
updateMenu();
return true;
}
}
if (!mSingleFolderMode) {
// None of the options after this point are "safe" for search results
//TODO: This is not true for "unread" and "starred" searches in regular folders
return false;
}
switch (itemId) {
case R.id.send_messages: {
mMessageListFragment.onSendPendingMessages();
return true;
}
case R.id.folder_settings: {
if (mFolderName != null) {
FolderSettings.actionSettings(this, mAccount, mFolderName);
}
return true;
}
case R.id.expunge: {
mMessageListFragment.onExpunge();
return true;
}
default: {
return super.onOptionsItemSelected(item);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.message_list_option, menu);
mMenu = menu;
mMenuButtonCheckMail= menu.findItem(R.id.check_mail);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
configureMenu(menu);
return true;
}
/**
* Hide menu items not appropriate for the current context.
*
* <p><strong>Note:</strong>
* Please adjust the comments in {@code res/menu/message_list_option.xml} if you change the
* visibility of a menu item in this method.
* </p>
*
* @param menu
* The {@link Menu} instance that should be modified. May be {@code null}; in that case
* the method does nothing and immediately returns.
*/
private void configureMenu(Menu menu) {
if (menu == null) {
return;
}
// Set visibility of account/folder settings menu items
if (mMessageListFragment == null) {
menu.findItem(R.id.account_settings).setVisible(false);
menu.findItem(R.id.folder_settings).setVisible(false);
} else {
menu.findItem(R.id.account_settings).setVisible(
mMessageListFragment.isSingleAccountMode());
menu.findItem(R.id.folder_settings).setVisible(
mMessageListFragment.isSingleFolderMode());
}
/*
* Set visibility of menu items related to the message view
*/
if (mDisplayMode == DisplayMode.MESSAGE_LIST
|| mMessageViewFragment == null
|| !mMessageViewFragment.isInitialized()) {
menu.findItem(R.id.next_message).setVisible(false);
menu.findItem(R.id.previous_message).setVisible(false);
menu.findItem(R.id.single_message_options).setVisible(false);
menu.findItem(R.id.delete).setVisible(false);
menu.findItem(R.id.compose).setVisible(false);
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.copy).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
menu.findItem(R.id.refile).setVisible(false);
menu.findItem(R.id.toggle_unread).setVisible(false);
menu.findItem(R.id.select_text).setVisible(false);
menu.findItem(R.id.toggle_message_view_theme).setVisible(false);
menu.findItem(R.id.show_headers).setVisible(false);
menu.findItem(R.id.hide_headers).setVisible(false);
} else {
// hide prev/next buttons in split mode
if (mDisplayMode != DisplayMode.MESSAGE_VIEW) {
menu.findItem(R.id.next_message).setVisible(false);
menu.findItem(R.id.previous_message).setVisible(false);
} else {
MessageReference ref = mMessageViewFragment.getMessageReference();
boolean initialized = (mMessageListFragment != null &&
mMessageListFragment.isLoadFinished());
boolean canDoPrev = (initialized && !mMessageListFragment.isFirst(ref));
boolean canDoNext = (initialized && !mMessageListFragment.isLast(ref));
MenuItem prev = menu.findItem(R.id.previous_message);
prev.setEnabled(canDoPrev);
prev.getIcon().setAlpha(canDoPrev ? 255 : 127);
MenuItem next = menu.findItem(R.id.next_message);
next.setEnabled(canDoNext);
next.getIcon().setAlpha(canDoNext ? 255 : 127);
}
MenuItem toggleTheme = menu.findItem(R.id.toggle_message_view_theme);
if (K9.useFixedMessageViewTheme()) {
toggleTheme.setVisible(false);
} else {
// Set title of menu item to switch to dark/light theme
if (K9.getK9MessageViewTheme() == K9.Theme.DARK) {
toggleTheme.setTitle(R.string.message_view_theme_action_light);
} else {
toggleTheme.setTitle(R.string.message_view_theme_action_dark);
}
toggleTheme.setVisible(true);
}
// Set title of menu item to toggle the read state of the currently displayed message
if (mMessageViewFragment.isMessageRead()) {
menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_unread_action);
} else {
menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_read_action);
}
// Jellybean has built-in long press selection support
menu.findItem(R.id.select_text).setVisible(Build.VERSION.SDK_INT < 16);
menu.findItem(R.id.delete).setVisible(K9.isMessageViewDeleteActionVisible());
/*
* Set visibility of copy, move, archive, spam in action bar and refile submenu
*/
if (mMessageViewFragment.isCopyCapable()) {
menu.findItem(R.id.copy).setVisible(K9.isMessageViewCopyActionVisible());
menu.findItem(R.id.refile_copy).setVisible(true);
} else {
menu.findItem(R.id.copy).setVisible(false);
menu.findItem(R.id.refile_copy).setVisible(false);
}
if (mMessageViewFragment.isMoveCapable()) {
boolean canMessageBeArchived = mMessageViewFragment.canMessageBeArchived();
boolean canMessageBeMovedToSpam = mMessageViewFragment.canMessageBeMovedToSpam();
menu.findItem(R.id.move).setVisible(K9.isMessageViewMoveActionVisible());
menu.findItem(R.id.archive).setVisible(canMessageBeArchived &&
K9.isMessageViewArchiveActionVisible());
menu.findItem(R.id.spam).setVisible(canMessageBeMovedToSpam &&
K9.isMessageViewSpamActionVisible());
menu.findItem(R.id.refile_move).setVisible(true);
menu.findItem(R.id.refile_archive).setVisible(canMessageBeArchived);
menu.findItem(R.id.refile_spam).setVisible(canMessageBeMovedToSpam);
} else {
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
menu.findItem(R.id.refile).setVisible(false);
}
if (mMessageViewFragment.allHeadersVisible()) {
menu.findItem(R.id.show_headers).setVisible(false);
} else {
menu.findItem(R.id.hide_headers).setVisible(false);
}
}
/*
* Set visibility of menu items related to the message list
*/
// Hide both search menu items by default and enable one when appropriate
menu.findItem(R.id.search).setVisible(false);
menu.findItem(R.id.search_remote).setVisible(false);
if (mDisplayMode == DisplayMode.MESSAGE_VIEW || mMessageListFragment == null ||
!mMessageListFragment.isInitialized()) {
menu.findItem(R.id.check_mail).setVisible(false);
menu.findItem(R.id.set_sort).setVisible(false);
menu.findItem(R.id.select_all).setVisible(false);
menu.findItem(R.id.send_messages).setVisible(false);
menu.findItem(R.id.expunge).setVisible(false);
menu.findItem(R.id.mark_all_as_read).setVisible(false);
menu.findItem(R.id.show_folder_list).setVisible(false);
} else {
menu.findItem(R.id.set_sort).setVisible(true);
menu.findItem(R.id.select_all).setVisible(true);
menu.findItem(R.id.compose).setVisible(true);
menu.findItem(R.id.mark_all_as_read).setVisible(
mMessageListFragment.isMarkAllAsReadSupported());
if (!mMessageListFragment.isSingleAccountMode()) {
menu.findItem(R.id.expunge).setVisible(false);
menu.findItem(R.id.send_messages).setVisible(false);
menu.findItem(R.id.show_folder_list).setVisible(false);
} else {
menu.findItem(R.id.send_messages).setVisible(mMessageListFragment.isOutbox());
menu.findItem(R.id.expunge).setVisible(mMessageListFragment.isRemoteFolder() &&
mMessageListFragment.isAccountExpungeCapable());
menu.findItem(R.id.show_folder_list).setVisible(true);
}
menu.findItem(R.id.check_mail).setVisible(mMessageListFragment.isCheckMailSupported());
// If this is an explicit local search, show the option to search on the server
if (!mMessageListFragment.isRemoteSearch() &&
mMessageListFragment.isRemoteSearchAllowed()) {
menu.findItem(R.id.search_remote).setVisible(true);
} else if (!mMessageListFragment.isManualSearch()) {
menu.findItem(R.id.search).setVisible(true);
}
}
}
protected void onAccountUnavailable() {
finish();
// TODO inform user about account unavailability using Toast
Accounts.listAccounts(this);
}
public void setActionBarTitle(String title) {
mActionBarTitle.setText(title);
}
public void setActionBarSubTitle(String subTitle) {
mActionBarSubTitle.setText(subTitle);
}
public void setActionBarUnread(int unread) {
if (unread == 0) {
mActionBarUnread.setVisibility(View.GONE);
} else {
mActionBarUnread.setVisibility(View.VISIBLE);
mActionBarUnread.setText(String.format("%d", unread));
}
}
@Override
public void setMessageListTitle(String title) {
setActionBarTitle(title);
}
@Override
public void setMessageListSubTitle(String subTitle) {
setActionBarSubTitle(subTitle);
}
@Override
public void setUnreadCount(int unread) {
setActionBarUnread(unread);
}
@Override
public void setMessageListProgress(int progress) {
setProgress(progress);
}
@Override
public void openMessage(MessageReference messageReference) {
Preferences prefs = Preferences.getPreferences(getApplicationContext());
Account account = prefs.getAccount(messageReference.getAccountUuid());
String folderName = messageReference.getFolderName();
if (folderName.equals(account.getDraftsFolderName())) {
MessageActions.actionEditDraft(this, messageReference);
} else {
mMessageViewContainer.removeView(mMessageViewPlaceHolder);
if (mMessageListFragment != null) {
mMessageListFragment.setActiveMessage(messageReference);
}
MessageViewFragment fragment = MessageViewFragment.newInstance(messageReference);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.message_view_container, fragment);
mMessageViewFragment = fragment;
ft.commit();
if (mDisplayMode != DisplayMode.SPLIT_VIEW) {
showMessageView();
}
}
}
@Override
public void onResendMessage(MessageReference messageReference) {
MessageActions.actionEditDraft(this, messageReference);
}
@Override
public void onForward(MessageReference messageReference) {
onForward(messageReference, null);
}
@Override
public void onForward(MessageReference messageReference, Parcelable decryptionResultForReply) {
MessageActions.actionForward(this, messageReference, decryptionResultForReply);
}
@Override
public void onReply(MessageReference messageReference) {
onReply(messageReference, null);
}
@Override
public void onReply(MessageReference messageReference, Parcelable decryptionResultForReply) {
MessageActions.actionReply(this, messageReference, false, decryptionResultForReply);
}
@Override
public void onReplyAll(MessageReference messageReference) {
onReplyAll(messageReference, null);
}
@Override
public void onReplyAll(MessageReference messageReference, Parcelable decryptionResultForReply) {
MessageActions.actionReply(this, messageReference, true, decryptionResultForReply);
}
@Override
public void onCompose(Account account) {
MessageActions.actionCompose(this, account);
}
@Override
public void showMoreFromSameSender(String senderAddress) {
LocalSearch tmpSearch = new LocalSearch("From " + senderAddress);
tmpSearch.addAccountUuids(mSearch.getAccountUuids());
tmpSearch.and(SearchField.SENDER, senderAddress, Attribute.CONTAINS);
MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, false, false);
addMessageListFragment(fragment, true);
}
@Override
public void onBackStackChanged() {
findFragments();
if (mDisplayMode == DisplayMode.SPLIT_VIEW) {
showMessageViewPlaceHolder();
}
configureMenu(mMenu);
}
@Override
public void onSwipeRightToLeft(MotionEvent e1, MotionEvent e2) {
if (mMessageListFragment != null && mDisplayMode != DisplayMode.MESSAGE_VIEW) {
mMessageListFragment.onSwipeRightToLeft(e1, e2);
}
}
@Override
public void onSwipeLeftToRight(MotionEvent e1, MotionEvent e2) {
if (mMessageListFragment != null && mDisplayMode != DisplayMode.MESSAGE_VIEW) {
mMessageListFragment.onSwipeLeftToRight(e1, e2);
}
}
private final class StorageListenerImplementation implements StorageManager.StorageListener {
@Override
public void onUnmount(String providerId) {
if (mAccount != null && providerId.equals(mAccount.getLocalStorageProviderId())) {
runOnUiThread(new Runnable() {
@Override
public void run() {
onAccountUnavailable();
}
});
}
}
@Override
public void onMount(String providerId) {
// no-op
}
}
private void addMessageListFragment(MessageListFragment fragment, boolean addToBackStack) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.message_list_container, fragment);
if (addToBackStack)
ft.addToBackStack(null);
mMessageListFragment = fragment;
int transactionId = ft.commit();
if (transactionId >= 0 && mFirstBackStackId < 0) {
mFirstBackStackId = transactionId;
}
}
@Override
public boolean startSearch(Account account, String folderName) {
// If this search was started from a MessageList of a single folder, pass along that folder info
// so that we can enable remote search.
if (account != null && folderName != null) {
final Bundle appData = new Bundle();
appData.putString(EXTRA_SEARCH_ACCOUNT, account.getUuid());
appData.putString(EXTRA_SEARCH_FOLDER, folderName);
startSearch(null, false, appData, false);
} else {
// TODO Handle the case where we're searching from within a search result.
startSearch(null, false, null, false);
}
return true;
}
@Override
public void showThread(Account account, String folderName, long threadRootId) {
showMessageViewPlaceHolder();
LocalSearch tmpSearch = new LocalSearch();
tmpSearch.addAccountUuid(account.getUuid());
tmpSearch.and(SearchField.THREAD_ID, String.valueOf(threadRootId), Attribute.EQUALS);
MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, true, false);
addMessageListFragment(fragment, true);
}
private void showMessageViewPlaceHolder() {
removeMessageViewFragment();
// Add placeholder view if necessary
if (mMessageViewPlaceHolder.getParent() == null) {
mMessageViewContainer.addView(mMessageViewPlaceHolder);
}
mMessageListFragment.setActiveMessage(null);
}
/**
* Remove MessageViewFragment if necessary.
*/
private void removeMessageViewFragment() {
if (mMessageViewFragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(mMessageViewFragment);
mMessageViewFragment = null;
ft.commit();
showDefaultTitleView();
}
}
private void removeMessageListFragment() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(mMessageListFragment);
mMessageListFragment = null;
ft.commit();
}
@Override
public void remoteSearchStarted() {
// Remove action button for remote search
configureMenu(mMenu);
}
@Override
public void goBack() {
FragmentManager fragmentManager = getFragmentManager();
if (mDisplayMode == DisplayMode.MESSAGE_VIEW) {
showMessageList();
} else if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
} else if (mMessageListFragment.isManualSearch()) {
finish();
} else if (!mSingleFolderMode) {
onAccounts();
} else {
onShowFolderList();
}
}
@Override
public void enableActionBarProgress(boolean enable) {
if (mMenuButtonCheckMail != null && mMenuButtonCheckMail.isVisible()) {
mActionBarProgress.setVisibility(ProgressBar.GONE);
if (enable) {
mMenuButtonCheckMail
.setActionView(mActionButtonIndeterminateProgress);
} else {
mMenuButtonCheckMail.setActionView(null);
}
} else {
if (mMenuButtonCheckMail != null)
mMenuButtonCheckMail.setActionView(null);
if (enable) {
mActionBarProgress.setVisibility(ProgressBar.VISIBLE);
} else {
mActionBarProgress.setVisibility(ProgressBar.GONE);
}
}
}
@Override
public void displayMessageSubject(String subject) {
if (mDisplayMode == DisplayMode.MESSAGE_VIEW) {
mActionBarSubject.setText(subject);
} else {
mActionBarSubject.showSubjectInMessageHeader();
}
}
@Override
public void showNextMessageOrReturn() {
if (K9.messageViewReturnToList() || !showLogicalNextMessage()) {
if (mDisplayMode == DisplayMode.SPLIT_VIEW) {
showMessageViewPlaceHolder();
} else {
showMessageList();
}
}
}
/**
* Shows the next message in the direction the user was displaying messages.
*
* @return {@code true}
*/
private boolean showLogicalNextMessage() {
boolean result = false;
if (mLastDirection == NEXT) {
result = showNextMessage();
} else if (mLastDirection == PREVIOUS) {
result = showPreviousMessage();
}
if (!result) {
result = showNextMessage() || showPreviousMessage();
}
return result;
}
@Override
public void setProgress(boolean enable) {
setProgressBarIndeterminateVisibility(enable);
}
@Override
public void messageHeaderViewAvailable(MessageHeader header) {
mActionBarSubject.setMessageHeader(header);
}
private boolean showNextMessage() {
MessageReference ref = mMessageViewFragment.getMessageReference();
if (ref != null) {
if (mMessageListFragment.openNext(ref)) {
mLastDirection = NEXT;
return true;
}
}
return false;
}
private boolean showPreviousMessage() {
MessageReference ref = mMessageViewFragment.getMessageReference();
if (ref != null) {
if (mMessageListFragment.openPrevious(ref)) {
mLastDirection = PREVIOUS;
return true;
}
}
return false;
}
private void showMessageList() {
mMessageListWasDisplayed = true;
mDisplayMode = DisplayMode.MESSAGE_LIST;
mViewSwitcher.showFirstView();
mMessageListFragment.setActiveMessage(null);
showDefaultTitleView();
configureMenu(mMenu);
}
private void showMessageView() {
mDisplayMode = DisplayMode.MESSAGE_VIEW;
if (!mMessageListWasDisplayed) {
mViewSwitcher.setAnimateFirstView(false);
}
mViewSwitcher.showSecondView();
showMessageTitleView();
configureMenu(mMenu);
}
@Override
public void updateMenu() {
invalidateOptionsMenu();
}
@Override
public void disableDeleteAction() {
mMenu.findItem(R.id.delete).setEnabled(false);
}
private void onToggleTheme() {
if (K9.getK9MessageViewTheme() == K9.Theme.DARK) {
K9.setK9MessageViewThemeSetting(K9.Theme.LIGHT);
} else {
K9.setK9MessageViewThemeSetting(K9.Theme.DARK);
}
new Thread(new Runnable() {
@Override
public void run() {
Context appContext = getApplicationContext();
Preferences prefs = Preferences.getPreferences(appContext);
StorageEditor editor = prefs.getStorage().edit();
K9.save(editor);
editor.commit();
}
}).start();
recreate();
}
private void showDefaultTitleView() {
mActionBarMessageView.setVisibility(View.GONE);
mActionBarMessageList.setVisibility(View.VISIBLE);
if (mMessageListFragment != null) {
mMessageListFragment.updateTitle();
}
mActionBarSubject.setMessageHeader(null);
}
private void showMessageTitleView() {
mActionBarMessageList.setVisibility(View.GONE);
mActionBarMessageView.setVisibility(View.VISIBLE);
if (mMessageViewFragment != null) {
displayMessageSubject(null);
mMessageViewFragment.updateTitle();
}
}
@Override
public void onSwitchComplete(int displayedChild) {
if (displayedChild == 0) {
removeMessageViewFragment();
}
}
@Override
public void startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags) throws SendIntentException {
requestCode |= REQUEST_MASK_PENDING_INTENT;
super.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode & REQUEST_MASK_PENDING_INTENT) == REQUEST_MASK_PENDING_INTENT) {
requestCode ^= REQUEST_MASK_PENDING_INTENT;
if (mMessageViewFragment != null) {
mMessageViewFragment.onPendingIntentResult(requestCode, resultCode, data);
}
}
}
}
|
public class Solution {
List<List<String>> res;
public List<List<String>> partition(String s) {
res = new ArrayList<List<String>>();
if (s.isEmpty()) return res;
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
map.put(0, new ArrayList<String>());
map.get(0).add(s.substring(0, 1));
for (int i = 1; i < s.length(); i++) {
map.put(i, new ArrayList<String>());
map.get(i).add(s.substring(i, i + 1));
// even length palindrome
int low = i - 1, high = i;
while (low >= 0 && high < s.length() && s.charAt(low) == s.charAt(high)) {
map.get(low).add(s.substring(low, high + 1));
low
high++;
}
// odd length palindrome
low = i - 1;
high = i + 1;
while (low >= 0 && high < s.length() && s.charAt(low) == s.charAt(high)) {
map.get(low).add(s.substring(low, high + 1));
low
high++;
}
}
partitionHelper(s, map, new Stack<String>(), 0);
return res;
}
private void partitionHelper(String s, Map<Integer, List<String>> map, Stack<String> ans, int index) {
if (index == s.length()) {
res.add(new ArrayList<String>(ans));
return;
}
for (int i = 0; i < map.get(index).size(); i++) {
String temp = map.get(index).get(i);
ans.add(temp);
partitionHelper(s, map, ans, index + temp.length());
ans.pop();
}
}
}
|
// $Id: ChatPanel.java 3273 2004-12-14 20:12:59Z mdb $
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.toybox.client;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JViewport;
import javax.swing.event.AncestorEvent;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import com.samskivert.swing.GroupLayout;
import com.samskivert.swing.HGroupLayout;
import com.samskivert.swing.VGroupLayout;
import com.samskivert.swing.event.AncestorAdapter;
import com.samskivert.util.StringUtil;
import com.threerings.util.MessageBundle;
import com.threerings.util.Name;
import com.threerings.crowd.chat.client.ChatDirector;
import com.threerings.crowd.chat.client.ChatDisplay;
import com.threerings.crowd.chat.data.ChatCodes;
import com.threerings.crowd.chat.data.ChatMessage;
import com.threerings.crowd.chat.data.SystemMessage;
import com.threerings.crowd.chat.data.TellFeedbackMessage;
import com.threerings.crowd.chat.data.UserMessage;
import com.threerings.crowd.client.OccupantObserver;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.OccupantInfo;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.toybox.data.ToyBoxCodes;
import com.threerings.toybox.util.ToyBoxContext;
import static com.threerings.toybox.Log.log;
public class ChatPanel extends JPanel
implements ActionListener, ChatDisplay, OccupantObserver, PlaceView
{
/** The message bundle identifier for chat translations. */
public static final String CHAT_MSGS = "client.chat";
public ChatPanel (ToyBoxContext ctx)
{
this(ctx, false);
}
public ChatPanel (ToyBoxContext ctx, boolean horizontal)
{
// keep this around for later
_ctx = ctx;
// create our chat director and register ourselves with it
_chatdtr = ctx.getChatDirector();
_chatdtr.addChatDisplay(this);
// register as an occupant observer
_ctx.getOccupantDirector().addOccupantObserver(this);
GroupLayout gl = new VGroupLayout(GroupLayout.STRETCH);
gl.setOffAxisPolicy(GroupLayout.STRETCH);
setLayout(gl);
setOpaque(false);
// create our scrolling chat text display
_text = new JTextPane();
_text.setOpaque(false);
_text.setEditable(false);
// we need to create an ultra-custom scroll pane that combines the
// safe-scroll-pane stuff with a painted background image
add(new JScrollPane(_text) {
protected JViewport createViewport ()
{
JViewport vp = new JViewport() {
public void setViewPosition (Point p) {
super.setViewPosition(p);
// simple scroll mode results in setViewPosition
// causing our view to become invalid, but nothing
// ever happens to queue up a revalidate for said
// view, so we have to do it here
Component c = getView();
if (c instanceof JComponent) {
((JComponent)c).revalidate();
}
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
// start with the light blue background
g.setColor(ToyBoxUI.LIGHT_BLUE);
g.fillRect(0, 0, getWidth(), getHeight());
// and draw our background image in the lower left
if (_bgimg != null) {
int yoff = getHeight() - _bgimg.getHeight();
g.drawImage(_bgimg, getX(), getY()+yoff, null);
}
}
};
vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
return vp;
}
});
// create our styles and add those to the text pane
createStyles(_text);
// add a label for the text entry stuff
String htext = _ctx.xlate(ToyBoxCodes.TOYBOX_MSGS, "m.chat_help");
if (!horizontal) {
add(new JLabel(htext), GroupLayout.FIXED);
}
// create a horizontal group for the text entry bar
gl = new HGroupLayout(GroupLayout.STRETCH);
JPanel epanel = new JPanel(gl);
if (horizontal) {
epanel.add(new JLabel(htext), GroupLayout.FIXED);
}
epanel.setOpaque(false);
epanel.add(_entry = new JTextField());
_entry.setActionCommand("send");
_entry.addActionListener(this);
_entry.setEnabled(false);
_send = new JButton(_ctx.xlate(ToyBoxCodes.TOYBOX_MSGS, "m.send"));
_send.setEnabled(false);
_send.addActionListener(this);
_send.setActionCommand("send");
if (horizontal) {
epanel.add(_send, GroupLayout.FIXED);
}
add(epanel, GroupLayout.FIXED);
// load up our chat background image
try {
InputStream in = getClass().getClassLoader().getResourceAsStream(
"rsrc/media/chat_background.png");
if (in != null) {
_bgimg = ImageIO.read(in);
}
} catch (Exception e) {
log.log(Level.WARNING, "Failed to load background image.", e);
}
// listen to ancestor events to request focus when added
addAncestorListener(new AncestorAdapter() {
public void ancestorAdded (AncestorEvent e) {
if (_focus) {
_entry.requestFocus();
}
}
});
}
/**
* For applications where the chat box has extremely limited space,
* the send button can be removed to leave more space for the text
* input box.
*
* @deprectated Pass non-horizontal to the constructor instead.
*/
public void removeSendButton ()
{
// this is now handled by specifying a horizontal or vertical
// layout when creating the chat panel
}
/**
* Sets whether the chat box text entry field requests the keyboard
* focus when the panel receives {@link
* AncestorListener#ancestorAdded} or {@link PlaceView#willEnterPlace}
* events.
*/
public void setRequestFocus (boolean focus)
{
_focus = focus;
}
protected void createStyles (JTextPane text)
{
StyleContext sctx = StyleContext.getDefaultStyleContext();
Style defstyle = sctx.getStyle(StyleContext.DEFAULT_STYLE);
_nameStyle = text.addStyle("name", defstyle);
StyleConstants.setForeground(_nameStyle, Color.blue);
_msgStyle = text.addStyle("msg", defstyle);
StyleConstants.setForeground(_msgStyle, Color.black);
_errStyle = text.addStyle("err", defstyle);
StyleConstants.setForeground(_errStyle, Color.red);
_noticeStyle = text.addStyle("notice", defstyle);
StyleConstants.setForeground(_noticeStyle, Color.magenta.darker());
_feedbackStyle = text.addStyle("feedback", defstyle);
StyleConstants.setForeground(_feedbackStyle, Color.green.darker());
}
// documentation inherited
public void actionPerformed (ActionEvent e)
{
String cmd = e.getActionCommand();
if (cmd.equals("send")) {
sendText();
} else {
System.out.println("Unknown action event: " + cmd);
}
}
// documentation inherited
public void occupantEntered (OccupantInfo info)
{
displayOccupantMessage("*** " + info.username + " entered.");
}
// documentation inherited
public void occupantLeft (OccupantInfo info)
{
displayOccupantMessage("*** " + info.username + " left.");
}
// documentation inherited
public void occupantUpdated (OccupantInfo oinfo, OccupantInfo info)
{
}
protected void displayOccupantMessage (String message)
{
appendAndScroll(message, _noticeStyle);
}
protected void sendText ()
{
String text = _entry.getText().trim();
// if the message to send begins with /tell then parse it and
// generate a tell request rather than a speak request
if (text.startsWith("/tell ")) {
StringTokenizer tok = new StringTokenizer(text);
// there should be at least three tokens: '/tell target word'
if (tok.countTokens() < 3) {
displayError("m.usage_tell");
return;
}
// skip the /tell and grab the username
tok.nextToken();
String username = tok.nextToken();
// now strip off everything up to the username to get the
// message
int uidx = text.indexOf(username);
String message = text.substring(uidx + username.length()).trim();
// request to send this text as a tell message
_chatdtr.requestTell(new Name(username), message, null);
} else if (text.startsWith("/clear")) {
// clear the chat box
_chatdtr.clearDisplays();
} else if (text.startsWith("/broadcast ")) {
text = text.substring(text.indexOf(" ")+1);
_chatdtr.requestBroadcast(text);
} else if (text.startsWith("/em ") ||
text.startsWith("/emote ") ||
text.startsWith("/me ")) {
text = text.substring(text.indexOf(" ")+1);
_chatdtr.requestSpeak(
_room.speakService, text, ChatCodes.EMOTE_MODE);
} else if (text.startsWith("/who")) {
// dump the occupants of the room to the chat box
displayFeedback("m.who_header");
Iterator iter = _room.occupantInfo.iterator();
while (iter.hasNext()) {
OccupantInfo info = (OccupantInfo)iter.next();
String msg = "m.who_active";
switch (info.status) {
case OccupantInfo.IDLE: msg = "m.who_idle"; break;
case OccupantInfo.DISCONNECTED: msg = "m.who_discon"; break;
}
displayFeedback(MessageBundle.tcompose(msg, info.username));
}
} else if (text.startsWith("/help")) {
displayFeedback("m.chat_help");
} else if (text.startsWith("/")) {
int sidx = text.indexOf(" ");
if (sidx != -1) {
text = text.substring(0, sidx);
}
displayError(MessageBundle.tcompose("m.unknown_command", text));
} else if (!StringUtil.blank(text)) {
// request to send this text as a chat message
_chatdtr.requestSpeak(
_room.speakService, text, ChatCodes.DEFAULT_MODE);
}
// clear out the input because we sent a request
_entry.setText("");
}
// documentation inherited from interface ChatDisplay
public void clear ()
{
_text.setText("");
}
// documentation inherited from interface ChatDisplay
public void displayMessage (ChatMessage message)
{
if (message instanceof UserMessage) {
UserMessage msg = (UserMessage) message;
String type = "m.chat_prefix_" + msg.mode;
Style msgStyle = _msgStyle;
if (msg.localtype == ChatCodes.USER_CHAT_TYPE) {
type = "m.chat_prefix_tell";
}
if (msg.mode == ChatCodes.BROADCAST_MODE) {
msgStyle = _noticeStyle;
}
String speaker = MessageBundle.tcompose(type, msg.speaker);
speaker = _ctx.xlate(CHAT_MSGS, speaker);
appendAndScroll(speaker, msg.message, msgStyle);
} else if (message instanceof SystemMessage) {
appendAndScroll(message.message, _noticeStyle);
} else if (message instanceof TellFeedbackMessage) {
appendAndScroll(message.message, _feedbackStyle);
} else {
log.warning("Received unknown message type [message=" +
message + "].");
}
}
protected void displayFeedback (String message)
{
appendAndScroll(_ctx.xlate(CHAT_MSGS, message), _feedbackStyle);
}
protected void displayError (String message)
{
appendAndScroll(_ctx.xlate(CHAT_MSGS, message), _errStyle);
}
protected void appendAndScroll (String message, Style style)
{
if (_text.getDocument().getLength() > 0) {
message = "\n" + message;
}
append(message, style);
_text.scrollRectToVisible(
new Rectangle(0, _text.getHeight(), _text.getWidth(), 1));
}
protected void appendAndScroll (String speaker, String message, Style style)
{
if (_text.getDocument().getLength() > 0) {
speaker = "\n" + speaker;
}
append(speaker + " ", _nameStyle);
append(message, style);
_text.scrollRectToVisible(
new Rectangle(0, _text.getHeight(), _text.getWidth(), 1));
}
/**
* Append the specified text in the specified style.
*/
protected void append (String text, Style style)
{
Document doc = _text.getDocument();
try {
doc.insertString(doc.getLength(), text, style);
} catch (BadLocationException ble) {
log.warning("Unable to insert text!? [error=" + ble + "].");
}
}
public void willEnterPlace (PlaceObject place)
{
// enable our chat input elements since we're now somewhere that
// we can chat
_entry.setEnabled(true);
_send.setEnabled(true);
if (_focus) {
_entry.requestFocus();
}
_room = place;
}
// documentation inherited
public void didLeavePlace (PlaceObject place)
{
_room = null;
}
// documentation inherited
public Dimension getPreferredSize ()
{
Dimension size = super.getPreferredSize();
// always prefer a sensible but not overly large width. this also
// prevents us from inheriting a foolishly large preferred width
// from the JTextPane which sometimes decides it wants to be as
// wide as its widest line of text rather than wrap that line of
// text.
size.width = PREFERRED_WIDTH;
return size;
}
protected ToyBoxContext _ctx;
protected ChatDirector _chatdtr;
protected PlaceObject _room;
protected boolean _focus = true;
protected JComboBox _roombox;
protected JTextPane _text;
protected JButton _send;
protected JTextField _entry;
protected BufferedImage _bgimg;
protected Style _nameStyle;
protected Style _msgStyle;
protected Style _errStyle;
protected Style _noticeStyle;
protected Style _feedbackStyle;
/** A width that isn't so skinny that the text is teeny. */
protected static final int PREFERRED_WIDTH = 200;
}
|
package org.openprovenance.prov.rdf;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import org.openprovenance.prov.xml.ActedOnBehalfOf;
import org.openprovenance.prov.xml.AlternateOf;
import org.openprovenance.prov.xml.Attribute;
import org.openprovenance.prov.xml.Document;
import org.openprovenance.prov.xml.HasExtensibility;
import org.openprovenance.prov.xml.HasLabel;
import org.openprovenance.prov.xml.HasLocation;
import org.openprovenance.prov.xml.HasRole;
import org.openprovenance.prov.xml.HasType;
import org.openprovenance.prov.xml.MentionOf;
import org.openprovenance.prov.xml.NamedBundle;
import org.openprovenance.prov.xml.ProvFactory;
import org.openprovenance.prov.xml.SpecializationOf;
import org.openprovenance.prov.xml.URIWrapper;
import org.openprovenance.prov.xml.Used;
import org.openprovenance.prov.xml.WasAssociatedWith;
import org.openprovenance.prov.xml.WasAttributedTo;
import org.openprovenance.prov.xml.WasDerivedFrom;
import org.openprovenance.prov.xml.WasEndedBy;
import org.openprovenance.prov.xml.WasGeneratedBy;
import org.openprovenance.prov.xml.WasInfluencedBy;
import org.openprovenance.prov.xml.WasInformedBy;
import org.openprovenance.prov.xml.WasInvalidatedBy;
import org.openprovenance.prov.xml.WasStartedBy;
import org.openrdf.model.BNode;
import org.openrdf.model.Literal;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.impl.BNodeImpl;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.rio.helpers.RDFHandlerBase;
public class RdfCollector extends RDFHandlerBase {
public static String PROV = "http://www.w3.org/ns/prov
public static String XMLS = "http://www.w3.org/2001/XMLSchema
enum ProvType
{
ENTITY("Entity"), AGENT("Agent"), ACTIVITY("Activity"), INFLUENCE(
"Influence"),
BUNDLE("Bundle", ProvType.ENTITY),
ORGANIZATION("Organization", ProvType.AGENT),
PERSON("Person", ProvType.AGENT),
SOFTWAREAGENT("SoftwareAgent", ProvType.AGENT),
LOCATION("Location"),
ROLE("Role"),
PLAN("Plan", ProvType.ENTITY),
COLLECTION("Collection", ProvType.ENTITY),
EMPTYCOLLECTION("EmptyCollection", ProvType.COLLECTION),
INSTANTANEOUSEVENT("InstantaneousEvent"),
ENTITYINFLUENCE("EntityInfluence", ProvType.INFLUENCE),
ACTIVITYINFLUENCE("ActivityInfluence", ProvType.INFLUENCE),
AGENTINFLUENCE("AgentInfluence", ProvType.INFLUENCE),
ASSOCIATION("Association", ProvType.AGENTINFLUENCE),
ATTRIBUTION("Attribution", ProvType.AGENTINFLUENCE),
COMMUNICATION("Communication", ProvType.AGENTINFLUENCE),
DELEGATION("Delegation", ProvType.AGENTINFLUENCE),
DERIVATION("Derivation", ProvType.ENTITYINFLUENCE),
QUOTATION("Quotation", ProvType.ENTITYINFLUENCE), REVISION("Revision",
ProvType.ENTITYINFLUENCE), PRIMARYSOURCE("PrimarySource",
ProvType.ENTITYINFLUENCE),
END("End", new ProvType[] { ProvType.INSTANTANEOUSEVENT,
ProvType.ENTITYINFLUENCE }),
START("Start", new ProvType[] { ProvType.INSTANTANEOUSEVENT,
ProvType.ENTITYINFLUENCE }),
GENERATION("Generation", new ProvType[] { ProvType.INSTANTANEOUSEVENT,
ProvType.ACTIVITYINFLUENCE }),
INVALIDATION("Invalidation", new ProvType[] {
ProvType.INSTANTANEOUSEVENT, ProvType.ACTIVITYINFLUENCE }),
USAGE("Usage", new ProvType[] { ProvType.INSTANTANEOUSEVENT,
ProvType.ENTITYINFLUENCE });
private static final Map<String, ProvType> lookup = new HashMap<String, ProvType>();
static
{
for (ProvType provStatement : EnumSet.allOf(ProvType.class))
lookup.put(provStatement.getURI(), provStatement);
}
private String uri;
private ProvType[] extendsTypes;
private ProvType(String localName)
{
this.uri = PROV + localName;
this.extendsTypes = new ProvType[] {};
}
private ProvType(String localName, ProvType extendsType)
{
this(localName);
this.extendsTypes = new ProvType[] { extendsType };
}
private ProvType(String localName, ProvType[] extendsTypes)
{
this(localName);
this.extendsTypes = extendsTypes;
}
public String getURI()
{
return uri;
}
public ProvType[] getExtends()
{
return this.extendsTypes;
}
public static ProvType lookup(String uri)
{
return lookup.get(uri);
}
public String toString()
{
return uri;
}
}
protected ProvFactory pFactory;
protected HashMap<QName, HashMap<QName, List<Statement>>> collators;
private Hashtable<QName, BundleHolder> bundles;
protected Document document;
private Hashtable<String, String> revnss;
public RdfCollector(ProvFactory pFactory)
{
this.pFactory = pFactory;
this.collators = new HashMap<QName, HashMap<QName, List<Statement>>>();
this.revnss = new Hashtable<String, String>();
this.document = pFactory.newDocument();
this.bundles = new Hashtable<QName, BundleHolder>();
document.setNss(new Hashtable<String, String>());
handleNamespace("xsd", XMLS);
}
private HashMap<QName, List<Statement>> getCollator(Resource context)
{
return this.collators.get(convertResourceToQName(context));
}
@Override
public void handleNamespace(String prefix, String namespace)
{
this.document.getNss().put(prefix, namespace);
pFactory.setNamespaces(this.document.getNss());
this.revnss.put(namespace, prefix);
}
private boolean isProvURI(URI uri)
{
if (!uri.getNamespace().equals(PROV))
{
return false;
}
return true;
}
private BundleHolder getBundleHolder(QName context)
{
if (context == null)
context = new QName("");
if (!bundles.containsKey(context))
{
bundles.put(context, new BundleHolder());
}
return bundles.get(context);
}
protected void store(QName context,
org.openprovenance.prov.xml.Element element)
{
if (element instanceof org.openprovenance.prov.xml.Activity)
{
getBundleHolder(context).addActivity(
(org.openprovenance.prov.xml.Activity) element);
} else if (element instanceof org.openprovenance.prov.xml.Entity)
{
getBundleHolder(context).addEntity(
(org.openprovenance.prov.xml.Entity) element);
} else if (element instanceof org.openprovenance.prov.xml.Agent)
{
getBundleHolder(context).addAgent(
(org.openprovenance.prov.xml.Agent) element);
}
}
protected void store(QName context,
org.openprovenance.prov.xml.Relation0 relation0)
{
getBundleHolder(context).addStatement(
(org.openprovenance.prov.xml.Statement) relation0);
}
/* Utility functions */
protected List<Statement> getStatementsForPredicate(QName context,
QName qname, String uri)
{
ArrayList<Statement> statements = new ArrayList<Statement>();
for (Statement statement : collators.get(context).get(qname))
{
if (statement.getPredicate().stringValue().equals(uri))
{
statements.add(statement);
}
}
return statements;
}
protected Statement getSingleStatementForPredicate(QName context,
QName qname, String uri)
{
List<Statement> statements = getStatementsForPredicate(context, qname,
uri);
assert (statements.size() <= 1);
Statement statement = null;
if (statements.size() == 1)
{
statement = statements.get(0);
}
return statement;
}
protected ProvType[] getResourceTypes(QName context, QName qname)
{
List<Statement> statements = collators.get(context).get(qname);
List<ProvType> options = new ArrayList<ProvType>();
for (Statement statement : statements)
{
if (statement.getPredicate().equals(RDF.TYPE))
{
Value value = statement.getObject();
if (value instanceof URI && !isProvURI((URI) value))
{
continue;
}
ProvType provType = ProvType.lookup(value.stringValue());
options.add(provType);
}
}
if (options.size() > 1)
{
List<ProvType> cloned = new ArrayList<ProvType>(options);
for (ProvType option : options)
{
for (ProvType extended : option.getExtends())
{
cloned.remove(extended);
}
}
options = cloned;
}
return options.toArray(new ProvType[] {});
}
protected Object valueToObject(Value value)
{
if (value instanceof Literal)
{
return decodeLiteral((Literal) value);
} else if (value instanceof URI)
{
URI uri = (URI) (value);
URIWrapper uw = new URIWrapper();
uw.setValue(java.net.URI.create(uri.toString()));
return uw;
} else if (value instanceof BNode)
{
return new QName(((BNode) (value)).getID());
} else
{
return null;
}
}
protected QName convertResourceToQName(Resource resource)
{
if (resource instanceof URI)
{
return convertURIToQName((URI) resource);
} else if (resource instanceof BNode)
{
return new QName(((BNode) (resource)).getID());
} else
{
return null;
}
}
protected Object decodeLiteral(Literal literal)
{
String dataType = XMLS + "string";
if (literal.getLanguage() != null)
{
return pFactory.newInternationalizedString(literal.stringValue(),
literal.getLanguage());
}
if (literal.getDatatype() != null)
{
if (literal instanceof URI)
{
QName qname = (QName) pFactory.newQName(literal.getDatatype()
.stringValue());
dataType = qname.getNamespaceURI() + qname.getLocalPart();
} else
{
dataType = literal.getDatatype().stringValue();
}
}
if (dataType.equals(XMLS + "QName"))
{
return pFactory.newQName(literal.stringValue());
} else if (dataType.equals(XMLS + "string"))
{
return literal.stringValue();
} else if (dataType.equals(XMLS + "dateTime"))
{
return literal.calendarValue();
} else if (dataType.equals(XMLS + "int"))
{
return literal.intValue();
} else if (dataType.equals(XMLS + "integer"))
{
return literal.integerValue();
} else if (dataType.equals(XMLS + "boolean"))
{
return literal.booleanValue();
} else if (dataType.equals(XMLS + "double"))
{
return literal.doubleValue();
} else if (dataType.equals(XMLS + "float"))
{
return literal.floatValue();
} else if (dataType.equals(XMLS + "long"))
{
return literal.longValue();
} else if (dataType.equals(XMLS + "short"))
{
return literal.shortValue();
} else if (dataType.equals(XMLS + "byte"))
{
return literal.byteValue();
} else if (dataType.equals(XMLS + "decimal"))
{
return literal.decimalValue();
} else if (dataType.equals(XMLS + "anyURI"))
{
URIWrapper uw = new URIWrapper();
uw.setValue(java.net.URI.create(literal.stringValue()));
return uw;
} else
{
// System.out.println("Unhandled::: "+literal.getDatatype());
return literal.stringValue();
}
}
private String getXsdType(String shorttype)
{
String xsdType = "";
if (revnss.containsKey(XMLS))
{
xsdType = revnss.get(XMLS) + ":" + shorttype;
} else
{
xsdType = XMLS + shorttype;
}
return xsdType;
}
/* Prov-specific functions */
protected List<Statement> handleBaseStatements(
org.openprovenance.prov.xml.Statement element, QName context,
QName qname, ProvType type)
{
List<Statement> statements = collators.get(context).get(qname);
for (Statement statement : statements)
{
String predS = statement.getPredicate().stringValue();
if (element instanceof HasType)
{
if (statement.getPredicate().stringValue()
.equals(PROV + "type"))
{
Value value = statement.getObject();
Object obj = valueToObject(statement.getObject());
if (obj != null)
{
Boolean sameAsType = false;
if(obj instanceof QName) {
// TODO: Nasty.
String uriVal = ((QName)(obj)).getNamespaceURI()+((QName)(obj)).getLocalPart();
sameAsType = uriVal.equals(type.toString());
}
if (!sameAsType && !((HasType) element).getType().contains(obj))
{
pFactory.addType((HasType) element, obj);
}
} else
{
System.out.println(value);
System.out.println("Value wasn't a suitable type");
}
}
}
if (element instanceof HasRole)
{
if (predS.equals(PROV + "role")
|| predS.equals(PROV + "hadRole"))
{
String role = statement.getObject().stringValue();
pFactory.addRole((HasRole) element, role);
}
}
if (element instanceof HasLocation)
{
if (predS.equals(PROV + "atLocation")
|| predS.equals(PROV + "location"))
{
Object obj = valueToObject(statement.getObject());
if (obj != null)
{
((HasLocation) element).getLocation().add(obj);
}
}
}
if (element instanceof HasLabel)
{
if (predS.equals(PROV + "label"))
{
Literal lit = (Literal) (statement.getObject());
if (lit.getLanguage() != null)
{
pFactory.addLabel((HasLabel) element,
lit.stringValue(), lit.getLanguage()
.toUpperCase());
} else
{
pFactory.addLabel((HasLabel) element, lit.stringValue());
}
}
}
if (element instanceof HasExtensibility)
{
URI uri = (URI) statement.getPredicate();
Value val = statement.getObject();
if (!isProvURI(uri))
{
if (uri.equals(RDF.TYPE))
{
// Add prov:type
if (element instanceof HasType)
{
if (val instanceof URI)
{
if (!val.toString().equals(type.getURI()))
{
URI valURI = (URI) (val);
String prefix = this.revnss.get(valURI
.getNamespace());
Object typeVal = null;
if (prefix == null)
{
URIWrapper uriWrapper = new URIWrapper();
java.net.URI jURI = java.net.URI
.create(valURI.toString());
uriWrapper.setValue(jURI);
typeVal = uriWrapper;
// System.out.println("info: "+valURI.getNamespace()+" "+valURI.getLocalName());
// valQ = new
// QName(valURI.getNamespace(),
// valURI.getLocalName());
} else
{
typeVal = new QName(
valURI.getNamespace(),
valURI.getLocalName(), prefix);
}
// Avoid adding duplicate types
if (typeVal != null
&& !((HasType) element).getType()
.contains(typeVal))
{
pFactory.addType((HasType) element,
typeVal);
}
}
} else if (val instanceof Literal)
{
Object typeVal = decodeLiteral((Literal) val);
if (typeVal != null
&& !((HasType) element).getType()
.contains(typeVal))
{
pFactory.addType((HasType) element, typeVal);
}
}
}
} else
{
// Retrieve the prefix
String prefix = this.revnss.get(uri.getNamespace());
Attribute attr = null;
if (val instanceof Literal)
{
Literal lit = (Literal) val;
String shortType = "string";
if (lit.getDatatype() != null)
{
shortType = lit.getDatatype().getLocalName();
}
// FIXME: Bug 3 occurs here.
String xsdType = getXsdType(shortType);
attr = pFactory.newAttribute(uri.getNamespace(),
uri.getLocalName(), prefix,
decodeLiteral(lit), xsdType);
} else if (val instanceof Resource)
{
URIWrapper uw = new URIWrapper();
java.net.URI jURI = java.net.URI
.create(val.stringValue());
uw.setValue(jURI);
attr = pFactory.newAttribute(uri.getNamespace(),
uri.getLocalName(), prefix,
uw, getXsdType("anyURI"));
} else
{
System.err.println("Invalid value");
}
if (attr != null)
{
pFactory.addAttribute((HasExtensibility) element,
attr);
}
}
}
}
if (predS.equals(PROV + "wasInfluencedBy"))
{
QName anyQ = convertResourceToQName((Resource) (statement
.getObject()));
WasInfluencedBy wib = pFactory.newWasInfluencedBy((QName) null,
pFactory.newAnyRef(qname), pFactory.newAnyRef(anyQ));
store(convertResourceToQName(statement.getContext()), wib);
}
if (predS.equals(PROV + "influenced"))
{
QName anyQ = convertResourceToQName((Resource) (statement
.getObject()));
WasInfluencedBy wib = pFactory.newWasInfluencedBy((QName) null,
pFactory.newAnyRef(anyQ), pFactory.newAnyRef(qname));
store(convertResourceToQName(statement.getContext()), wib);
}
}
return statements;
}
protected void buildGraph()
{
for (QName contextQ : collators.keySet())
{
HashMap<QName, List<Statement>> collator = collators.get(contextQ);
for (QName qname : collator.keySet())
{
ProvType[] types = getResourceTypes(contextQ, qname);
for (ProvType type : types)
{
switch (type)
{
case ACTIVITY:
createActivity(contextQ, qname);
break;
case AGENT:
case PERSON:
case ORGANIZATION:
case SOFTWAREAGENT:
createAgent(contextQ, qname);
break;
case ENTITY:
case PLAN:
case BUNDLE:
createEntity(contextQ, qname);
break;
default:
}
}
}
}
}
protected void buildBundles()
{
// Add 'default' bundle
if (bundles.containsKey(new QName("")))
{
BundleHolder defaultBundle = bundles.get(new QName(""));
for (org.openprovenance.prov.xml.Activity activity : defaultBundle
.getActivities())
{
document.getEntityOrActivityOrWasGeneratedBy().add(activity);
}
for (org.openprovenance.prov.xml.Agent agent : defaultBundle
.getAgents())
{
document.getEntityOrActivityOrWasGeneratedBy().add(agent);
}
for (org.openprovenance.prov.xml.Entity entity : defaultBundle
.getEntities())
{
document.getEntityOrActivityOrWasGeneratedBy().add(entity);
}
for (org.openprovenance.prov.xml.Statement statement : defaultBundle
.getStatements())
{
document.getEntityOrActivityOrWasGeneratedBy().add(statement);
}
}
for (QName key : bundles.keySet())
{
if (key.getLocalPart().equals(""))
{
continue;
}
BundleHolder bundleHolder = bundles.get(key);
NamedBundle bundle = pFactory.newNamedBundle(key,
bundleHolder.getActivities(), bundleHolder.getEntities(),
bundleHolder.getAgents(), bundleHolder.getStatements());
bundle.setId(key);
document.getEntityOrActivityOrWasGeneratedBy().add(bundle);
}
}
protected void dumpUnhandled()
{
for (QName contextQ : collators.keySet())
{
HashMap<QName, List<Statement>> collator = collators.get(contextQ);
for (QName qname : collator.keySet())
{
if (collator.get(qname).size() > 0)
{
System.out.println("Unhandled statements in " + qname);
for (Statement statement : collator.get(qname))
{
if (isProvURI(statement.getPredicate()))
{
System.out.println(statement);
}
}
}
}
}
}
@Override
public void endRDF()
{
buildGraph();
buildBundles();
}
private QName convertURIToQName(URI uri)
{
// It is not necessary to specify a prefix for a QName. This code was
// breaking on the jpl trace.
QName qname;
if (revnss.containsKey(uri.getNamespace()))
{
String prefix = revnss.get(uri.getNamespace());
qname = new QName(uri.getNamespace(), uri.getLocalName(), prefix);
} else
{
qname = new QName(uri.getNamespace(), uri.getLocalName());
}
return qname;
}
private void createEntity(QName context, QName qname)
{
org.openprovenance.prov.xml.Entity entity = pFactory.newEntity(qname);
List<Statement> statements = collators.get(context).get(qname);
statements = handleBaseStatements(entity, context, qname,
ProvType.ENTITY);
for (Statement statement : statements)
{
String predS = statement.getPredicate().stringValue();
Value value = statement.getObject();
if (value instanceof Resource)
{
QName valueQ = convertResourceToQName((Resource) value);
if (predS.equals(PROV + "wasDerivedFrom"))
{
WasDerivedFrom wdf = pFactory.newWasDerivedFrom(
(QName) null, pFactory.newEntityRef(qname),
pFactory.newEntityRef(valueQ));
store(context, wdf);
} else if (predS.equals(PROV + "hadPrimarySource"))
{
WasDerivedFrom wdf = pFactory.newWasDerivedFrom(
(QName) null, pFactory.newEntityRef(qname),
pFactory.newEntityRef(valueQ));
pFactory.addPrimarySourceType(wdf);
store(context, wdf);
} else if (predS.equals(PROV + "wasQuotedFrom"))
{
WasDerivedFrom wdf = pFactory.newWasDerivedFrom(
(QName) null, pFactory.newEntityRef(qname),
pFactory.newEntityRef(valueQ));
pFactory.addQuotationType(wdf);
store(context, wdf);
} else if (predS.equals(PROV + "wasRevisionOf"))
{
WasDerivedFrom wdf = pFactory.newWasDerivedFrom(
(QName) null, pFactory.newEntityRef(qname),
pFactory.newEntityRef(valueQ));
pFactory.addRevisionType(wdf);
store(context, wdf);
} else if (predS.equals(PROV + "wasGeneratedBy"))
{
WasGeneratedBy wgb = pFactory.newWasGeneratedBy(
(QName) null, pFactory.newEntityRef(qname), null,
pFactory.newActivityRef(valueQ));
store(context, wgb);
} else if (predS.equals(PROV + "alternateOf"))
{
AlternateOf ao = pFactory.newAlternateOf(
pFactory.newEntityRef(qname),
pFactory.newEntityRef(valueQ));
store(context, ao);
} else if (predS.equals(PROV + "specializationOf"))
{
SpecializationOf so = pFactory.newSpecializationOf(
pFactory.newEntityRef(qname),
pFactory.newEntityRef(valueQ));
store(context, so);
} else if (predS.equals(PROV + "wasInvalidatedBy"))
{
WasInvalidatedBy wib = pFactory.newWasInvalidatedBy(
(QName) null, pFactory.newEntityRef(qname),
pFactory.newActivityRef(valueQ));
store(context, wib);
} else if (predS.equals(PROV + "wasAttributedTo"))
{
WasAttributedTo wit = pFactory.newWasAttributedTo(
(QName) null, pFactory.newEntityRef(qname),
pFactory.newAgentRef(valueQ));
store(context, wit);
} else if (predS.equals(PROV + "mentionOf"))
{
Statement asInBundleStatement = getSingleStatementForPredicate(
context, qname, PROV + "asInBundle");
Object o = (asInBundleStatement == null) ? null
: asInBundleStatement.getObject();
QName bundleQ = (o == null) ? null
: convertURIToQName((URI) o);
QName entityQ = (value == null) ? null
: convertURIToQName((URI) value);
MentionOf nmo = pFactory.newMentionOf(
(qname == null) ? null : pFactory
.newEntityRef(qname),
(entityQ == null) ? null : pFactory
.newEntityRef(entityQ),
(bundleQ == null) ? null : pFactory
.newEntityRef(bundleQ));
store(context, nmo);
}
} else if (value instanceof Literal)
{
if (predS.equals(PROV + "generatedAtTime"))
{
// TODO: Unable to implement this.
Object literal = decodeLiteral((Literal) value);
}
if (predS.equals(PROV + "invalidatedAtTime"))
{
// TODO: Unable to implement this.
Object literal = decodeLiteral((Literal) value);
} else if (predS.equals(PROV + "value"))
{
Object literal = decodeLiteral((Literal) value);
entity.setValue(literal);
}
}
}
store(context, entity);
}
private void createAgent(QName context, QName qname)
{
org.openprovenance.prov.xml.Agent agent = pFactory.newAgent(qname);
List<Statement> statements = collators.get(context).get(qname);
statements = handleBaseStatements(agent, context, qname, ProvType.AGENT);
for (Statement statement : statements)
{
String predS = statement.getPredicate().stringValue();
Value value = statement.getObject();
if (value instanceof Resource)
{
if (predS.equals(PROV + "actedOnBehalfOf"))
{
QName agentQ = convertResourceToQName((Resource) value);
ActedOnBehalfOf aobo = pFactory.newActedOnBehalfOf(
(QName) null, pFactory.newAgentRef(qname),
pFactory.newAgentRef(agentQ), null);
store(context, aobo);
}
}
}
store(context, agent);
}
private void createActivity(QName context, QName qname)
{
org.openprovenance.prov.xml.Activity activity = pFactory
.newActivity(qname);
List<Statement> statements = collators.get(context).get(qname);
statements = handleBaseStatements(activity, context, qname,
ProvType.ACTIVITY);
for (Statement statement : statements)
{
String predS = statement.getPredicate().stringValue();
Value value = statement.getObject();
if (value instanceof Resource)
{
QName valueQ = convertResourceToQName((Resource) value);
if (predS.equals(PROV + "wasAssociatedWith"))
{
WasAssociatedWith waw = pFactory.newWasAssociatedWith(
(QName) null, pFactory.newActivityRef(qname),
pFactory.newAgentRef(valueQ));
store(context, waw);
} else if (predS.equals(PROV + "used"))
{
Used used = pFactory.newUsed((QName) null,
pFactory.newActivityRef(qname), null,
pFactory.newEntityRef(valueQ));
store(context, used);
} else if (predS.equals(PROV + "wasStartedBy"))
{
WasStartedBy wsb = pFactory.newWasStartedBy((QName) null,
pFactory.newActivityRef(qname),
pFactory.newEntityRef(valueQ));
store(context, wsb);
} else if (predS.equals(PROV + "generated"))
{
WasGeneratedBy wgb = pFactory.newWasGeneratedBy(
(QName) null, pFactory.newEntityRef(valueQ), null,
pFactory.newActivityRef(qname));
store(context, wgb);
} else if (predS.equals(PROV + "wasEndedBy"))
{
WasEndedBy web = pFactory.newWasEndedBy((QName) null,
pFactory.newActivityRef(qname),
pFactory.newEntityRef(valueQ));
store(context, web);
} else if (predS.equals(PROV + "wasInformedBy"))
{
WasInformedBy wib = pFactory.newWasInformedBy((QName) null,
pFactory.newActivityRef(qname),
pFactory.newActivityRef(valueQ));
store(context, wib);
}
} else if (value instanceof Literal)
{
if (predS.equals(PROV + "startedAtTime"))
{
Object literal = decodeLiteral((Literal) value);
activity.setStartTime((XMLGregorianCalendar) literal);
} else if (predS.equals(PROV + "endedAtTime"))
{
Object literal = decodeLiteral((Literal) value);
activity.setEndTime((XMLGregorianCalendar) literal);
}
}
}
store(context, activity);
}
@Override
public void handleStatement(Statement statement)
{
QName subjectQ = null;
Resource subject = statement.getSubject();
if (subject instanceof BNodeImpl)
{
BNodeImpl bnode = (BNodeImpl) subject;
subjectQ = new QName(bnode.getID());
} else if (subject instanceof URI)
{
URI uri = (URI) subject;
subjectQ = convertURIToQName(uri);
} else
{
System.err.println("Invalid subject resource");
}
QName contextQ = convertResourceToQName(statement.getContext());
if (!collators.containsKey(contextQ))
{
collators.put(contextQ, new HashMap<QName, List<Statement>>());
}
HashMap<QName, List<Statement>> currcollator = getCollator(statement
.getContext());
if (!currcollator.containsKey(subjectQ))
{
currcollator.put(subjectQ, new ArrayList<Statement>());
}
currcollator.get(subjectQ).add(statement);
}
public Document getDocument()
{
return document;
}
}
|
package mondrian.xmla;
import mondrian.olap.*;
import mondrian.olap.Util.PropertyList;
import mondrian.olap4j.MondrianOlap4jDriver;
import mondrian.rolap.RolapConnectionProperties;
import mondrian.test.DiffRepository;
import mondrian.test.TestContext;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.*;
/**
* This test creates 2 catalogs and constraints on one of them.
* Then it runs a few queries to check that the filtering
* occurs as expected.
*/
public class XmlaMetaDataConstraintsTest extends XmlaBaseTestCase {
protected void setUp() throws Exception {
super.setUp();
Class.forName(MondrianOlap4jDriver.class.getName());
}
protected Map<String, String> getCatalogNameUrls(TestContext testContext) {
if (catalogNameUrls == null) {
catalogNameUrls = new TreeMap<String, String>();
String connectString = testContext.getConnectString();
Util.PropertyList connectProperties =
Util.parseConnectString(connectString);
String catalog = connectProperties.get(
RolapConnectionProperties.Catalog.name());
// read the catalog and copy it to another temp file.
File outputFile1 = null;
File outputFile2 = null;
try {
// Output
outputFile1 = File.createTempFile("cat1", ".xml");
outputFile2 = File.createTempFile("cat2", ".xml");
outputFile1.deleteOnExit();
outputFile2.deleteOnExit();
BufferedWriter bw1 =
new BufferedWriter(new FileWriter(outputFile1));
BufferedWriter bw2 =
new BufferedWriter(new FileWriter(outputFile2));
// Input
DataInputStream in =
new DataInputStream(Util.readVirtualFile(catalog));
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
bw1.write(
strLine.replaceAll("FoodMart", "FoodMart1schema"));
bw1.newLine();
bw2.write(
strLine.replaceAll("FoodMart", "FoodMart2schema"));
bw2.newLine();
}
in.close();
bw1.close();
bw2.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
catalogNameUrls.put("FoodMart1", outputFile1.getAbsolutePath());
catalogNameUrls.put("FoodMart2", outputFile2.getAbsolutePath());
}
return catalogNameUrls;
}
protected String filterConnectString(String original) {
PropertyList props = Util.parseConnectString(original);
if (props.get(RolapConnectionProperties.Catalog.name()) != null) {
props.remove(RolapConnectionProperties.Catalog.name());
}
return props.toString();
}
public void testDBSchemataFiltered() throws Exception {
doTest(
RowsetDefinition.DBSCHEMA_SCHEMATA.name(), "FoodMart2");
doTest(
RowsetDefinition.DBSCHEMA_SCHEMATA.name(), "FoodMart1");
}
public void testDBSchemataFilteredByRestraints() throws Exception {
doTest(
RowsetDefinition.DBSCHEMA_SCHEMATA.name(), "FoodMart2");
doTest(
RowsetDefinition.DBSCHEMA_SCHEMATA.name(), "FoodMart1");
}
public void testCatalogsFiltered() throws Exception {
doTest(
RowsetDefinition.DBSCHEMA_CATALOGS.name(), "FoodMart2");
doTest(
RowsetDefinition.DBSCHEMA_CATALOGS.name(), "FoodMart1");
}
public void testCatalogsFilteredByRestraints() throws Exception {
doTest(
RowsetDefinition.DBSCHEMA_CATALOGS.name(), "FoodMart2");
doTest(
RowsetDefinition.DBSCHEMA_CATALOGS.name(), "FoodMart1");
}
public void testCubesFiltered() throws Exception {
doTest(
RowsetDefinition.MDSCHEMA_CUBES.name(), "FoodMart2");
doTest(
RowsetDefinition.MDSCHEMA_CUBES.name(), "FoodMart1");
}
public void testCubesFilteredByRestraints() throws Exception {
doTest(
RowsetDefinition.MDSCHEMA_CUBES.name(), "FoodMart2");
doTest(
RowsetDefinition.MDSCHEMA_CUBES.name(), "FoodMart1");
}
private void doTest(String requestType, String catalog)
throws Exception
{
Properties props = new Properties();
props.setProperty(REQUEST_TYPE_PROP, requestType);
props.setProperty(DATA_SOURCE_INFO_PROP, DATA_SOURCE_INFO);
props.setProperty(CATALOG_NAME_PROP, catalog);
try {
doTest(requestType, props, TestContext.instance());
} catch (Throwable t) {
t.printStackTrace();
throw new Exception(t);
}
}
protected DiffRepository getDiffRepos() {
return DiffRepository.lookup(XmlaMetaDataConstraintsTest.class);
}
protected Class<? extends XmlaRequestCallback> getServletCallbackClass() {
return null;
}
protected String getSessionId(Action action) {
throw new UnsupportedOperationException();
}
}
// End XmlaMetaDataConstraintsTest.java
|
package mod._sc;
import java.io.PrintWriter;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.AccessibilityTools;
import util.SOfficeFactory;
import util.utils;
import com.sun.star.accessibility.AccessibleRole;
import com.sun.star.accessibility.XAccessible;
import com.sun.star.awt.XWindow;
import com.sun.star.container.XIndexAccess;
import com.sun.star.frame.XModel;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.table.XCell;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
/**
* Test for accessible object of spreadsheet document.<p>
* Object implements the following interfaces:
* <ul>
* <li> <code>::com::sun::star::accessibility::XAccessibleComponent</code>
* </li>
* <li> <code>::com::sun::star::accessibility::XAccessibleContext</code>
* </li>
* <li> <code>::com::sun::star::accessibility::XAccessibleSelection
* </code></li>
* <li><code>::com::sun::star::accessibility::XAccessibleTable</code>
* </li>
* </ul>
* @see com.sun.star.accessibility.XAccessibleComponent
* @see com.sun.star.accessibility.XAccessibleContext
* @see com.sun.star.accessibility.XAccessibleSelection
* @see com.sun.star.accessibility.XAccessibleTable
* @see ifc.accessibility._XAccessibleComponent
* @see ifc.accessibility._XAccessibleContext
* @see ifc.accessibility._XAccessibleSelection
* @see ifc.accessibility._XAccessibleTable
*/
public class ScAccessibleSpreadsheet extends TestCase {
static XSpreadsheetDocument xSheetDoc = null;
/**
* Creates a spreadsheet document.
*/
protected void initialize( TestParameters tParam, PrintWriter log ) {
SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF() );
try {
log.println( "creating a Spreadsheet document" );
xSheetDoc = SOF.createCalcDoc(null);
} catch ( com.sun.star.uno.Exception e ) {
// Some exception occures.FAILED
e.printStackTrace( log );
throw new StatusException( "Couldn't create document", e );
}
}
/**
* Disposes a spreadsheet document.
*/
protected void cleanup( TestParameters tParam, PrintWriter log ) {
log.println( " disposing xSheetDoc " );
XComponent oComp = (XComponent)UnoRuntime.queryInterface
(XComponent.class, xSheetDoc);
util.DesktopTools.closeDoc(oComp);
}
/**
* Creating a Testenvironment for the interfaces to be tested.
* Obtains the accessible object for the spreadsheet.
*/
public synchronized TestEnvironment createTestEnvironment
( TestParameters Param, PrintWriter log )
throws StatusException {
XInterface oObj = null;
XModel xModel = (XModel)
UnoRuntime.queryInterface(XModel.class, xSheetDoc);
AccessibilityTools at = new AccessibilityTools();
XWindow xWindow = at.getCurrentWindow((XMultiServiceFactory)Param.getMSF(), xModel);
XAccessible xRoot = at.getAccessibleObject(xWindow);
at.getAccessibleObjectForRole(xRoot, AccessibleRole.TABLE );
oObj = AccessibilityTools.SearchedContext;
log.println("ImplementationName " + utils.getImplName(oObj));
TestEnvironment tEnv = new TestEnvironment( oObj );
// relation for XAccessibleEventBroadcaster
XCell xCell = null;
final String text = "Text for testing of the interface XAccessibleText";
try {
XSpreadsheets oSheets = xSheetDoc.getSheets() ;
XIndexAccess oIndexSheets = (XIndexAccess)
UnoRuntime.queryInterface(XIndexAccess.class, oSheets);
XSpreadsheet oSheet = (XSpreadsheet) AnyConverter.toObject(
new Type(XSpreadsheet.class),oIndexSheets.getByIndex(0));
xCell = oSheet.getCellByPosition(5, 5) ;
xCell.setFormula(text);
} catch(com.sun.star.lang.WrappedTargetException e) {
log.println("Exception ceating relation :");
e.printStackTrace(log);
} catch(com.sun.star.lang.IndexOutOfBoundsException e) {
log.println("Exception ceating relation :");
e.printStackTrace(log);
} catch(com.sun.star.lang.IllegalArgumentException e) {
log.println("Exception ceating relation :");
e.printStackTrace(log);
}
final XCell fCell = xCell ;
tEnv.addObjRelation("EventProducer",
new ifc.accessibility._XAccessibleEventBroadcaster.EventProducer(){
public void fireEvent() {
fCell.setFormula("firing event");
fCell.setFormula(text);
}
});
return tEnv;
}
}
|
package railo.runtime.op;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import railo.commons.date.DateTimeUtil;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.i18n.LocaleFactory;
import railo.runtime.op.date.DateCaster;
import railo.runtime.type.Collection;
import railo.runtime.type.dt.DateTime;
import railo.runtime.type.dt.DateTimeImpl;
import railo.runtime.type.util.CollectionUtil;
/**
* class to compare objects and primitive value types
*
*
*/
public final class Operator {
/**
* compares two Objects
* @param left
* @param right
* @return different of objects as int
* @throws PageException
*/
public static int compare(Object left, Object right) throws PageException {
//print.dumpStack();
if(left instanceof String) return compare((String)left,right);
else if(left instanceof Number) return compare(((Number)left).doubleValue(),right);
else if(left instanceof Boolean) return compare(((Boolean)left).booleanValue(),right);
else if(left instanceof Date) return compare((Date)left ,right);
else if(left instanceof Castable) return compare(((Castable)left) ,right);
else if(left instanceof Locale) return compare(((Locale)left) ,right);
else if(left==null) return compare("",right);
/*/NICE disabled at the moment left Comparable
else if(left instanceof Comparable) {
return ((Comparable)left).compareTo(right);
} */
else if(left instanceof Character) return compare( ((Character)left).toString() , right );
else if(left instanceof Calendar) return compare( ((Calendar)left).getTime() , right );
else {
return error(false,true);
}
}
public static int compare(Locale left, Object right) throws PageException {
if(right instanceof String) return compare(left,(String)right);
else if(right instanceof Number) return compare(left,Caster.toString(right));
else if(right instanceof Boolean) return compare(left,Caster.toString(right));
else if(right instanceof Date) return compare(left,Caster.toString(right));
else if(right instanceof Castable) return compare(left,((Castable)right).castToString());
else if(right instanceof Locale) return left.toString().compareTo(right.toString());
else if(right==null) return compare( left, "" );
else if(right instanceof Character) return compare(left,((Character)right).toString());
else if(right instanceof Calendar) return compare(left, Caster.toString(((Calendar)right).getTime()) );
else return error(false,true);
}
public static int compare(Object left, Locale right) throws PageException {
return -compare(right,left);
}
public static int compare(Locale left, String right) {
Locale rightLocale = LocaleFactory.getLocale(right, null);
if(rightLocale==null) return LocaleFactory.toString(left).compareTo(right);
return left.toString().compareTo(rightLocale.toString());
}
public static int compare(String left, Locale right) {
return -compare(right,left);
}
/**
* compares a Object with a String
* @param left
* @param right
* @return difference as int
* @throws PageException
*/
public static int compare(Object left, String right) throws PageException {
if(left instanceof String) return compare((String)left, right );
else if(left instanceof Number) return compare( ((Number)left).doubleValue() , right );
else if(left instanceof Boolean) return compare( ((Boolean)left).booleanValue(), right );
else if(left instanceof Date) return compare( (Date)left , right );
else if(left instanceof Castable) return ((Castable)left).compareTo(right );
else if(left instanceof Locale) return compare( (Locale)left , right );
else if(left==null) return "".compareToIgnoreCase(right);
else if(left instanceof Character) return compare( ((Character)left).toString() , right );
else if(left instanceof Calendar) return compare( ((Calendar)left).getTime() , right );
else return error(false,true);
}
/**
* compares a String with a Object
* @param left
* @param right
* @return difference as int
* @throws PageException
*/
public static int compare(String left, Object right) throws PageException {
if(right instanceof String) return compare(left,(String)right);
else if(right instanceof Number) return compare(left,((Number)right).doubleValue());
else if(right instanceof Boolean) return compare(left,((Boolean)right).booleanValue()?1:0);
else if(right instanceof Date) return compare(left,(Date)right);
else if(right instanceof Castable) return -((Castable)right).compareTo(left);//compare(left ,((Castable)right).castToString());
else if(right instanceof Locale) return compare(left ,(Locale)right);
else if(right==null) return left.compareToIgnoreCase("");
else if(right instanceof Character) return compare(left ,((Character)right).toString());
else if(right instanceof Calendar) return compare(left, ((Calendar)right).getTime() );
else return error(false,true);
}
/**
* compares a Object with a double
* @param left
* @param right
* @return difference as int
* @throws PageException
*/
public static int compare(Object left, double right) throws PageException {
if(left instanceof Number) return compare( ((Number)left).doubleValue() ,right );
else if(left instanceof String) return compare( (String)left, right );
else if(left instanceof Boolean) return compare( ((Boolean)left).booleanValue()?1D:0D , right );
else if(left instanceof Date) return compare( ((Date)left) ,right);
else if(left instanceof Castable) return ((Castable)left).compareTo(right);
//else if(left instanceof Castable) return compare(((Castable)left).castToDoubleValue() , right );
else if(left instanceof Locale) return compare( ((Locale)left), Caster.toString(right));
else if(left==null) return -1;
else if(left instanceof Character) return compare(((Character)left).toString(),right);
else if(left instanceof Calendar) return compare( ((Calendar)left).getTime() , right );
else {
return error(false,true);
}
}
/**
* compares a double with a Object
* @param left
* @param right
* @return difference as int
* @throws PageException
*/
public static int compare(double left, Object right) throws PageException {
if(right instanceof Number) return compare(left,((Number)right).doubleValue());
else if(right instanceof String) return compare(left,(String)right);
else if(right instanceof Boolean) return compare(left,((Boolean)right).booleanValue()?1D:0D);
else if(right instanceof Date) return compare(left,((Date)right));
else if(right instanceof Castable) return -((Castable)right).compareTo(left);//compare(left ,((Castable)right).castToDoubleValue());
else if(right instanceof Locale) return compare(Caster.toString(left) ,((Locale)right));
else if(right==null) return 1;
else if(right instanceof Character) return compare(left ,((Character)right).toString());
else if(right instanceof Calendar) return compare(left, ((Calendar)right).getTime() );
else return error(true,false);
}
/**
* compares a Object with a boolean
* @param left
* @param right
* @return difference as int
* @throws PageException
*/
public static int compare(Object left, boolean right) throws PageException {
if(left instanceof Boolean) return compare(((Boolean)left).booleanValue(),right);
else if(left instanceof String) return compare((String)left,right);
else if(left instanceof Number) return compare(((Number)left).doubleValue(),right?1D:0D);
else if(left instanceof Date) return compare(((Date)left),right?1:0);
else if(left instanceof Castable) return ((Castable)left).compareTo(right );
else if(left instanceof Locale) return compare(((Locale)left),Caster.toString(right));
else if(left==null) return -1;
else if(left instanceof Character) return compare(((Character)left).toString(),right);
else if(left instanceof Calendar) return compare( ((Calendar)left).getTime() , right?1:0 );
else return error(false,true);
}
/**
* compares a boolean with a Object
* @param left
* @param right
* @return difference as int
* @throws PageException
*/
public static int compare(boolean left, Object right) throws PageException {
if(right instanceof Boolean) return compare(left,((Boolean)right).booleanValue());
else if(right instanceof String) return compare(left?1:0,(String)right);
else if(right instanceof Number) return compare(left?1D:0D,((Number)right).doubleValue());
else if(right instanceof Date) return compare(left?1:0,((Date)right));
else if(right instanceof Castable) return -((Castable)right).compareTo(left);//compare(left ,((Castable)right).castToBooleanValue());
else if(right instanceof Locale) return compare(Caster.toString(left),((Locale)right));
else if(right==null) return 1;
else if(right instanceof Character) return compare(left ,((Character)right).toString());
else if(right instanceof Calendar) return compare(left?1:0, ((Calendar)right).getTime() );
else return error(true,false);
}
/**
* compares a Object with a Date
* @param left
* @param right
* @return difference as int
* @throws PageException
*/
public static int compare(Object left, Date right) throws PageException {
if(left instanceof String) return compare((String)left,right);
else if(left instanceof Number) return compare(((Number)left).doubleValue() ,right.getTime()/1000 );
else if(left instanceof Boolean) return compare( ((Boolean)left).booleanValue()?1D:0D , right.getTime()/1000 );
else if(left instanceof Date) return compare( ((Date)left) , right );
else if(left instanceof Castable) return ((Castable)left).compareTo(Caster.toDatetime(right,null) );
else if(left instanceof Locale) return compare( ((Locale)left) , Caster.toString(right));
else if(left==null) return compare("", right);
else if(left instanceof Character) return compare(((Character)left).toString(),right);
else if(left instanceof Calendar) return compare( ((Calendar)left).getTime() , right );
else return error(false,true);
}
/**
* compares a Date with a Object
* @param left
* @param right
* @return difference as int
* @throws PageException
*/
public static int compare(Date left, Object right) throws PageException {
if(right instanceof String) return compare(left,(String)right);
else if(right instanceof Number) return compare(left.getTime()/1000,((Number)right).doubleValue());
else if(right instanceof Boolean) return compare(left.getTime()/1000,((Boolean)right).booleanValue()?1D:0D);
else if(right instanceof Date) return compare(left.getTime()/1000,((Date)right).getTime()/1000);
else if(right instanceof Castable) return -((Castable)right).compareTo(Caster.toDate(left,null));//compare(left ,(Date)((Castable)right).castToDateTime());
else if(right instanceof Locale) return compare(Caster.toString(left),(Locale)right);
else if(right==null) return compare(left,"");
else if(right instanceof Character) return compare(left ,((Character)right).toString());
else if(right instanceof Calendar) return compare(left.getTime()/1000, ((Calendar)right).getTime().getTime()/1000 );
else return error(true,false);
}
public static int compare(Castable left, Object right) throws PageException {
if(right instanceof String) return left.compareTo((String)right);
else if(right instanceof Number) return left.compareTo(((Number)right).doubleValue());
else if(right instanceof Boolean) return left.compareTo(((Boolean)right).booleanValue()?1d:0d);
else if(right instanceof Date) return left.compareTo(Caster.toDate(right,null));
else if(right instanceof Castable) return compare(left.castToString() , ((Castable)right).castToString() );
else if(right instanceof Locale) return compare(left.castToString() , (Locale)right);
else if(right == null) return compare(left.castToString(), "" );
else if(right instanceof Character) return left.compareTo(((Character)right).toString());
else if(right instanceof Calendar) return left.compareTo(new DateTimeImpl(((Calendar)right).getTime()) );
else return error(true,false);
}
public static int compare(Object left, Castable right) throws PageException {
return -compare(right,left);
}
/**
* compares a String with a String
* @param left
* @param right
* @return difference as int
*/
public static int compare(String left, String right) {
if(Decision.isNumeric(left)) {
if(Decision.isNumeric(right)){
// long numbers
if(left.length()>9 || right.length()>9) {
try{
return new BigDecimal(left).compareTo(new BigDecimal(right));
}
catch(Throwable t){}
}
return compare(Caster.toDoubleValue(left,Double.NaN),Caster.toDoubleValue(right,Double.NaN));
}
}
else if(Decision.isBoolean(left)) {
return compare(Caster.toBooleanValue(left,false)?1D:0D,right);
}
// NICE Date compare, perhaps datetime to double
return left.compareToIgnoreCase(right);
}
/**
* compares a String with a double
* @param left
* @param right
* @return difference as int
*/
public static int compare(String left, double right) {
if(Decision.isNumeric(left)) {
if(left.length()>9) {
return new BigDecimal(left).compareTo(new BigDecimal(right));
}
return compare(Caster.toDoubleValue(left,Double.NaN),right);
}
if(Decision.isBoolean(left))
return compare(Caster.toBooleanValue(left,false),right);
if(left.length()==0) return -1;
char leftFirst=left.charAt(0);
if(leftFirst>='0' && leftFirst<='9')
return left.compareToIgnoreCase(Caster.toString(right));
return leftFirst-'0';
}
/**
* compares a String with a boolean
* @param left
* @param right
* @return difference as int
*/
public static int compare(String left, boolean right) {
if(Decision.isBoolean(left))
return compare(Caster.toBooleanValue(left,false),right);
if(Decision.isNumeric(left))
return compare(Caster.toDoubleValue(left,Double.NaN),right?1d:0d);
if(left.length()==0) return -1;
char leftFirst=left.charAt(0);
//print.ln(left+".compareTo("+Caster.toString(right)+")");
//p(left);
if(leftFirst>='0' && leftFirst<='9')
return left.compareToIgnoreCase(Caster.toString(right?1D:0D));
return leftFirst-'0';
}
/**
* compares a String with a Date
* @param left
* @param right
* @return difference as int
* @throws PageException
*/
public static int compare(String left, Date right) throws PageException {
return -compare(right,left);
}
/**
* compares a double with a String
* @param left
* @param right
* @return difference as int
*/
public static int compare(double left, String right) {
return -compare(right,left);
}
/**
* compares a double with a double
* @param left
* @param right
* @return difference as int
*/
public static int compare(double left, double right) {
if((left)<(right))return -1;
else if((left)>(right))return 1;
else return 0;
}
/**
* compares a double with a boolean
* @param left
* @param right
* @return difference as int
*/
public static int compare(double left, boolean right) {
return compare(left,right?1d:0d);
}
/**
* compares a double with a Date
* @param left
* @param right
* @return difference as int
*/
public static int compare(double left, Date right) {
return compare(DateTimeUtil.getInstance().toDateTime(left).getTime()/1000,right.getTime()/1000);
}
/**
* compares a boolean with a double
* @param left
* @param right
* @return difference as int
*/
public static int compare(boolean left, double right) {
return compare(left?1d:0d, right);
}
/**
* compares a boolean with a double
* @param left
* @param right
* @return difference as int
*/
public static int compare(boolean left, String right) {
return -compare(right,left);
}
/**
* compares a boolean with a boolean
* @param left
* @param right
* @return difference as int
*/
public static int compare(boolean left, boolean right) {
if(left)return right?0:1;
return right?-1:0;
}
/**
* compares a boolean with a Date
* @param left
* @param right
* @return difference as int
*/
public static int compare(boolean left, Date right) {
return compare(left?1D:0D,right);
}
/**
* compares a Date with a String
* @param left
* @param right
* @return difference as int
* @throws PageException
*/
public static int compare(Date left, String right) throws PageException {
if(Decision.isNumeric(right)) return compare(left.getTime()/1000,Caster.toDoubleValue(right));
DateTime dt=DateCaster.toDateAdvanced(right,true,null,null);
if(dt!=null) {
return compare(left.getTime()/1000,dt.getTime()/1000);
}
return Caster.toString(left).compareToIgnoreCase(right);
}
/**
* compares a Date with a double
* @param left
* @param right
* @return difference as int
*/
public static int compare(Date left, double right) {
return compare(left.getTime()/1000, DateTimeUtil.getInstance().toDateTime(right).getTime()/1000);
}
/**
* compares a Date with a boolean
* @param left
* @param right
* @return difference as int
*/
public static int compare(Date left, boolean right) {
return compare(left,right?1D:0D);
}
/**
* compares a Date with a Date
* @param left
* @param right
* @return difference as int
*/
public static int compare(Date left, Date right) {
return compare(left.getTime()/1000,right.getTime()/1000);
}
private static int error(boolean leftIsOk, boolean rightIsOk, Object left, Object right) throws ExpressionException {
throw new ExpressionException("can't compare complex object types ("+Caster.toClassName(left)+" - "+Caster.toClassName(right)+") as simple value");
}
private static int error(boolean leftIsOk, boolean rightIsOk) throws ExpressionException {
// TODO remove this method
throw new ExpressionException("can't compare complex object types as simple value");
}
/**
* Method to compare to different values, return true of objects are same otherwise false
* @param left left value to compare
* @param right right value to compare
* @param caseSensitive check case sensitive or not
* @return is same or not
* @throws PageException
*/
public static boolean equals(Object left, Object right, boolean caseSensitive) throws PageException {
if(caseSensitive) {
try {
return Caster.toString(left).equals(Caster.toString(right));
} catch (ExpressionException e) {
return compare(left,right)==0;
}
}
return compare(left,right)==0;
}
public static boolean equals(Object left, Object right, boolean caseSensitive, boolean allowComplexValues) throws PageException {
if(!allowComplexValues || (Decision.isSimpleValue(left) && Decision.isSimpleValue(right)))
return equals(left, right, caseSensitive);
return left.equals(right);
}
public static boolean equalsEL(Object left, Object right, boolean caseSensitive, boolean allowComplexValues) {
if(!allowComplexValues || (Decision.isSimpleValue(left) && Decision.isSimpleValue(right))){
try {
return equals(left, right, caseSensitive);
} catch (PageException e) {
return false;
}
}
if(left instanceof Collection && right instanceof Collection)
return CollectionUtil.equals((Collection)left, (Collection)right);
return left.equals(right);
}
/**
* check if left is inside right (String-> ignore case)
* @param left string to check
* @param right substring to find in string
* @return return if substring has been found
* @throws PageException
*/
public static boolean ct(Object left, Object right) throws PageException {
return Caster.toString(left).toLowerCase().indexOf(Caster.toString(right).toLowerCase())!=-1;
}
/**
* Equivalence: Return True if both operands are True or both are False. The EQV operator is the opposite of the XOR operator. For example, True EQV True is True, but True EQV False is False.
* @param left value to check
* @param right value to check
* @return result of operation
* @throws PageException
*/
public static boolean eqv(Object left, Object right) throws PageException {
return eqv(Caster.toBooleanValue(left),Caster.toBooleanValue(right));
}
/**
* Equivalence: Return True if both operands are True or both are False. The EQV operator is the opposite of the XOR operator. For example, True EQV True is True, but True EQV False is False.
* @param left value to check
* @param right value to check
* @return result of operation
*/
public static boolean eqv(boolean left, boolean right) {
return (left==true && right==true) || (left==false && right==false);
}
/**
* Implication: The statement A IMP B is the equivalent of the logical statement
* "If A Then B." A IMP B is False only if A is True and B is False. It is True in all other cases.
* @param left value to check
* @param right value to check
* @return result
* @throws PageException
*/
public static boolean imp(Object left, Object right) throws PageException {
return imp(Caster.toBooleanValue(left),Caster.toBooleanValue(right));
}
/**
* Implication: The statement A IMP B is the equivalent of the logical statement
* "If A Then B." A IMP B is False only if A is True and B is False. It is True in all other cases.
* @param left value to check
* @param right value to check
* @return result
*/
public static boolean imp(boolean left, boolean right) {
return !(left==true && right==false);
}
/**
* check if left is not inside right (String-> ignore case)
* @param left string to check
* @param right substring to find in string
* @return return if substring NOT has been found
* @throws PageException
*/
public static boolean nct(Object left, Object right) throws PageException {
return !ct(left,right);
}
/**
* simple reference compersion
* @param left
* @param right
* @return
* @throws PageException
*/
public static boolean eeq(Object left, Object right) throws PageException {
return left==right;
}
/**
* simple reference compersion
* @param left
* @param right
* @return
* @throws PageException
*/
public static boolean neeq(Object left, Object right) throws PageException {
return left!=right;
}
/**
* calculate the exponent of the left value
* @param left value to get exponent from
* @param right exponent count
* @return return expoinended value
* @throws PageException
*/
public static double exponent(Object left, Object right) throws PageException {
return StrictMath.pow(Caster.toDoubleValue(left),Caster.toDoubleValue(right));
}
public static double exponent(double left, double right) {
return StrictMath.pow(left,right);
}
public static double intdiv(double left, double right) {
return ((int)left)/((int)right);
}
public static double div(double left, double right) {
if(right==0d)
throw new ArithmeticException("Division by zero is not possible");
return left/right;
}
public static float exponent(float left, float right) {
return (float) StrictMath.pow(left,right);
}
/**
* concat to Strings
* @param left
* @param right
* @return concated String
*/
public static String concat(String left,String right) {
int ll = left.length();
int rl = right.length();
int i;
char[] chars=new char[ll+rl];
for(i=0;i<ll;i++)chars[i]=left.charAt(i);
for(i=0;i<rl;i++)chars[ll+i]=right.charAt(i);
return new String(chars);
}
/**
* plus operation
* @param left
* @param right
* @return result of the opertions
*/
public final static double plus(double left, double right) {
return left+right;
}
/**
* minus operation
* @param left
* @param right
* @return result of the opertions
*/
public static double minus(double left, double right) {
return left-right;
}
/**
* modulus operation
* @param left
* @param right
* @return result of the opertions
*/
public static double modulus(double left, double right) {
return left%right;
}
/**
* divide operation
* @param left
* @param right
* @return result of the opertions
*/
public static double divide(double left, double right) {
return left/right;
}
/**
* multiply operation
* @param left
* @param right
* @return result of the opertions
*/
public static double multiply(double left, double right) {
return left*right;
}
/**
* bitand operation
* @param left
* @param right
* @return result of the opertions
*/
public static double bitand(double left, double right) {
return (int)left&(int)right;
}
/**
* bitand operation
* @param left
* @param right
* @return result of the opertions
*/
public static double bitor(double left, double right) {
return (int)left|(int)right;
}
public static Double divRef(Object left, Object right) throws PageException {
double r = Caster.toDoubleValue(right);
if(r==0d)
throw new ArithmeticException("Division by zero is not possible");
return Caster.toDouble(Caster.toDoubleValue(left)/r);
}
public static Double exponentRef(Object left, Object right) throws PageException {
return Caster.toDouble(StrictMath.pow(Caster.toDoubleValue(left),Caster.toDoubleValue(right)));
}
public static Double intdivRef(Object left, Object right) throws PageException {
return Caster.toDouble(Caster.toIntValue(left)/Caster.toIntValue(right));
}
public static Double plusRef(Object left, Object right) throws PageException {
return Caster.toDouble(Caster.toDoubleValue(left)+Caster.toDoubleValue(right));
}
public static Double minusRef(Object left, Object right) throws PageException {
return Caster.toDouble(Caster.toDoubleValue(left)-Caster.toDoubleValue(right));
}
public static Double modulusRef(Object left, Object right) throws PageException {
return Caster.toDouble(Caster.toDoubleValue(left)%Caster.toDoubleValue(right));
}
public static Double divideRef(Object left, Object right) throws PageException {
return Caster.toDouble(Caster.toDoubleValue(left)/Caster.toDoubleValue(right));
}
public static Double multiplyRef(Object left, Object right) throws PageException {
return Caster.toDouble(Caster.toDoubleValue(left)*Caster.toDoubleValue(right));
}
}
|
package railo.runtime.orm;
import java.util.HashSet;
import railo.commons.lang.SystemOut;
import railo.runtime.Component;
import railo.runtime.ComponentPro;
import railo.runtime.PageContext;
import railo.runtime.PageContextImpl;
import railo.runtime.component.Property;
import railo.runtime.config.ConfigImpl;
import railo.runtime.exp.PageException;
import railo.runtime.op.Caster;
import railo.runtime.op.Decision;
import railo.runtime.op.Operator;
import railo.runtime.orm.hibernate.HBMCreator;
import railo.runtime.type.Collection;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.Struct;
import railo.runtime.type.util.ComponentUtil;
public class ORMUtil {
public static ORMSession getSession(PageContext pc) throws PageException {
return getSession(pc,true);
}
public static ORMSession getSession(PageContext pc, boolean create) throws PageException {
return ((PageContextImpl) pc).getORMSession(create);
}
public static ORMEngine getEngine(PageContext pc) throws PageException {
ConfigImpl config=(ConfigImpl) pc.getConfig();
return config.getORMEngine(pc);
}
/**
*
* @param pc
* @param force if set to false the engine is on loaded when the configuration has changed
* @throws PageException
*/
public static void resetEngine(PageContext pc, boolean force) throws PageException {
ConfigImpl config=(ConfigImpl) pc.getConfig();
config.resetORMEngine(pc,force);
}
public static void printError(Throwable t, ORMEngine engine) {
printError(t, engine, t.getMessage());
}
public static void printError(String msg, ORMEngine engine) {
printError(null, engine, msg);
}
private static void printError(Throwable t, ORMEngine engine,String msg) {
SystemOut.printDate("{"+engine.getLabel().toUpperCase()+"} - "+msg,SystemOut.ERR);
if(t==null)t=new Throwable();
t.printStackTrace(SystemOut.getPrinWriter(SystemOut.ERR));
}
public static boolean equals(Object left, Object right) {
HashSet<Object> done=new HashSet<Object>();
return _equals(done, left, right);
}
private static boolean _equals(HashSet<Object> done,Object left, Object right) {
if(left==right) return true;
if(left==null || right==null) return false;
// components
if(left instanceof Component && right instanceof Component){
return _equals(done,(Component)left, (Component)right);
}
// arrays
if(Decision.isArray(left) && Decision.isArray(right)){
return _equals(done,Caster.toArray(left,null), Caster.toArray(right,null));
}
// struct
if(Decision.isStruct(left) && Decision.isStruct(right)){
return _equals(done,Caster.toStruct(left,null), Caster.toStruct(right,null));
}
try {
return Operator.equals(left,right,false);
} catch (PageException e) {
return false;
}
}
private static boolean _equals(HashSet<Object> done,Collection left, Collection right) {
if(done.contains(left)) return done.contains(right);
done.add(left);
done.add(right);
if(left.size()!=right.size()) return false;
Key[] keys = left.keys();
Object l,r;
for(int i=0;i<keys.length;i++){
l=left.get(keys[i],null);
r=right.get(keys[i],null);
if(r==null || !_equals(done,l, r)) return false;
}
return true;
}
private static boolean _equals(HashSet<Object> done,Component left, Component right) {
if(done.contains(left)) return done.contains(right);
done.add(left);
done.add(right);
ComponentPro cpl =ComponentUtil.toComponentPro(left,null);
ComponentPro cpr = ComponentUtil.toComponentPro(right,null);
if(cpl==null || cpr==null) return false;
if(!cpl.getPageSource().equals(cpr.getPageSource())) return false;
Property[] props = cpl.getProperties(true);
Object l,r;
props=HBMCreator.getIds(null,null,props,null,true);
for(int i=0;i<props.length;i++){
l=cpl.getComponentScope().get(KeyImpl.getInstance(props[i].getName()),null);
r=cpr.getComponentScope().get(KeyImpl.getInstance(props[i].getName()),null);
if(!_equals(done,l, r)) return false;
}
return true;
}
public static Object getPropertyValue(Component cfc, String name, Object defaultValue) {
ComponentPro cp =ComponentUtil.toComponentPro(cfc,null);
Property[] props = cp.getProperties(true);
for(int i=0;i<props.length;i++){
if(!props[i].getName().equalsIgnoreCase(name)) continue;
return cp.getComponentScope().get(KeyImpl.getInstance(name),null);
}
return defaultValue;
}
}
|
package org.reactfx;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import javafx.application.Platform;
import org.reactfx.util.Either;
public interface EitherEventStream<L, R> extends EventStream<Either<L, R>> {
default Subscription subscribe(
Consumer<? super L> leftSubscriber,
Consumer<? super R> rightSubscriber) {
return subscribe(either -> {
either.ifLeft(leftSubscriber);
either.ifRight(rightSubscriber);
});
}
default EventStream<L> left() {
return filterMap(Either::isLeft, Either::getLeft);
}
default EventStream<R> right() {
return filterMap(Either::isRight, Either::getRight);
}
@Override
default EitherEventStream<L, R> hook(
Consumer<? super Either<L, R>> sideEffect) {
return new SideEffectEitherStream<>(this, sideEffect);
}
default EitherEventStream<L, R> hook(
Consumer<? super L> leftSideEffect,
Consumer<? super R> rightSideEffect) {
return hook(either -> {
either.ifLeft(leftSideEffect);
either.ifRight(rightSideEffect);
});
}
@Override
default EitherEventStream<L, R> filter(
Predicate<? super Either<L, R>> predicate) {
return new FilterEitherStream<>(this, predicate);
}
@Override
default EitherEventStream<L, R> distinct() {
return new DistinctEitherStream<>(this);
}
default <L1, R1> EitherEventStream<L1, R1> map(
Function<? super L, ? extends L1> leftMap,
Function<? super R, ? extends R1> rightMap) {
return split(either -> either.map(leftMap, rightMap));
}
default <L1> EitherEventStream<L1, R> mapLeft(
Function<? super L, ? extends L1> f) {
return split(either -> either.mapLeft(f));
}
default <R1> EitherEventStream<L, R1> mapRight(
Function<? super R, ? extends R1> f) {
return split(either -> either.mapRight(f));
}
default <L1, R1> EitherEventStream<L1, R1> split(
Function<? super L, Either<L1, R1>> leftMap,
Function<? super R, Either<L1, R1>> rightMap) {
return split(either -> either.isLeft()
? leftMap.apply(either.getLeft())
: rightMap.apply(either.getRight()));
}
default <L1> EitherEventStream<L1, R> splitLeft(
Function<? super L, Either<L1, R>> leftMap) {
return split(leftMap, Either::right);
}
default <R1> EitherEventStream<L, R1> splitRight(
Function<? super R, Either<L, R1>> rightMap) {
return split(Either::left, rightMap);
}
default <T> EventStream<T> unify(
Function<? super L, ? extends T> leftMap,
Function<? super R, ? extends T> rightMap) {
return map(either -> either.unify(leftMap, rightMap));
}
@Override
default EitherEventStream<L, R> emitOn(EventStream<?> impulse) {
return new EmitOnEitherStream<>(this, impulse);
}
@Override
default EitherEventStream<L, R> emitOnEach(EventStream<?> impulse) {
return new EmitOnEachEitherStream<>(this, impulse);
}
@Override
default EitherEventStream<L, R> repeatOn(EventStream<?> impulse) {
return new RepeatOnEitherStream<>(this, impulse);
}
@Override
default InterceptableEitherEventStream<L, R> interceptable() {
if(this instanceof InterceptableEitherEventStream) {
return (InterceptableEitherEventStream<L, R>) this;
} else {
return new InterceptableEitherEventStreamImpl<L, R>(this);
}
}
@Override
default EitherEventStream<L, R> threadBridge(
Executor sourceThreadExecutor,
Executor targetThreadExecutor) {
return new EitherThreadBridge<L, R>(this, sourceThreadExecutor, targetThreadExecutor);
}
@Override
default EitherEventStream<L, R> threadBridgeFromFx(Executor targetThreadExecutor) {
return threadBridge(Platform::runLater, targetThreadExecutor);
}
@Override
default EitherEventStream<L, R> threadBridgeToFx(Executor sourceThreadExecutor) {
return threadBridge(sourceThreadExecutor, Platform::runLater);
}
@Override
default EitherEventStream<L, R> guardedBy(Guardian... guardians) {
return new GuardedEitherStream<>(this, guardians);
}
}
|
package com.alamkanak.weekview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.Typeface;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.style.StyleSpan;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.OverScroller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
public class WeekView extends View {
private enum Direction {
NONE, LEFT, RIGHT, VERTICAL
}
@Deprecated
public static final int LENGTH_SHORT = 1;
@Deprecated
public static final int LENGTH_LONG = 2;
private final Context mContext;
private Paint mTimeTextPaint;
private float mTimeTextWidth;
private float mTimeTextHeight;
private Paint mHeaderTextPaint;
private float mHeaderTextHeight;
private float mHeaderHeight;
private GestureDetectorCompat mGestureDetector;
private OverScroller mScroller;
private PointF mCurrentOrigin = new PointF(0f, 0f);
private Direction mCurrentScrollDirection = Direction.NONE;
private Paint mHeaderBackgroundPaint;
private float mWidthPerDay;
private Paint mDayBackgroundPaint;
private Paint mHourSeparatorPaint;
private float mHeaderMarginBottom;
private Paint mTodayBackgroundPaint;
private Paint mFutureBackgroundPaint;
private Paint mPastBackgroundPaint;
private Paint mFutureWeekendBackgroundPaint;
private Paint mPastWeekendBackgroundPaint;
private Paint mNowLinePaint;
private Paint mTodayHeaderTextPaint;
private Paint mEventBackgroundPaint;
private float mHeaderColumnWidth;
private List<EventRect> mEventRects;
private List<? extends WeekViewEvent> mPreviousPeriodEvents;
private List<? extends WeekViewEvent> mCurrentPeriodEvents;
private List<? extends WeekViewEvent> mNextPeriodEvents;
private TextPaint mEventTextPaint;
private Paint mHeaderColumnBackgroundPaint;
private int mFetchedPeriod = -1; // the middle period the calendar has fetched.
private boolean mRefreshEvents = false;
private Direction mCurrentFlingDirection = Direction.NONE;
private ScaleGestureDetector mScaleDetector;
private boolean mIsZooming;
private Calendar mFirstVisibleDay;
private Calendar mLastVisibleDay;
private int mDefaultEventColor;
private int mMinimumFlingVelocity = 0;
private int mScaledTouchSlop = 0;
// Attributes and their default values.
private int mHourHeight = 50;
private int mNewHourHeight = -1;
private int mMinHourHeight = 0; //no minimum specified (will be dynamic, based on screen)
private int mEffectiveMinHourHeight = mMinHourHeight; //compensates for the fact that you can't keep zooming out.
private int mMaxHourHeight = 250;
private int mColumnGap = 10;
private int mFirstDayOfWeek = Calendar.MONDAY;
private int mTextSize = 12;
private int mHeaderColumnPadding = 10;
private int mHeaderColumnTextColor = Color.BLACK;
private int mNumberOfVisibleDays = 3;
private int mHeaderRowPadding = 10;
private int mHeaderRowBackgroundColor = Color.WHITE;
private int mDayBackgroundColor = Color.rgb(245, 245, 245);
private int mPastBackgroundColor = Color.rgb(227, 227, 227);
private int mFutureBackgroundColor = Color.rgb(245, 245, 245);
private int mPastWeekendBackgroundColor = 0;
private int mFutureWeekendBackgroundColor = 0;
private int mNowLineColor = Color.rgb(102, 102, 102);
private int mNowLineThickness = 5;
private int mHourSeparatorColor = Color.rgb(230, 230, 230);
private int mTodayBackgroundColor = Color.rgb(239, 247, 254);
private int mHourSeparatorHeight = 2;
private int mTodayHeaderTextColor = Color.rgb(39, 137, 228);
private int mEventTextSize = 12;
private int mEventTextColor = Color.BLACK;
private int mEventPadding = 8;
private int mHeaderColumnBackgroundColor = Color.WHITE;
private boolean mIsFirstDraw = true;
private boolean mAreDimensionsInvalid = true;
@Deprecated private int mDayNameLength = LENGTH_LONG;
private int mOverlappingEventGap = 0;
private int mEventMarginVertical = 0;
private float mXScrollingSpeed = 1f;
private Calendar mScrollToDay = null;
private double mScrollToHour = -1;
private int mEventCornerRadius = 0;
private boolean mShowDistinctWeekendColor = false;
private boolean mShowNowLine = false;
private boolean mShowDistinctPastFutureColor = false;
private boolean mHorizontalFlingEnabled = true;
private boolean mVerticalFlingEnabled = true;
private int mAllDayEventHeight= 100;
// Listeners.
private EventClickListener mEventClickListener;
private EventLongPressListener mEventLongPressListener;
private WeekViewLoader mWeekViewLoader;
private EmptyViewClickListener mEmptyViewClickListener;
private EmptyViewLongPressListener mEmptyViewLongPressListener;
private DateTimeInterpreter mDateTimeInterpreter;
private ScrollListener mScrollListener;
private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
goToNearestOrigin();
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// Check if view is zoomed.
if (mIsZooming)
return true;
switch (mCurrentScrollDirection) {
case NONE: {
// Allow scrolling only in one direction.
if (Math.abs(distanceX) > Math.abs(distanceY)) {
if (distanceX > 0) {
mCurrentScrollDirection = Direction.LEFT;
} else {
mCurrentScrollDirection = Direction.RIGHT;
}
} else {
mCurrentScrollDirection = Direction.VERTICAL;
}
break;
}
case LEFT: {
// Change direction if there was enough change.
if (Math.abs(distanceX) > Math.abs(distanceY) && (distanceX < -mScaledTouchSlop)) {
mCurrentScrollDirection = Direction.RIGHT;
}
break;
}
case RIGHT: {
// Change direction if there was enough change.
if (Math.abs(distanceX) > Math.abs(distanceY) && (distanceX > mScaledTouchSlop)) {
mCurrentScrollDirection = Direction.LEFT;
}
break;
}
}
// Calculate the new origin after scroll.
switch (mCurrentScrollDirection) {
case LEFT:
case RIGHT:
mCurrentOrigin.x -= distanceX * mXScrollingSpeed;
ViewCompat.postInvalidateOnAnimation(WeekView.this);
break;
case VERTICAL:
mCurrentOrigin.y -= distanceY;
ViewCompat.postInvalidateOnAnimation(WeekView.this);
break;
}
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (mIsZooming)
return true;
if ((mCurrentFlingDirection == Direction.LEFT && !mHorizontalFlingEnabled) ||
(mCurrentFlingDirection == Direction.RIGHT && !mHorizontalFlingEnabled) ||
(mCurrentFlingDirection == Direction.VERTICAL && !mVerticalFlingEnabled)) {
return true;
}
mScroller.forceFinished(true);
mCurrentFlingDirection = mCurrentScrollDirection;
switch (mCurrentFlingDirection) {
case LEFT:
case RIGHT:
mScroller.fling((int) mCurrentOrigin.x, (int) mCurrentOrigin.y, (int) (velocityX * mXScrollingSpeed), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, (int) -(mHourHeight * 24 + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight / 2 - getHeight()), 0);
break;
case VERTICAL:
mScroller.fling((int) mCurrentOrigin.x, (int) mCurrentOrigin.y, 0, (int) velocityY, Integer.MIN_VALUE, Integer.MAX_VALUE, (int) -(mHourHeight * 24 + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - getHeight()), 0);
break;
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// If the tap was on an event then trigger the callback.
if (mEventRects != null && mEventClickListener != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventClickListener.onEventClick(event.originalEvent, event.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
return super.onSingleTapConfirmed(e);
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewClickListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mEmptyViewClickListener.onEmptyViewClicked(selectedTime);
}
}
return super.onSingleTapConfirmed(e);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
if (mEventLongPressListener != null && mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventLongPressListener.onEventLongPress(event.originalEvent, event.rectF);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return;
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewLongPressListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
mEmptyViewLongPressListener.onEmptyViewLongPress(selectedTime);
}
}
}
};
public WeekView(Context context) {
this(context, null);
}
public WeekView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WeekView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Hold references.
mContext = context;
// Get the attribute values (if any).
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WeekView, 0, 0);
try {
mFirstDayOfWeek = a.getInteger(R.styleable.WeekView_firstDayOfWeek, mFirstDayOfWeek);
mHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourHeight, mHourHeight);
mMinHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_minHourHeight, mMinHourHeight);
mEffectiveMinHourHeight = mMinHourHeight;
mMaxHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_maxHourHeight, mMaxHourHeight);
mTextSize = a.getDimensionPixelSize(R.styleable.WeekView_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, context.getResources().getDisplayMetrics()));
mHeaderColumnPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerColumnPadding, mHeaderColumnPadding);
mColumnGap = a.getDimensionPixelSize(R.styleable.WeekView_columnGap, mColumnGap);
mHeaderColumnTextColor = a.getColor(R.styleable.WeekView_headerColumnTextColor, mHeaderColumnTextColor);
mNumberOfVisibleDays = a.getInteger(R.styleable.WeekView_noOfVisibleDays, mNumberOfVisibleDays);
mHeaderRowPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerRowPadding, mHeaderRowPadding);
mHeaderRowBackgroundColor = a.getColor(R.styleable.WeekView_headerRowBackgroundColor, mHeaderRowBackgroundColor);
mDayBackgroundColor = a.getColor(R.styleable.WeekView_dayBackgroundColor, mDayBackgroundColor);
mFutureBackgroundColor = a.getColor(R.styleable.WeekView_futureBackgroundColor, mFutureBackgroundColor);
mPastBackgroundColor = a.getColor(R.styleable.WeekView_pastBackgroundColor, mPastBackgroundColor);
mFutureWeekendBackgroundColor = a.getColor(R.styleable.WeekView_futureWeekendBackgroundColor, mFutureBackgroundColor); // If not set, use the same color as in the week
mPastWeekendBackgroundColor = a.getColor(R.styleable.WeekView_pastWeekendBackgroundColor, mPastBackgroundColor);
mNowLineColor = a.getColor(R.styleable.WeekView_nowLineColor, mNowLineColor);
mNowLineThickness = a.getDimensionPixelSize(R.styleable.WeekView_nowLineThickness, mNowLineThickness);
mHourSeparatorColor = a.getColor(R.styleable.WeekView_hourSeparatorColor, mHourSeparatorColor);
mTodayBackgroundColor = a.getColor(R.styleable.WeekView_todayBackgroundColor, mTodayBackgroundColor);
mHourSeparatorHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mHourSeparatorHeight);
mTodayHeaderTextColor = a.getColor(R.styleable.WeekView_todayHeaderTextColor, mTodayHeaderTextColor);
mEventTextSize = a.getDimensionPixelSize(R.styleable.WeekView_eventTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mEventTextSize, context.getResources().getDisplayMetrics()));
mEventTextColor = a.getColor(R.styleable.WeekView_eventTextColor, mEventTextColor);
mEventPadding = a.getDimensionPixelSize(R.styleable.WeekView_eventPadding, mEventPadding);
mHeaderColumnBackgroundColor = a.getColor(R.styleable.WeekView_headerColumnBackground, mHeaderColumnBackgroundColor);
mDayNameLength = a.getInteger(R.styleable.WeekView_dayNameLength, mDayNameLength);
mOverlappingEventGap = a.getDimensionPixelSize(R.styleable.WeekView_overlappingEventGap, mOverlappingEventGap);
mEventMarginVertical = a.getDimensionPixelSize(R.styleable.WeekView_eventMarginVertical, mEventMarginVertical);
mXScrollingSpeed = a.getFloat(R.styleable.WeekView_xScrollingSpeed, mXScrollingSpeed);
mEventCornerRadius = a.getDimensionPixelSize(R.styleable.WeekView_eventCornerRadius, mEventCornerRadius);
mShowDistinctPastFutureColor = a.getBoolean(R.styleable.WeekView_showDistinctPastFutureColor, mShowDistinctPastFutureColor);
mShowDistinctWeekendColor = a.getBoolean(R.styleable.WeekView_showDistinctWeekendColor, mShowDistinctWeekendColor);
mShowNowLine = a.getBoolean(R.styleable.WeekView_showNowLine, mShowNowLine);
mHorizontalFlingEnabled = a.getBoolean(R.styleable.WeekView_horizontalFlingEnabled, mHorizontalFlingEnabled);
mVerticalFlingEnabled = a.getBoolean(R.styleable.WeekView_verticalFlingEnabled, mVerticalFlingEnabled);
mAllDayEventHeight = a.getInt(R.styleable.WeekView_allDayEventHeight, mAllDayEventHeight);
} finally {
a.recycle();
}
init();
}
private void init() {
// Scrolling initialization.
mGestureDetector = new GestureDetectorCompat(mContext, mGestureListener);
mScroller = new OverScroller(mContext, new FastOutLinearInInterpolator());
mMinimumFlingVelocity = ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity();
mScaledTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
// Measure settings for time column.
mTimeTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTimeTextPaint.setTextAlign(Paint.Align.RIGHT);
mTimeTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
Rect rect = new Rect();
mTimeTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mTimeTextHeight = rect.height();
mHeaderMarginBottom = mTimeTextHeight / 2;
initTextTimeWidth();
// Measure settings for header row.
mHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mHeaderTextHeight = rect.height();
mHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
// Prepare header background paint.
mHeaderBackgroundPaint = new Paint();
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
// Prepare day background color paint.
mDayBackgroundPaint = new Paint();
mDayBackgroundPaint.setColor(mDayBackgroundColor);
mFutureBackgroundPaint = new Paint();
mFutureBackgroundPaint.setColor(mFutureBackgroundColor);
mPastBackgroundPaint = new Paint();
mPastBackgroundPaint.setColor(mPastBackgroundColor);
mFutureWeekendBackgroundPaint = new Paint();
mFutureWeekendBackgroundPaint.setColor(mFutureWeekendBackgroundColor);
mPastWeekendBackgroundPaint = new Paint();
mPastWeekendBackgroundPaint.setColor(mPastWeekendBackgroundColor);
// Prepare hour separator color paint.
mHourSeparatorPaint = new Paint();
mHourSeparatorPaint.setStyle(Paint.Style.STROKE);
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
mHourSeparatorPaint.setColor(mHourSeparatorColor);
// Prepare the "now" line color paint
mNowLinePaint = new Paint();
mNowLinePaint.setStrokeWidth(mNowLineThickness);
mNowLinePaint.setColor(mNowLineColor);
// Prepare today background color paint.
mTodayBackgroundPaint = new Paint();
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
// Prepare today header text color paint.
mTodayHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTodayHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mTodayHeaderTextPaint.setTextSize(mTextSize);
mTodayHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
// Prepare event background color.
mEventBackgroundPaint = new Paint();
mEventBackgroundPaint.setColor(Color.rgb(174, 208, 238));
// Prepare header column background color.
mHeaderColumnBackgroundPaint = new Paint();
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
// Prepare event text size and color.
mEventTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
mEventTextPaint.setStyle(Paint.Style.FILL);
mEventTextPaint.setColor(mEventTextColor);
mEventTextPaint.setTextSize(mEventTextSize);
// Set default event color.
mDefaultEventColor = Color.parseColor("#9fc6e7");
mScaleDetector = new ScaleGestureDetector(mContext, new ScaleGestureDetector.OnScaleGestureListener() {
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
mIsZooming = false;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mIsZooming = true;
goToNearestOrigin();
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
mNewHourHeight = Math.round(mHourHeight * detector.getScaleFactor());
invalidate();
return true;
}
});
}
// fix rotation changes
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mAreDimensionsInvalid = true;
}
/**
* Initialize time column width. Calculate value with all possible hours (supposed widest text).
*/
private void initTextTimeWidth() {
mTimeTextWidth = 0;
for (int i = 0; i < 24; i++) {
// Measure time string and get max width.
String time = getDateTimeInterpreter().interpretTime(i);
if (time == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null time");
mTimeTextWidth = Math.max(mTimeTextWidth, mTimeTextPaint.measureText(time));
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Hide everything in the first cell (top left corner).
canvas.drawRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row.
drawHeaderRowAndEvents(canvas);
// Draw the time column and all the axes/separators.
drawTimeColumnAndAxes(canvas);
}
private void drawTimeColumnAndAxes(Canvas canvas) {
// Draw the background color for the header column.
canvas.drawRect(0, mHeaderHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), mHeaderColumnBackgroundPaint);
// Clip to paint in left column only.
canvas.clipRect(0, mHeaderHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), Region.Op.REPLACE);
for (int i = 0; i < 24; i++) {
float top = mHeaderHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * i + mHeaderMarginBottom;
// Draw the text if its y position is not outside of the visible area. The pivot point of the text is the point at the bottom-right corner.
String time = getDateTimeInterpreter().interpretTime(i);
if (time == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null time");
if (top < getHeight()) canvas.drawText(time, mTimeTextWidth + mHeaderColumnPadding, top + mTimeTextHeight, mTimeTextPaint);
}
}
private void drawHeaderRowAndEvents(Canvas canvas) {
// Calculate the available width for each day.
mHeaderColumnWidth = mTimeTextWidth + mHeaderColumnPadding *2;
mWidthPerDay = getWidth() - mHeaderColumnWidth - mColumnGap * (mNumberOfVisibleDays - 1);
mWidthPerDay = mWidthPerDay/mNumberOfVisibleDays;
boolean containsAllDayEvent = false;
if (mEventRects != null && mEventRects.size() > 0) {
for (int dayNumber = 0;
dayNumber < mNumberOfVisibleDays;
dayNumber++) {
Calendar day = (Calendar) getFirstVisibleDay().clone();
day.add(Calendar.DATE, dayNumber);
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), day) && mEventRects.get(i).event.isAllDay()) {
containsAllDayEvent = true;
break;
}
}
if(containsAllDayEvent){
break;
}
}
}
float newHeaderHeight;
if(containsAllDayEvent) {
newHeaderHeight = mHeaderTextHeight + (mAllDayEventHeight + mHeaderMarginBottom);
}
else{
newHeaderHeight = mHeaderTextHeight;
}
if(newHeaderHeight!=mHeaderHeight){
mHeaderHeight = newHeaderHeight;
postInvalidate();
}
Calendar today = today();
if (mAreDimensionsInvalid) {
mEffectiveMinHourHeight= Math.max(mMinHourHeight, (int) ((getHeight() - mHeaderHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom) / 24));
mAreDimensionsInvalid = false;
if(mScrollToDay != null)
goToDate(mScrollToDay);
mAreDimensionsInvalid = false;
if(mScrollToHour >= 0)
goToHour(mScrollToHour);
mScrollToDay = null;
mScrollToHour = -1;
mAreDimensionsInvalid = false;
}
if (mIsFirstDraw){
mIsFirstDraw = false;
// If the week view is being drawn for the first time, then consider the first day of the week.
if(mNumberOfVisibleDays >= 7 && today.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek) {
int difference = 7 + (today.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek);
mCurrentOrigin.x += (mWidthPerDay + mColumnGap) * difference;
}
}
// Calculate the new height due to the zooming.
if (mNewHourHeight > 0){
if (mNewHourHeight < mEffectiveMinHourHeight)
mNewHourHeight = mEffectiveMinHourHeight;
else if (mNewHourHeight > mMaxHourHeight)
mNewHourHeight = mMaxHourHeight;
mCurrentOrigin.y = (mCurrentOrigin.y/mHourHeight)*mNewHourHeight;
mHourHeight = mNewHourHeight;
mNewHourHeight = -1;
}
// If the new mCurrentOrigin.y is invalid, make it valid.
if (mCurrentOrigin.y < getHeight() - mHourHeight * 24 - mHeaderHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom - mTimeTextHeight/2)
mCurrentOrigin.y = getHeight() - mHourHeight * 24 - mHeaderHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom - mTimeTextHeight/2;
// Don't put an "else if" because it will trigger a glitch when completely zoomed out and
// scrolling vertically.
if (mCurrentOrigin.y > 0) {
mCurrentOrigin.y = 0;
}
// Consider scroll offset.
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startFromPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
float startPixel = startFromPixel;
// Prepare to iterate for each day.
Calendar day = (Calendar) today.clone();
day.add(Calendar.HOUR, 6);
// Prepare to iterate for each hour to draw the hour lines.
int lineCount = (int) ((getHeight() - mHeaderHeight - mHeaderRowPadding * 2 -
mHeaderMarginBottom) / mHourHeight) + 1;
lineCount = (lineCount) * (mNumberOfVisibleDays+1);
float[] hourLines = new float[lineCount * 4];
// Clear the cache for event rectangles.
if (mEventRects != null) {
for (EventRect eventRect: mEventRects) {
eventRect.rectF = null;
}
}
// Clip to paint events only.
canvas.clipRect(mHeaderColumnWidth, mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2, getWidth(), getHeight(), Region.Op.REPLACE);
// Iterate through each day.
Calendar oldFirstVisibleDay = mFirstVisibleDay;
mFirstVisibleDay = (Calendar) today.clone();
mFirstVisibleDay.add(Calendar.DATE, -(Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap))));
if(!mFirstVisibleDay.equals(oldFirstVisibleDay) && mScrollListener != null){
mScrollListener.onFirstVisibleDayChanged(mFirstVisibleDay, oldFirstVisibleDay);
}
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
// Check if the day is today.
day = (Calendar) today.clone();
mLastVisibleDay = (Calendar) day.clone();
day.add(Calendar.DATE, dayNumber - 1);
mLastVisibleDay.add(Calendar.DATE, dayNumber - 2);
boolean sameDay = isSameDay(day, today);
// Get more events if necessary. We want to store the events 3 months beforehand. Get
// events only when it is the first iteration of the loop.
if (mEventRects == null || mRefreshEvents ||
(dayNumber == leftDaysWithGaps + 1 && mFetchedPeriod != (int) mWeekViewLoader.toWeekViewPeriodIndex(day) &&
Math.abs(mFetchedPeriod - mWeekViewLoader.toWeekViewPeriodIndex(day)) > 0.5)) {
getMoreEvents(day);
mRefreshEvents = false;
}
// Draw background color for each day.
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start > 0){
if (mShowDistinctPastFutureColor){
boolean isWeekend = day.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || day.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
Paint pastPaint = isWeekend && mShowDistinctWeekendColor ? mPastWeekendBackgroundPaint : mPastBackgroundPaint;
Paint futurePaint = isWeekend && mShowDistinctWeekendColor ? mFutureWeekendBackgroundPaint : mFutureBackgroundPaint;
float startY = mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom + mCurrentOrigin.y;
if (sameDay){
Calendar now = Calendar.getInstance();
float beforeNow = (now.get(Calendar.HOUR_OF_DAY) + now.get(Calendar.MINUTE)/60.0f) * mHourHeight;
canvas.drawRect(start, startY, startPixel + mWidthPerDay, startY+beforeNow, pastPaint);
canvas.drawRect(start, startY+beforeNow, startPixel + mWidthPerDay, getHeight(), futurePaint);
}
else if (day.before(today)) {
canvas.drawRect(start, startY, startPixel + mWidthPerDay, getHeight(), pastPaint);
}
else {
canvas.drawRect(start, startY, startPixel + mWidthPerDay, getHeight(), futurePaint);
}
}
else {
canvas.drawRect(start, mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom, startPixel + mWidthPerDay, getHeight(), sameDay ? mTodayBackgroundPaint : mDayBackgroundPaint);
}
}
// Prepare the separator lines for hours.
int i = 0;
for (int hourNumber = 0; hourNumber < 24; hourNumber++) {
float top = mHeaderHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * hourNumber + mTimeTextHeight/2 + mHeaderMarginBottom;
if (top > mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom - mHourSeparatorHeight && top < getHeight() && startPixel + mWidthPerDay - start > 0){
hourLines[i * 4] = start;
hourLines[i * 4 + 1] = top;
hourLines[i * 4 + 2] = startPixel + mWidthPerDay;
hourLines[i * 4 + 3] = top;
i++;
}
}
// Draw the lines for hours.
canvas.drawLines(hourLines, mHourSeparatorPaint);
// Draw the events.
drawEvents(day, startPixel, canvas);
// Draw the line at the current time.
if (mShowNowLine && sameDay){
float startY = mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom + mCurrentOrigin.y;
Calendar now = Calendar.getInstance();
float beforeNow = (now.get(Calendar.HOUR_OF_DAY) + now.get(Calendar.MINUTE)/60.0f) * mHourHeight;
canvas.drawLine(start, startY + beforeNow, startPixel + mWidthPerDay, startY + beforeNow, mNowLinePaint);
}
// In the next iteration, start from the next day.
startPixel += mWidthPerDay + mColumnGap;
}
// Clip to paint header row only.
canvas.clipRect(mHeaderColumnWidth, 0, getWidth(), mHeaderHeight + mHeaderRowPadding * 2, Region.Op.REPLACE);
// Draw the header background.
canvas.drawRect(0, 0, getWidth(), mHeaderHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row texts.
startPixel = startFromPixel;
for (int dayNumber=leftDaysWithGaps+1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) {
// Check if the day is today.
day = (Calendar) today.clone();
day.add(Calendar.DATE, dayNumber - 1);
boolean sameDay = isSameDay(day, today);
// Draw the day labels.
String dayLabel = getDateTimeInterpreter().interpretDate(day);
if (dayLabel == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null date");
canvas.drawText(dayLabel, startPixel + mWidthPerDay / 2, mHeaderTextHeight + mHeaderRowPadding, sameDay ? mTodayHeaderTextPaint : mHeaderTextPaint);
drawAllDayEvents(day, startPixel, canvas);
startPixel += mWidthPerDay + mColumnGap;
}
}
/**
* Get the time and date where the user clicked on.
* @param x The x position of the touch event.
* @param y The y position of the touch event.
* @return The time and date at the clicked position.
*/
private Calendar getTimeFromPoint(float x, float y){
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start > 0 && x > start && x < startPixel + mWidthPerDay){
Calendar day = today();
day.add(Calendar.DATE, dayNumber - 1);
float pixelsFromZero = y - mCurrentOrigin.y - mHeaderHeight
- mHeaderRowPadding * 2 - mTimeTextHeight/2 - mHeaderMarginBottom;
int hour = (int)(pixelsFromZero / mHourHeight);
int minute = (int) (60 * (pixelsFromZero - hour * mHourHeight) / mHourHeight);
day.add(Calendar.HOUR, hour);
day.set(Calendar.MINUTE, minute);
return day;
}
startPixel += mWidthPerDay + mColumnGap;
}
return null;
}
/**
* Draw all the events of a particular day.
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date) && !mEventRects.get(i).event.isAllDay()){
// Calculate top.
float top = mHourHeight * 24 * mEventRects.get(i).top / 1440 + mCurrentOrigin.y + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 + mEventMarginVertical;
// Calculate bottom.
float bottom = mEventRects.get(i).bottom;
bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin.y + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - mEventMarginVertical;
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
// Draw the event and the event name on top of it.
if (left < right &&
left < getWidth() &&
top < getHeight() &&
right > mHeaderColumnWidth &&
bottom > mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom
) {
mEventRects.get(i).rectF = new RectF(left, top, right, bottom);
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
canvas.drawRoundRect(mEventRects.get(i).rectF, mEventCornerRadius, mEventCornerRadius, mEventBackgroundPaint);
drawEventTitle(mEventRects.get(i).event, mEventRects.get(i).rectF, canvas, top, left);
}
else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw all the Allday-events of a particular day.
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawAllDayEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date) && mEventRects.get(i).event.isAllDay()){
// Calculate top.
float top = mHeaderRowPadding * 2 + mHeaderMarginBottom + + mTimeTextHeight/2 + mEventMarginVertical;
// Calculate bottom.
float bottom = top + mEventRects.get(i).bottom;
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
// Draw the event and the event name on top of it.
if (left < right &&
left < getWidth() &&
top < getHeight() &&
right > mHeaderColumnWidth &&
bottom > 0
) {
mEventRects.get(i).rectF = new RectF(left, top, right, bottom);
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
canvas.drawRoundRect(mEventRects.get(i).rectF, mEventCornerRadius, mEventCornerRadius, mEventBackgroundPaint);
drawEventTitle(mEventRects.get(i).event, mEventRects.get(i).rectF, canvas, top, left);
}
else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw the name of the event on top of the event rectangle.
* @param event The event of which the title (and location) should be drawn.
* @param rect The rectangle on which the text is to be drawn.
* @param canvas The canvas to draw upon.
* @param originalTop The original top position of the rectangle. The rectangle may have some of its portion outside of the visible area.
* @param originalLeft The original left position of the rectangle. The rectangle may have some of its portion outside of the visible area.
*/
private void drawEventTitle(WeekViewEvent event, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
if (rect.bottom - rect.top - mEventPadding * 2 < 0) return;
// Prepare the name of the event.
SpannableStringBuilder bob = new SpannableStringBuilder();
if (event.getName() != null) {
bob.append(event.getName());
bob.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, bob.length(), 0);
bob.append(' ');
}
// Prepare the location of the event.
if (event.getLocation() != null) {
bob.append(event.getLocation());
}
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int availableWidth = (int) (rect.right - originalLeft - mEventPadding * 2);
// Get text dimensions.
StaticLayout textLayout = new StaticLayout(bob, mEventTextPaint, availableWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (availableHeight >= lineHeight) {
// Calculate available number of line counts.
int availableLineCount = availableHeight / lineHeight;
do {
// Ellipsize text to fit into event rect.
textLayout = new StaticLayout(TextUtils.ellipsize(bob, mEventTextPaint, availableLineCount * availableWidth, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Reduce line count.
availableLineCount
// Repeat until text is short enough.
} while (textLayout.getHeight() > availableHeight);
// Draw text.
canvas.save();
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding);
textLayout.draw(canvas);
canvas.restore();
}
}
/**
* A class to hold reference to the events and their visual representation. An EventRect is
* actually the rectangle that is drawn on the calendar for a given event. There may be more
* than one rectangle for a single event (an event that expands more than one day). In that
* case two instances of the EventRect will be used for a single event. The given event will be
* stored in "originalEvent". But the event that corresponds to rectangle the rectangle
* instance will be stored in "event".
*/
private class EventRect {
public WeekViewEvent event;
public WeekViewEvent originalEvent;
public RectF rectF;
public float left;
public float width;
public float top;
public float bottom;
/**
* Create a new instance of event rect. An EventRect is actually the rectangle that is drawn
* on the calendar for a given event. There may be more than one rectangle for a single
* event (an event that expands more than one day). In that case two instances of the
* EventRect will be used for a single event. The given event will be stored in
* "originalEvent". But the event that corresponds to rectangle the rectangle instance will
* be stored in "event".
* @param event Represents the event which this instance of rectangle represents.
* @param originalEvent The original event that was passed by the user.
* @param rectF The rectangle.
*/
public EventRect(WeekViewEvent event, WeekViewEvent originalEvent, RectF rectF) {
this.event = event;
this.rectF = rectF;
this.originalEvent = originalEvent;
}
}
/**
* Gets more events of one/more month(s) if necessary. This method is called when the user is
* scrolling the week view. The week view stores the events of three months: the visible month,
* the previous month, the next month.
* @param day The day where the user is currently is.
*/
private void getMoreEvents(Calendar day) {
// Get more events if the month is changed.
if (mEventRects == null)
mEventRects = new ArrayList<EventRect>();
if (mWeekViewLoader == null && !isInEditMode())
throw new IllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if (mRefreshEvents) {
mEventRects.clear();
mPreviousPeriodEvents = null;
mCurrentPeriodEvents = null;
mNextPeriodEvents = null;
mFetchedPeriod = -1;
}
if (mWeekViewLoader != null){
int periodToFetch = (int) mWeekViewLoader.toWeekViewPeriodIndex(day);
if (!isInEditMode() && (mFetchedPeriod < 0 || mFetchedPeriod != periodToFetch || mRefreshEvents)) {
List<? extends WeekViewEvent> previousPeriodEvents = null;
List<? extends WeekViewEvent> currentPeriodEvents = null;
List<? extends WeekViewEvent> nextPeriodEvents = null;
if (mPreviousPeriodEvents != null && mCurrentPeriodEvents != null && mNextPeriodEvents != null){
if (periodToFetch == mFetchedPeriod-1){
currentPeriodEvents = mPreviousPeriodEvents;
nextPeriodEvents = mCurrentPeriodEvents;
}
else if (periodToFetch == mFetchedPeriod){
previousPeriodEvents = mPreviousPeriodEvents;
currentPeriodEvents = mCurrentPeriodEvents;
nextPeriodEvents = mNextPeriodEvents;
}
else if (periodToFetch == mFetchedPeriod+1){
previousPeriodEvents = mCurrentPeriodEvents;
currentPeriodEvents = mNextPeriodEvents;
}
}
if (currentPeriodEvents == null)
currentPeriodEvents = mWeekViewLoader.onLoad(periodToFetch);
if (previousPeriodEvents == null)
previousPeriodEvents = mWeekViewLoader.onLoad(periodToFetch-1);
if (nextPeriodEvents == null)
nextPeriodEvents = mWeekViewLoader.onLoad(periodToFetch+1);
// Clear events.
mEventRects.clear();
sortAndCacheEvents(previousPeriodEvents);
sortAndCacheEvents(currentPeriodEvents);
sortAndCacheEvents(nextPeriodEvents);
mPreviousPeriodEvents = previousPeriodEvents;
mCurrentPeriodEvents = currentPeriodEvents;
mNextPeriodEvents = nextPeriodEvents;
mFetchedPeriod = periodToFetch;
}
}
// Prepare to calculate positions of each events.
List<EventRect> tempEvents = mEventRects;
mEventRects = new ArrayList<EventRect>();
// Iterate through each day with events to calculate the position of the events.
while (tempEvents.size() > 0) {
ArrayList<EventRect> eventRects = new ArrayList<>(tempEvents.size());
// Get first event for a day.
EventRect eventRect1 = tempEvents.remove(0);
eventRects.add(eventRect1);
int i = 0;
while (i < tempEvents.size()) {
// Collect all other events for same day.
EventRect eventRect2 = tempEvents.get(i);
if (isSameDay(eventRect1.event.getStartTime(), eventRect2.event.getStartTime())) {
tempEvents.remove(i);
eventRects.add(eventRect2);
} else {
i++;
}
}
computePositionOfEvents(eventRects);
}
}
/**
* Cache the event for smooth scrolling functionality.
* @param event The event to cache.
*/
private void cacheEvent(WeekViewEvent event) {
if(event.getStartTime().compareTo(event.getEndTime()) >= 0)
return;
if (!isSameDay(event.getStartTime(), event.getEndTime())) {
// Add first day.
Calendar endTime = (Calendar) event.getStartTime().clone();
endTime.set(Calendar.HOUR_OF_DAY, 23);
endTime.set(Calendar.MINUTE, 59);
WeekViewEvent event1 = new WeekViewEvent(event.getId(), event.getName(), event.getLocation(), event.getStartTime(), endTime, event.isAllDay());
event1.setColor(event.getColor());
mEventRects.add(new EventRect(event1, event, null));
// Add other days.
Calendar otherDay = (Calendar) event.getStartTime().clone();
otherDay.add(Calendar.DATE, 1);
while (!isSameDay(otherDay, event.getEndTime())) {
Calendar overDay = (Calendar) otherDay.clone();
overDay.set(Calendar.HOUR_OF_DAY, 0);
overDay.set(Calendar.MINUTE, 0);
Calendar endOfOverDay = (Calendar) overDay.clone();
endOfOverDay.set(Calendar.HOUR_OF_DAY, 23);
endOfOverDay.set(Calendar.MINUTE, 59);
WeekViewEvent eventMore = new WeekViewEvent(event.getId(), event.getName(),null, overDay, endOfOverDay, event.isAllDay());
eventMore.setColor(event.getColor());
mEventRects.add(new EventRect(eventMore, event, null));
// Add next day.
otherDay.add(Calendar.DATE, 1);
}
// Add last day.
Calendar startTime = (Calendar) event.getEndTime().clone();
startTime.set(Calendar.HOUR_OF_DAY, 0);
startTime.set(Calendar.MINUTE, 0);
WeekViewEvent event2 = new WeekViewEvent(event.getId(), event.getName(), event.getLocation(), startTime, event.getEndTime(), event.isAllDay());
event2.setColor(event.getColor());
mEventRects.add(new EventRect(event2, event, null));
}
else {
mEventRects.add(new EventRect(event, event, null));
}
}
/**
* Sort and cache events.
* @param events The events to be sorted and cached.
*/
private void sortAndCacheEvents(List<? extends WeekViewEvent> events) {
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
/**
* Sorts the events in ascending order.
* @param events The events to be sorted.
*/
private void sortEvents(List<? extends WeekViewEvent> events) {
Collections.sort(events, new Comparator<WeekViewEvent>() {
@Override
public int compare(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
int comparator = start1 > start2 ? 1 : (start1 < start2 ? -1 : 0);
if (comparator == 0) {
long end1 = event1.getEndTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
comparator = end1 > end2 ? 1 : (end1 < end2 ? -1 : 0);
}
return comparator;
}
});
}
/**
* Calculates the left and right positions of each events. This comes handy specially if events
* are overlapping.
* @param eventRects The events along with their wrapper class.
*/
private void computePositionOfEvents(List<EventRect> eventRects) {
// Make "collision groups" for all events that collide with others.
List<List<EventRect>> collisionGroups = new ArrayList<List<EventRect>>();
for (EventRect eventRect : eventRects) {
boolean isPlaced = false;
outerLoop:
for (List<EventRect> collisionGroup : collisionGroups) {
for (EventRect groupEvent : collisionGroup) {
if (isEventsCollide(groupEvent.event, eventRect.event) && groupEvent.event.isAllDay() == eventRect.event.isAllDay()) {
collisionGroup.add(eventRect);
isPlaced = true;
break outerLoop;
}
}
}
if (!isPlaced) {
List<EventRect> newGroup = new ArrayList<EventRect>();
newGroup.add(eventRect);
collisionGroups.add(newGroup);
}
}
for (List<EventRect> collisionGroup : collisionGroups) {
expandEventsToMaxWidth(collisionGroup);
}
}
/**
* Expands all the events to maximum possible width. The events will try to occupy maximum
* space available horizontally.
* @param collisionGroup The group of events which overlap with each other.
*/
private void expandEventsToMaxWidth(List<EventRect> collisionGroup) {
// Expand the events to maximum possible width.
List<List<EventRect>> columns = new ArrayList<List<EventRect>>();
columns.add(new ArrayList<EventRect>());
for (EventRect eventRect : collisionGroup) {
boolean isPlaced = false;
for (List<EventRect> column : columns) {
if (column.size() == 0) {
column.add(eventRect);
isPlaced = true;
}
else if (!isEventsCollide(eventRect.event, column.get(column.size()-1).event)) {
column.add(eventRect);
isPlaced = true;
break;
}
}
if (!isPlaced) {
List<EventRect> newColumn = new ArrayList<EventRect>();
newColumn.add(eventRect);
columns.add(newColumn);
}
}
// Calculate left and right position for all the events.
// Get the maxRowCount by looking in all columns.
int maxRowCount = 0;
for (List<EventRect> column : columns){
maxRowCount = Math.max(maxRowCount, column.size());
}
for (int i = 0; i < maxRowCount; i++) {
// Set the left and right values of the event.
float j = 0;
for (List<EventRect> column : columns) {
if (column.size() >= i+1) {
EventRect eventRect = column.get(i);
eventRect.width = 1f / columns.size();
eventRect.left = j / columns.size();
if(!eventRect.event.isAllDay()) {
eventRect.top = eventRect.event.getStartTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getStartTime().get(Calendar.MINUTE);
eventRect.bottom = eventRect.event.getEndTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getEndTime().get(Calendar.MINUTE);
}
else{
eventRect.top = 0;
eventRect.bottom = mAllDayEventHeight;
}
mEventRects.add(eventRect);
}
j++;
}
}
}
/**
* Checks if two events overlap.
* @param event1 The first event.
* @param event2 The second event.
* @return true if the events overlap.
*/
private boolean isEventsCollide(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long end1 = event1.getEndTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
return !((start1 >= end2) || (end1 <= start2));
}
/**
* Checks if time1 occurs after (or at the same time) time2.
* @param time1 The time to check.
* @param time2 The time to check against.
* @return true if time1 and time2 are equal or if time1 is after time2. Otherwise false.
*/
private boolean isTimeAfterOrEquals(Calendar time1, Calendar time2) {
return !(time1 == null || time2 == null) && time1.getTimeInMillis() >= time2.getTimeInMillis();
}
@Override
public void invalidate() {
super.invalidate();
mAreDimensionsInvalid = true;
}
// Functions related to setting and getting the properties.
public void setOnEventClickListener (EventClickListener listener) {
this.mEventClickListener = listener;
}
public EventClickListener getEventClickListener() {
return mEventClickListener;
}
public @Nullable MonthLoader.MonthChangeListener getMonthChangeListener() {
if (mWeekViewLoader instanceof MonthLoader)
return ((MonthLoader) mWeekViewLoader).getOnMonthChangeListener();
return null;
}
public void setMonthChangeListener(MonthLoader.MonthChangeListener monthChangeListener) {
this.mWeekViewLoader = new MonthLoader(monthChangeListener);
}
/**
* Get event loader in the week view. Event loaders define the interval after which the events
* are loaded in week view. For a MonthLoader events are loaded for every month. You can define
* your custom event loader by extending WeekViewLoader.
* @return The event loader.
*/
public WeekViewLoader getWeekViewLoader(){
return mWeekViewLoader;
}
/**
* Set event loader in the week view. For example, a MonthLoader. Event loaders define the
* interval after which the events are loaded in week view. For a MonthLoader events are loaded
* for every month. You can define your custom event loader by extending WeekViewLoader.
* @param loader The event loader.
*/
public void setWeekViewLoader(WeekViewLoader loader){
this.mWeekViewLoader = loader;
}
public EventLongPressListener getEventLongPressListener() {
return mEventLongPressListener;
}
public void setEventLongPressListener(EventLongPressListener eventLongPressListener) {
this.mEventLongPressListener = eventLongPressListener;
}
public void setEmptyViewClickListener(EmptyViewClickListener emptyViewClickListener){
this.mEmptyViewClickListener = emptyViewClickListener;
}
public EmptyViewClickListener getEmptyViewClickListener(){
return mEmptyViewClickListener;
}
public void setEmptyViewLongPressListener(EmptyViewLongPressListener emptyViewLongPressListener){
this.mEmptyViewLongPressListener = emptyViewLongPressListener;
}
public EmptyViewLongPressListener getEmptyViewLongPressListener(){
return mEmptyViewLongPressListener;
}
public void setScrollListener(ScrollListener scrolledListener){
this.mScrollListener = scrolledListener;
}
public ScrollListener getScrollListener(){
return mScrollListener;
}
/**
* Get the interpreter which provides the text to show in the header column and the header row.
* @return The date, time interpreter.
*/
public DateTimeInterpreter getDateTimeInterpreter() {
if (mDateTimeInterpreter == null) {
mDateTimeInterpreter = new DateTimeInterpreter() {
@Override
public String interpretDate(Calendar date) {
try {
SimpleDateFormat sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE M/dd", Locale.getDefault()) : new SimpleDateFormat("EEE M/dd", Locale.getDefault());
return sdf.format(date.getTime()).toUpperCase();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
@Override
public String interpretTime(int hour) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, 0);
try {
SimpleDateFormat sdf = DateFormat.is24HourFormat(getContext()) ? new SimpleDateFormat("HH:mm", Locale.getDefault()) : new SimpleDateFormat("hh a", Locale.getDefault());
return sdf.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
};
}
return mDateTimeInterpreter;
}
/**
* Set the interpreter which provides the text to show in the header column and the header row.
* @param dateTimeInterpreter The date, time interpreter.
*/
public void setDateTimeInterpreter(DateTimeInterpreter dateTimeInterpreter){
this.mDateTimeInterpreter = dateTimeInterpreter;
// Refresh time column width.
initTextTimeWidth();
}
/**
* Get the number of visible days in a week.
* @return The number of visible days in a week.
*/
public int getNumberOfVisibleDays() {
return mNumberOfVisibleDays;
}
/**
* Set the number of visible days in a week.
* @param numberOfVisibleDays The number of visible days in a week.
*/
public void setNumberOfVisibleDays(int numberOfVisibleDays) {
this.mNumberOfVisibleDays = numberOfVisibleDays;
mCurrentOrigin.x = 0;
mCurrentOrigin.y = 0;
invalidate();
}
public int getHourHeight() {
return mHourHeight;
}
public void setHourHeight(int hourHeight) {
mNewHourHeight = hourHeight;
invalidate();
}
public int getColumnGap() {
return mColumnGap;
}
public void setColumnGap(int columnGap) {
mColumnGap = columnGap;
invalidate();
}
public int getFirstDayOfWeek() {
return mFirstDayOfWeek;
}
/**
* Set the first day of the week. First day of the week is used only when the week view is first
* drawn. It does not of any effect after user starts scrolling horizontally.
* <p>
* <b>Note:</b> This method will only work if the week view is set to display more than 6 days at
* once.
* </p>
* @param firstDayOfWeek The supported values are {@link java.util.Calendar#SUNDAY},
* {@link java.util.Calendar#MONDAY}, {@link java.util.Calendar#TUESDAY},
* {@link java.util.Calendar#WEDNESDAY}, {@link java.util.Calendar#THURSDAY},
* {@link java.util.Calendar#FRIDAY}.
*/
public void setFirstDayOfWeek(int firstDayOfWeek) {
mFirstDayOfWeek = firstDayOfWeek;
invalidate();
}
public int getTextSize() {
return mTextSize;
}
public void setTextSize(int textSize) {
mTextSize = textSize;
mTodayHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setTextSize(mTextSize);
invalidate();
}
public int getHeaderColumnPadding() {
return mHeaderColumnPadding;
}
public void setHeaderColumnPadding(int headerColumnPadding) {
mHeaderColumnPadding = headerColumnPadding;
invalidate();
}
public int getHeaderColumnTextColor() {
return mHeaderColumnTextColor;
}
public void setHeaderColumnTextColor(int headerColumnTextColor) {
mHeaderColumnTextColor = headerColumnTextColor;
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
invalidate();
}
public int getHeaderRowPadding() {
return mHeaderRowPadding;
}
public void setHeaderRowPadding(int headerRowPadding) {
mHeaderRowPadding = headerRowPadding;
invalidate();
}
public int getHeaderRowBackgroundColor() {
return mHeaderRowBackgroundColor;
}
public void setHeaderRowBackgroundColor(int headerRowBackgroundColor) {
mHeaderRowBackgroundColor = headerRowBackgroundColor;
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
invalidate();
}
public int getDayBackgroundColor() {
return mDayBackgroundColor;
}
public void setDayBackgroundColor(int dayBackgroundColor) {
mDayBackgroundColor = dayBackgroundColor;
mDayBackgroundPaint.setColor(mDayBackgroundColor);
invalidate();
}
public int getHourSeparatorColor() {
return mHourSeparatorColor;
}
public void setHourSeparatorColor(int hourSeparatorColor) {
mHourSeparatorColor = hourSeparatorColor;
mHourSeparatorPaint.setColor(mHourSeparatorColor);
invalidate();
}
public int getTodayBackgroundColor() {
return mTodayBackgroundColor;
}
public void setTodayBackgroundColor(int todayBackgroundColor) {
mTodayBackgroundColor = todayBackgroundColor;
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
invalidate();
}
public int getHourSeparatorHeight() {
return mHourSeparatorHeight;
}
public void setHourSeparatorHeight(int hourSeparatorHeight) {
mHourSeparatorHeight = hourSeparatorHeight;
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
invalidate();
}
public int getTodayHeaderTextColor() {
return mTodayHeaderTextColor;
}
public void setTodayHeaderTextColor(int todayHeaderTextColor) {
mTodayHeaderTextColor = todayHeaderTextColor;
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
invalidate();
}
public int getEventTextSize() {
return mEventTextSize;
}
public void setEventTextSize(int eventTextSize) {
mEventTextSize = eventTextSize;
mEventTextPaint.setTextSize(mEventTextSize);
invalidate();
}
public int getEventTextColor() {
return mEventTextColor;
}
public void setEventTextColor(int eventTextColor) {
mEventTextColor = eventTextColor;
mEventTextPaint.setColor(mEventTextColor);
invalidate();
}
public int getEventPadding() {
return mEventPadding;
}
public void setEventPadding(int eventPadding) {
mEventPadding = eventPadding;
invalidate();
}
public int getHeaderColumnBackgroundColor() {
return mHeaderColumnBackgroundColor;
}
public void setHeaderColumnBackgroundColor(int headerColumnBackgroundColor) {
mHeaderColumnBackgroundColor = headerColumnBackgroundColor;
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
invalidate();
}
public int getDefaultEventColor() {
return mDefaultEventColor;
}
public void setDefaultEventColor(int defaultEventColor) {
mDefaultEventColor = defaultEventColor;
invalidate();
}
/**
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} and
* {@link #getDateTimeInterpreter()} instead.
* @return Either long or short day name is being used.
*/
@Deprecated
public int getDayNameLength() {
return mDayNameLength;
}
/**
* Set the length of the day name displayed in the header row. Example of short day names is
* 'M' for 'Monday' and example of long day names is 'Mon' for 'Monday'.
* <p>
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} instead.
* </p>
* @param length Supported values are {@link com.alamkanak.weekview.WeekView#LENGTH_SHORT} and
* {@link com.alamkanak.weekview.WeekView#LENGTH_LONG}.
*/
@Deprecated
public void setDayNameLength(int length) {
if (length != LENGTH_LONG && length != LENGTH_SHORT) {
throw new IllegalArgumentException("length parameter must be either LENGTH_LONG or LENGTH_SHORT");
}
this.mDayNameLength = length;
}
public int getOverlappingEventGap() {
return mOverlappingEventGap;
}
/**
* Set the gap between overlapping events.
* @param overlappingEventGap The gap between overlapping events.
*/
public void setOverlappingEventGap(int overlappingEventGap) {
this.mOverlappingEventGap = overlappingEventGap;
invalidate();
}
public int getEventCornerRadius() {
return mEventCornerRadius;
}
/**
* Set corner radius for event rect.
*
* @param eventCornerRadius the radius in px.
*/
public void setEventCornerRadius(int eventCornerRadius) {
mEventCornerRadius = eventCornerRadius;
}
public int getEventMarginVertical() {
return mEventMarginVertical;
}
/**
* Set the top and bottom margin of the event. The event will release this margin from the top
* and bottom edge. This margin is useful for differentiation consecutive events.
* @param eventMarginVertical The top and bottom margin.
*/
public void setEventMarginVertical(int eventMarginVertical) {
this.mEventMarginVertical = eventMarginVertical;
invalidate();
}
/**
* Returns the first visible day in the week view.
* @return The first visible day in the week view.
*/
public Calendar getFirstVisibleDay() {
return mFirstVisibleDay;
}
/**
* Returns the last visible day in the week view.
* @return The last visible day in the week view.
*/
public Calendar getLastVisibleDay() {
return mLastVisibleDay;
}
/**
* Get the scrolling speed factor in horizontal direction.
* @return The speed factor in horizontal direction.
*/
public float getXScrollingSpeed() {
return mXScrollingSpeed;
}
/**
* Sets the speed for horizontal scrolling.
* @param xScrollingSpeed The new horizontal scrolling speed.
*/
public void setXScrollingSpeed(float xScrollingSpeed) {
this.mXScrollingSpeed = xScrollingSpeed;
}
/**
* Whether weekends should have a background color different from the normal day background
* color. The weekend background colors are defined by the attributes
* `futureWeekendBackgroundColor` and `pastWeekendBackgroundColor`.
* @return True if weekends should have different background colors.
*/
public boolean isShowDistinctWeekendColor() {
return mShowDistinctWeekendColor;
}
/**
* Set whether weekends should have a background color different from the normal day background
* color. The weekend background colors are defined by the attributes
* `futureWeekendBackgroundColor` and `pastWeekendBackgroundColor`.
* @param showDistinctWeekendColor True if weekends should have different background colors.
*/
public void setShowDistinctWeekendColor(boolean showDistinctWeekendColor) {
this.mShowDistinctWeekendColor = showDistinctWeekendColor;
invalidate();
}
/**
* Whether past and future days should have two different background colors. The past and
* future day colors are defined by the attributes `futureBackgroundColor` and
* `pastBackgroundColor`.
* @return True if past and future days should have two different background colors.
*/
public boolean isShowDistinctPastFutureColor() {
return mShowDistinctPastFutureColor;
}
/**
* Set whether weekends should have a background color different from the normal day background
* color. The past and future day colors are defined by the attributes `futureBackgroundColor`
* and `pastBackgroundColor`.
* @param showDistinctPastFutureColor True if past and future should have two different
* background colors.
*/
public void setShowDistinctPastFutureColor(boolean showDistinctPastFutureColor) {
this.mShowDistinctPastFutureColor = showDistinctPastFutureColor;
invalidate();
}
/**
* Get whether "now" line should be displayed. "Now" line is defined by the attributes
* `nowLineColor` and `nowLineThickness`.
* @return True if "now" line should be displayed.
*/
public boolean isShowNowLine() {
return mShowNowLine;
}
/**
* Set whether "now" line should be displayed. "Now" line is defined by the attributes
* `nowLineColor` and `nowLineThickness`.
* @param showNowLine True if "now" line should be displayed.
*/
public void setShowNowLine(boolean showNowLine) {
this.mShowNowLine = showNowLine;
invalidate();
}
/**
* Get the "now" line color.
* @return The color of the "now" line.
*/
public int getNowLineColor() {
return mNowLineColor;
}
/**
* Set the "now" line color.
* @param nowLineColor The color of the "now" line.
*/
public void setNowLineColor(int nowLineColor) {
this.mNowLineColor = nowLineColor;
invalidate();
}
/**
* Get the "now" line thickness.
* @return The thickness of the "now" line.
*/
public int getNowLineThickness() {
return mNowLineThickness;
}
/**
* Set the "now" line thickness.
* @param nowLineThickness The thickness of the "now" line.
*/
public void setNowLineThickness(int nowLineThickness) {
this.mNowLineThickness = nowLineThickness;
invalidate();
}
/**
* Get whether the week view should fling horizontally.
* @return True if the week view has horizontal fling enabled.
*/
public boolean isHorizontalFlingEnabled() {
return mHorizontalFlingEnabled;
}
/**
* Set whether the week view should fling horizontally.
* @return True if it should have horizontal fling enabled.
*/
public void setHorizontalFlingEnabled(boolean enabled) {
mHorizontalFlingEnabled = enabled;
}
/**
* Get whether the week view should fling vertically.
* @return True if the week view has vertical fling enabled.
*/
public boolean isVerticalFlingEnabled() {
return mVerticalFlingEnabled;
}
/**
* Set whether the week view should fling vertically.
* @return True if it should have vertical fling enabled.
*/
public void setVerticalFlingEnabled(boolean enabled) {
mVerticalFlingEnabled = enabled;
}
/**
* Get the height of AllDay-events
* @return Height of AllDay-events
*/
public int getAllDayEventHeight(){ return mAllDayEventHeight; }
/**
* Set the height of AllDay-events
* @param height
*/
public void setAllDayEventHeight(int height){ mAllDayEventHeight = height; }
// Functions related to scrolling.
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
boolean val = mGestureDetector.onTouchEvent(event);
// Check after call of mGestureDetector, so mCurrentFlingDirection and mCurrentScrollDirection are set.
if (event.getAction() == MotionEvent.ACTION_UP && !mIsZooming && mCurrentFlingDirection == Direction.NONE) {
if (mCurrentScrollDirection == Direction.RIGHT || mCurrentScrollDirection == Direction.LEFT) {
goToNearestOrigin();
}
mCurrentScrollDirection = Direction.NONE;
}
return val;
}
private void goToNearestOrigin(){
double leftDays = mCurrentOrigin.x / (mWidthPerDay + mColumnGap);
if (mCurrentFlingDirection != Direction.NONE) {
// snap to nearest day
leftDays = Math.round(leftDays);
} else if (mCurrentScrollDirection == Direction.LEFT) {
// snap to last day
leftDays = Math.floor(leftDays);
} else if (mCurrentScrollDirection == Direction.RIGHT) {
// snap to next day
leftDays = Math.ceil(leftDays);
} else {
// snap to nearest day
leftDays = Math.round(leftDays);
}
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay + mColumnGap));
if (nearestOrigin != 0) {
// Stop current animation.
mScroller.forceFinished(true);
// Snap to date.
mScroller.startScroll((int) mCurrentOrigin.x, (int) mCurrentOrigin.y, -nearestOrigin, 0, (int) (Math.abs(nearestOrigin) / mWidthPerDay * 500));
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
// Reset scrolling and fling direction.
mCurrentScrollDirection = mCurrentFlingDirection = Direction.NONE;
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.isFinished()) {
if (mCurrentFlingDirection != Direction.NONE) {
// Snap to day after fling is finished.
goToNearestOrigin();
}
} else {
if (mCurrentFlingDirection != Direction.NONE && forceFinishScroll()) {
goToNearestOrigin();
} else if (mScroller.computeScrollOffset()) {
mCurrentOrigin.y = mScroller.getCurrY();
mCurrentOrigin.x = mScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
}
/**
* Check if scrolling should be stopped.
* @return true if scrolling should be stopped before reaching the end of animation.
*/
private boolean forceFinishScroll() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// current velocity only available since api 14
return mScroller.getCurrVelocity() <= mMinimumFlingVelocity;
} else {
return false;
}
}
// Public methods.
/**
* Show today on the week view.
*/
public void goToToday() {
Calendar today = Calendar.getInstance();
goToDate(today);
}
/**
* Show a specific day on the week view.
* @param date The date to show.
*/
public void goToDate(Calendar date) {
mScroller.forceFinished(true);
mCurrentScrollDirection = mCurrentFlingDirection = Direction.NONE;
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
if(mAreDimensionsInvalid) {
mScrollToDay = date;
return;
}
mRefreshEvents = true;
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
long day = 1000L * 60L * 60L * 24L;
long dateInMillis = date.getTimeInMillis() + date.getTimeZone().getOffset(date.getTimeInMillis());
long todayInMillis = today.getTimeInMillis() + today.getTimeZone().getOffset(today.getTimeInMillis());
long dateDifference = (dateInMillis/day) - (todayInMillis/day);
mCurrentOrigin.x = - dateDifference * (mWidthPerDay + mColumnGap);
invalidate();
}
/**
* Refreshes the view and loads the events again.
*/
public void notifyDatasetChanged(){
mRefreshEvents = true;
invalidate();
}
/**
* Vertically scroll to a specific hour in the week view.
* @param hour The hour to scroll to in 24-hour format. Supported values are 0-24.
*/
public void goToHour(double hour){
if (mAreDimensionsInvalid) {
mScrollToHour = hour;
return;
}
int verticalOffset = 0;
if (hour > 24)
verticalOffset = mHourHeight * 24;
else if (hour > 0)
verticalOffset = (int) (mHourHeight * hour);
if (verticalOffset > mHourHeight * 24 - getHeight() + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)
verticalOffset = (int)(mHourHeight * 24 - getHeight() + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom);
mCurrentOrigin.y = -verticalOffset;
invalidate();
}
/**
* Get the first hour that is visible on the screen.
* @return The first hour that is visible.
*/
public double getFirstVisibleHour(){
return -mCurrentOrigin.y / mHourHeight;
}
// Interfaces.
public interface EventClickListener {
/**
* Triggered when clicked on one existing event
* @param event: event clicked.
* @param eventRect: view containing the clicked event.
*/
void onEventClick(WeekViewEvent event, RectF eventRect);
}
public interface EventLongPressListener {
/**
* Similar to {@link com.alamkanak.weekview.WeekView.EventClickListener} but with a long press.
* @param event: event clicked.
* @param eventRect: view containing the clicked event.
*/
void onEventLongPress(WeekViewEvent event, RectF eventRect);
}
public interface EmptyViewClickListener {
/**
* Triggered when the users clicks on a empty space of the calendar.
* @param time: {@link Calendar} object set with the date and time of the clicked position on the view.
*/
void onEmptyViewClicked(Calendar time);
}
public interface EmptyViewLongPressListener {
/**
* Similar to {@link com.alamkanak.weekview.WeekView.EmptyViewClickListener} but with long press.
* @param time: {@link Calendar} object set with the date and time of the long pressed position on the view.
*/
void onEmptyViewLongPress(Calendar time);
}
public interface ScrollListener {
/**
* Called when the first visible day has changed.
*
* (this will also be called during the first draw of the weekview)
* @param newFirstVisibleDay The new first visible day
* @param oldFirstVisibleDay The old first visible day (is null on the first call).
*/
void onFirstVisibleDayChanged(Calendar newFirstVisibleDay, Calendar oldFirstVisibleDay);
}
// Helper methods.
/**
* Checks if two times are on the same day.
* @param dayOne The first day.
* @param dayTwo The second day.
* @return Whether the times are on the same day.
*/
private boolean isSameDay(Calendar dayOne, Calendar dayTwo) {
return dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR) && dayOne.get(Calendar.DAY_OF_YEAR) == dayTwo.get(Calendar.DAY_OF_YEAR);
}
/**
* Returns a calendar instance at the start of this day
* @return the calendar instance
*/
private Calendar today(){
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
return today;
}
}
|
package com.alamkanak.weekview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.style.StyleSpan;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.OverScroller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import static com.alamkanak.weekview.WeekViewUtil.daysBetween;
import static com.alamkanak.weekview.WeekViewUtil.getPassedMinutesInDay;
import static com.alamkanak.weekview.WeekViewUtil.isSameDay;
import static com.alamkanak.weekview.WeekViewUtil.today;
public class WeekView extends View {
private enum Direction {
NONE, LEFT, RIGHT, VERTICAL
}
@Deprecated
public static final int LENGTH_SHORT = 1;
@Deprecated
public static final int LENGTH_LONG = 2;
private final Context mContext;
private Calendar mHomeDate;
private Calendar mMinDate;
private Calendar mMaxDate;
private Paint mTimeTextPaint;
private float mTimeTextWidth;
private float mTimeTextHeight;
private Paint mHeaderTextPaint;
private float mHeaderTextHeight;
private float mHeaderHeight;
private GestureDetectorCompat mGestureDetector;
private OverScroller mScroller;
private PointF mCurrentOrigin = new PointF(0f, 0f);
private Direction mCurrentScrollDirection = Direction.NONE;
private Paint mHeaderBackgroundPaint;
private float mWidthPerDay;
private Paint mDayBackgroundPaint;
private Paint mHourSeparatorPaint;
private float mHeaderMarginBottom;
private Paint mTodayBackgroundPaint;
private Paint mFutureBackgroundPaint;
private Paint mPastBackgroundPaint;
private Paint mFutureWeekendBackgroundPaint;
private Paint mPastWeekendBackgroundPaint;
private Paint mNowLinePaint;
private Paint mTodayHeaderTextPaint;
private Paint mEventBackgroundPaint;
private Paint mNewEventBackgroundPaint;
private float mHeaderColumnWidth;
private List<EventRect> mEventRects;
private List<WeekViewEvent> mEvents;
private TextPaint mEventTextPaint;
private TextPaint mNewEventTextPaint;
private Paint mHeaderColumnBackgroundPaint;
private int mFetchedPeriod = -1; // the middle period the calendar has fetched.
private boolean mRefreshEvents = false;
private Direction mCurrentFlingDirection = Direction.NONE;
private ScaleGestureDetector mScaleDetector;
private boolean mIsZooming;
private Calendar mFirstVisibleDay;
private Calendar mLastVisibleDay;
private int mMinimumFlingVelocity = 0;
private int mScaledTouchSlop = 0;
private EventRect mNewEventRect;
private TextColorPicker textColorPicker;
// Attributes and their default values.
private int mHourHeight = 50;
private int mNewHourHeight = -1;
private int mMinHourHeight = 0; //no minimum specified (will be dynamic, based on screen)
private int mEffectiveMinHourHeight = mMinHourHeight; //compensates for the fact that you can't keep zooming out.
private int mMaxHourHeight = 250;
private int mColumnGap = 10;
private int mFirstDayOfWeek = Calendar.MONDAY;
private int mTextSize = 12;
private int mHeaderColumnPadding = 10;
private int mHeaderColumnTextColor = Color.BLACK;
private int mNumberOfVisibleDays = 3;
private int mHeaderRowPadding = 10;
private int mHeaderRowBackgroundColor = Color.WHITE;
private int mDayBackgroundColor = Color.rgb(245, 245, 245);
private int mPastBackgroundColor = Color.rgb(227, 227, 227);
private int mFutureBackgroundColor = Color.rgb(245, 245, 245);
private int mPastWeekendBackgroundColor = 0;
private int mFutureWeekendBackgroundColor = 0;
private int mNowLineColor = Color.rgb(102, 102, 102);
private int mNowLineThickness = 5;
private int mHourSeparatorColor = Color.rgb(230, 230, 230);
private int mTodayBackgroundColor = Color.rgb(239, 247, 254);
private int mHourSeparatorHeight = 2;
private int mTodayHeaderTextColor = Color.rgb(39, 137, 228);
private int mEventTextSize = 12;
private int mEventTextColor = Color.BLACK;
private int mEventPadding = 8;
private int mHeaderColumnBackgroundColor = Color.WHITE;
private int mDefaultEventColor;
private int mNewEventColor;
private String mNewEventIdentifier = "-100";
private Drawable mNewEventIconDrawable;
private int mNewEventLengthInMinutes = 60;
private int mNewEventTimeResolutionInMinutes = 15;
private boolean mShowFirstDayOfWeekFirst = false;
private boolean mIsFirstDraw = true;
private boolean mAreDimensionsInvalid = true;
@Deprecated
private int mDayNameLength = LENGTH_LONG;
private int mOverlappingEventGap = 0;
private int mEventMarginVertical = 0;
private float mXScrollingSpeed = 1f;
private Calendar mScrollToDay = null;
private double mScrollToHour = -1;
private int mEventCornerRadius = 0;
private boolean mShowDistinctWeekendColor = false;
private boolean mShowNowLine = false;
private boolean mShowDistinctPastFutureColor = false;
private boolean mHorizontalFlingEnabled = true;
private boolean mVerticalFlingEnabled = true;
private int mAllDayEventHeight = 100;
private float mZoomFocusPoint = 0;
private boolean mZoomFocusPointEnabled = true;
private int mScrollDuration = 250;
private int mTimeColumnResolution = 60;
private Typeface mTypeface = Typeface.DEFAULT_BOLD;
private int mMinTime = 0;
private int mMaxTime = 24;
private boolean mAutoLimitTime = false;
private boolean mEnableDropListener = false;
private int mMinOverlappingMinutes = 0;
// Listeners.
private EventClickListener mEventClickListener;
private EventLongPressListener mEventLongPressListener;
private WeekViewLoader mWeekViewLoader;
private EmptyViewClickListener mEmptyViewClickListener;
private EmptyViewLongPressListener mEmptyViewLongPressListener;
private DateTimeInterpreter mDateTimeInterpreter;
private ScrollListener mScrollListener;
private AddEventClickListener mAddEventClickListener;
private DropListener mDropListener;
private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
goToNearestOrigin();
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// Check if view is zoomed.
if (mIsZooming)
return true;
switch (mCurrentScrollDirection) {
case NONE: {
// Allow scrolling only in one direction.
if (Math.abs(distanceX) > Math.abs(distanceY)) {
if (distanceX > 0) {
mCurrentScrollDirection = Direction.LEFT;
} else {
mCurrentScrollDirection = Direction.RIGHT;
}
} else {
mCurrentScrollDirection = Direction.VERTICAL;
}
break;
}
case LEFT: {
// Change direction if there was enough change.
if (Math.abs(distanceX) > Math.abs(distanceY) && (distanceX < -mScaledTouchSlop)) {
mCurrentScrollDirection = Direction.RIGHT;
}
break;
}
case RIGHT: {
// Change direction if there was enough change.
if (Math.abs(distanceX) > Math.abs(distanceY) && (distanceX > mScaledTouchSlop)) {
mCurrentScrollDirection = Direction.LEFT;
}
break;
}
default:
break;
}
// Calculate the new origin after scroll.
switch (mCurrentScrollDirection) {
case LEFT:
case RIGHT:
float minX = getXMinLimit();
float maxX = getXMaxLimit();
if ((mCurrentOrigin.x - (distanceX * mXScrollingSpeed)) > maxX) {
mCurrentOrigin.x = maxX;
} else if ((mCurrentOrigin.x - (distanceX * mXScrollingSpeed)) < minX) {
mCurrentOrigin.x = minX;
} else {
mCurrentOrigin.x -= distanceX * mXScrollingSpeed;
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
break;
case VERTICAL:
float minY = getYMinLimit();
float maxY = getYMaxLimit();
if ((mCurrentOrigin.y - (distanceY)) > maxY) {
mCurrentOrigin.y = maxY;
} else if ((mCurrentOrigin.y - (distanceY)) < minY) {
mCurrentOrigin.y = minY;
} else {
mCurrentOrigin.y -= distanceY;
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
break;
default:
break;
}
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (mIsZooming)
return true;
if ((mCurrentFlingDirection == Direction.LEFT && !mHorizontalFlingEnabled) ||
(mCurrentFlingDirection == Direction.RIGHT && !mHorizontalFlingEnabled) ||
(mCurrentFlingDirection == Direction.VERTICAL && !mVerticalFlingEnabled)) {
return true;
}
mScroller.forceFinished(true);
mCurrentFlingDirection = mCurrentScrollDirection;
switch (mCurrentFlingDirection) {
case LEFT:
case RIGHT:
mScroller.fling((int) mCurrentOrigin.x, (int) mCurrentOrigin.y, (int) (velocityX * mXScrollingSpeed), 0, (int) getXMinLimit(), (int) getXMaxLimit(), (int) getYMinLimit(), (int) getYMaxLimit());
break;
case VERTICAL:
mScroller.fling((int) mCurrentOrigin.x, (int) mCurrentOrigin.y, 0, (int) velocityY, (int) getXMinLimit(), (int) getXMaxLimit(), (int) getYMinLimit(), (int) getYMaxLimit());
break;
default:
break;
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// If the tap was on an event then trigger the callback.
if (mEventRects != null && mEventClickListener != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect eventRect : reversedEventRects) {
if (!mNewEventIdentifier.equals(eventRect.event.getIdentifier()) && eventRect.rectF != null && e.getX() > eventRect.rectF.left && e.getX() < eventRect.rectF.right && e.getY() > eventRect.rectF.top && e.getY() < eventRect.rectF.bottom) {
mEventClickListener.onEventClick(eventRect.originalEvent, eventRect.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
return super.onSingleTapConfirmed(e);
}
}
}
float xOffset = getXStartPixel();
float x = e.getX() - xOffset;
float y = e.getY() - mCurrentOrigin.y;
// If the tap was on add new Event space, then trigger the callback
if (mAddEventClickListener != null && mNewEventRect != null && mNewEventRect.rectF != null &&
mNewEventRect.rectF.contains(x,y)){
mAddEventClickListener.onAddEventClicked(mNewEventRect.event.getStartTime(), mNewEventRect.event.getEndTime());
return super.onSingleTapConfirmed(e);
}
// If the tap was on an empty space, then trigger the callback.
if ((mEmptyViewClickListener != null || mAddEventClickListener != null) && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
List<WeekViewEvent> tempEvents = new ArrayList<>(mEvents);
if (mNewEventRect != null) {
tempEvents.remove(mNewEventRect.event);
mNewEventRect = null;
}
playSoundEffect(SoundEffectConstants.CLICK);
if (mEmptyViewClickListener != null)
mEmptyViewClickListener.onEmptyViewClicked((Calendar) selectedTime.clone());
if (mAddEventClickListener != null) {
//round selectedTime to resolution
selectedTime.add(Calendar.MINUTE, -(mNewEventLengthInMinutes / 2));
//Fix selected time if before the minimum hour
if (selectedTime.get(Calendar.HOUR_OF_DAY) < mMinTime) {
selectedTime.set(Calendar.HOUR_OF_DAY, mMinTime);
selectedTime.set(Calendar.MINUTE, 0);
}
int unroundedMinutes = selectedTime.get(Calendar.MINUTE);
int mod = unroundedMinutes % mNewEventTimeResolutionInMinutes;
selectedTime.add(Calendar.MINUTE, mod < Math.ceil(mNewEventTimeResolutionInMinutes / 2) ? -mod : (mNewEventTimeResolutionInMinutes - mod));
Calendar endTime = (Calendar) selectedTime.clone();
//Minus one to ensure it is the same day and not midnight (next day)
int maxMinutes = (mMaxTime - selectedTime.get(Calendar.HOUR_OF_DAY)) * 60 - selectedTime.get(Calendar.MINUTE) - 1;
endTime.add(Calendar.MINUTE, Math.min(maxMinutes, mNewEventLengthInMinutes));
//If clicked at end of the day, fix selected startTime
if (maxMinutes < mNewEventLengthInMinutes) {
selectedTime.add(Calendar.MINUTE, maxMinutes - mNewEventLengthInMinutes);
}
WeekViewEvent newEvent = new WeekViewEvent(mNewEventIdentifier, "", null, selectedTime, endTime);
float top = mHourHeight * getPassedMinutesInDay(selectedTime) / 60 + getEventsTop();
float bottom = mHourHeight * getPassedMinutesInDay(endTime) / 60 + getEventsTop();
// Calculate left and right.
float left = mWidthPerDay * WeekViewUtil.daysBetween(getFirstVisibleDay(), selectedTime);
float right = left + mWidthPerDay;
// Add the new event if its bounds are valid
if (left < right &&
left < getWidth() &&
top < getHeight() &&
right > mHeaderColumnWidth &&
bottom > 0
) {
RectF dayRectF = new RectF(left, top , right, bottom - mCurrentOrigin.y);
newEvent.setColor(mNewEventColor);
mNewEventRect = new EventRect(newEvent, newEvent, dayRectF);
tempEvents.add(newEvent);
WeekView.this.clearEvents();
cacheAndSortEvents(tempEvents);
computePositionOfEvents(mEventRects);
invalidate();
}
}
}
}
return super.onSingleTapConfirmed(e);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
if (mEventLongPressListener != null && mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventLongPressListener.onEventLongPress(event.originalEvent, event.rectF);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return;
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewLongPressListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
mEmptyViewLongPressListener.onEmptyViewLongPress(selectedTime);
}
}
}
};
public WeekView(Context context) {
this(context, null);
}
public WeekView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WeekView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Hold references.
mContext = context;
// Get the attribute values (if any).
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WeekView, 0, 0);
try {
mFirstDayOfWeek = a.getInteger(R.styleable.WeekView_firstDayOfWeek, mFirstDayOfWeek);
mHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourHeight, mHourHeight);
mMinHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_minHourHeight, mMinHourHeight);
mEffectiveMinHourHeight = mMinHourHeight;
mMaxHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_maxHourHeight, mMaxHourHeight);
mTextSize = a.getDimensionPixelSize(R.styleable.WeekView_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, context.getResources().getDisplayMetrics()));
mHeaderColumnPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerColumnPadding, mHeaderColumnPadding);
mColumnGap = a.getDimensionPixelSize(R.styleable.WeekView_columnGap, mColumnGap);
mHeaderColumnTextColor = a.getColor(R.styleable.WeekView_headerColumnTextColor, mHeaderColumnTextColor);
mNumberOfVisibleDays = a.getInteger(R.styleable.WeekView_noOfVisibleDays, mNumberOfVisibleDays);
mShowFirstDayOfWeekFirst = a.getBoolean(R.styleable.WeekView_showFirstDayOfWeekFirst, mShowFirstDayOfWeekFirst);
mHeaderRowPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerRowPadding, mHeaderRowPadding);
mHeaderRowBackgroundColor = a.getColor(R.styleable.WeekView_headerRowBackgroundColor, mHeaderRowBackgroundColor);
mDayBackgroundColor = a.getColor(R.styleable.WeekView_dayBackgroundColor, mDayBackgroundColor);
mFutureBackgroundColor = a.getColor(R.styleable.WeekView_futureBackgroundColor, mFutureBackgroundColor);
mPastBackgroundColor = a.getColor(R.styleable.WeekView_pastBackgroundColor, mPastBackgroundColor);
mFutureWeekendBackgroundColor = a.getColor(R.styleable.WeekView_futureWeekendBackgroundColor, mFutureBackgroundColor); // If not set, use the same color as in the week
mPastWeekendBackgroundColor = a.getColor(R.styleable.WeekView_pastWeekendBackgroundColor, mPastBackgroundColor);
mNowLineColor = a.getColor(R.styleable.WeekView_nowLineColor, mNowLineColor);
mNowLineThickness = a.getDimensionPixelSize(R.styleable.WeekView_nowLineThickness, mNowLineThickness);
mHourSeparatorColor = a.getColor(R.styleable.WeekView_hourSeparatorColor, mHourSeparatorColor);
mTodayBackgroundColor = a.getColor(R.styleable.WeekView_todayBackgroundColor, mTodayBackgroundColor);
mHourSeparatorHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mHourSeparatorHeight);
mTodayHeaderTextColor = a.getColor(R.styleable.WeekView_todayHeaderTextColor, mTodayHeaderTextColor);
mEventTextSize = a.getDimensionPixelSize(R.styleable.WeekView_eventTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mEventTextSize, context.getResources().getDisplayMetrics()));
mEventTextColor = a.getColor(R.styleable.WeekView_eventTextColor, mEventTextColor);
mNewEventColor = a.getColor(R.styleable.WeekView_newEventColor, mNewEventColor);
mNewEventIconDrawable = a.getDrawable(R.styleable.WeekView_newEventIconResource);
// For backward compatibility : Set "mNewEventIdentifier" if the attribute is "WeekView_newEventId" of type int
setNewEventId(a.getInt(R.styleable.WeekView_newEventId, Integer.parseInt(mNewEventIdentifier)));
mNewEventIdentifier = (a.getString(R.styleable.WeekView_newEventIdentifier) != null) ? a.getString(R.styleable.WeekView_newEventIdentifier) : mNewEventIdentifier;
mNewEventLengthInMinutes = a.getInt(R.styleable.WeekView_newEventLengthInMinutes, mNewEventLengthInMinutes);
mNewEventTimeResolutionInMinutes = a.getInt(R.styleable.WeekView_newEventTimeResolutionInMinutes, mNewEventTimeResolutionInMinutes);
mEventPadding = a.getDimensionPixelSize(R.styleable.WeekView_eventPadding, mEventPadding);
mHeaderColumnBackgroundColor = a.getColor(R.styleable.WeekView_headerColumnBackground, mHeaderColumnBackgroundColor);
mDayNameLength = a.getInteger(R.styleable.WeekView_dayNameLength, mDayNameLength);
mOverlappingEventGap = a.getDimensionPixelSize(R.styleable.WeekView_overlappingEventGap, mOverlappingEventGap);
mEventMarginVertical = a.getDimensionPixelSize(R.styleable.WeekView_eventMarginVertical, mEventMarginVertical);
mXScrollingSpeed = a.getFloat(R.styleable.WeekView_xScrollingSpeed, mXScrollingSpeed);
mEventCornerRadius = a.getDimensionPixelSize(R.styleable.WeekView_eventCornerRadius, mEventCornerRadius);
mShowDistinctPastFutureColor = a.getBoolean(R.styleable.WeekView_showDistinctPastFutureColor, mShowDistinctPastFutureColor);
mShowDistinctWeekendColor = a.getBoolean(R.styleable.WeekView_showDistinctWeekendColor, mShowDistinctWeekendColor);
mShowNowLine = a.getBoolean(R.styleable.WeekView_showNowLine, mShowNowLine);
mHorizontalFlingEnabled = a.getBoolean(R.styleable.WeekView_horizontalFlingEnabled, mHorizontalFlingEnabled);
mVerticalFlingEnabled = a.getBoolean(R.styleable.WeekView_verticalFlingEnabled, mVerticalFlingEnabled);
mAllDayEventHeight = a.getDimensionPixelSize(R.styleable.WeekView_allDayEventHeight, mAllDayEventHeight);
mZoomFocusPoint = a.getFraction(R.styleable.WeekView_zoomFocusPoint, 1, 1, mZoomFocusPoint);
mZoomFocusPointEnabled = a.getBoolean(R.styleable.WeekView_zoomFocusPointEnabled, mZoomFocusPointEnabled);
mScrollDuration = a.getInt(R.styleable.WeekView_scrollDuration, mScrollDuration);
mTimeColumnResolution = a.getInt(R.styleable.WeekView_timeColumnResolution, mTimeColumnResolution);
mAutoLimitTime = a.getBoolean(R.styleable.WeekView_autoLimitTime, mAutoLimitTime);
mMinTime = a.getInt(R.styleable.WeekView_minTime, mMinTime);
mMaxTime = a.getInt(R.styleable.WeekView_maxTime, mMaxTime);
if (a.getBoolean(R.styleable.WeekView_dropListenerEnabled, false))
this.enableDropListener();
mMinOverlappingMinutes = a.getInt(R.styleable.WeekView_minOverlappingMinutes, 0);
} finally {
a.recycle();
}
init();
}
private void init() {
resetHomeDate();
// Scrolling initialization.
mGestureDetector = new GestureDetectorCompat(mContext, mGestureListener);
mScroller = new OverScroller(mContext, new FastOutLinearInInterpolator());
mMinimumFlingVelocity = ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity();
mScaledTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
// Measure settings for time column.
mTimeTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTimeTextPaint.setTextAlign(Paint.Align.RIGHT);
mTimeTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
Rect rect = new Rect();
final String exampleTime = (mTimeColumnResolution % 60 != 0) ? "00:00 PM" : "00 PM";
mTimeTextPaint.getTextBounds(exampleTime, 0, exampleTime.length(), rect);
mTimeTextWidth = mTimeTextPaint.measureText(exampleTime);
mTimeTextHeight = rect.height();
mHeaderMarginBottom = mTimeTextHeight / 2;
initTextTimeWidth();
// Measure settings for header row.
mHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.getTextBounds(exampleTime, 0, exampleTime.length(), rect);
mHeaderTextHeight = rect.height();
mHeaderTextPaint.setTypeface(mTypeface);
// Prepare header background paint.
mHeaderBackgroundPaint = new Paint();
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
// Prepare day background color paint.
mDayBackgroundPaint = new Paint();
mDayBackgroundPaint.setColor(mDayBackgroundColor);
mFutureBackgroundPaint = new Paint();
mFutureBackgroundPaint.setColor(mFutureBackgroundColor);
mPastBackgroundPaint = new Paint();
mPastBackgroundPaint.setColor(mPastBackgroundColor);
mFutureWeekendBackgroundPaint = new Paint();
mFutureWeekendBackgroundPaint.setColor(mFutureWeekendBackgroundColor);
mPastWeekendBackgroundPaint = new Paint();
mPastWeekendBackgroundPaint.setColor(mPastWeekendBackgroundColor);
// Prepare hour separator color paint.
mHourSeparatorPaint = new Paint();
mHourSeparatorPaint.setStyle(Paint.Style.STROKE);
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
mHourSeparatorPaint.setColor(mHourSeparatorColor);
// Prepare the "now" line color paint
mNowLinePaint = new Paint();
mNowLinePaint.setStrokeWidth(mNowLineThickness);
mNowLinePaint.setColor(mNowLineColor);
// Prepare today background color paint.
mTodayBackgroundPaint = new Paint();
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
// Prepare today header text color paint.
mTodayHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTodayHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mTodayHeaderTextPaint.setTextSize(mTextSize);
mTodayHeaderTextPaint.setTypeface(mTypeface);
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
// Prepare event background color.
mEventBackgroundPaint = new Paint();
mEventBackgroundPaint.setColor(Color.rgb(174, 208, 238));
// Prepare empty event background color.
mNewEventBackgroundPaint = new Paint();
mNewEventBackgroundPaint.setColor(Color.rgb(60, 147, 217));
// Prepare header column background color.
mHeaderColumnBackgroundPaint = new Paint();
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
// Prepare event text size and color.
mEventTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
mEventTextPaint.setStyle(Paint.Style.FILL);
mEventTextPaint.setColor(mEventTextColor);
mEventTextPaint.setTextSize(mEventTextSize);
// Set default event color.
mDefaultEventColor = Color.parseColor("#9fc6e7");
// Set default empty event color.
mNewEventColor = Color.parseColor("#3c93d9");
mScaleDetector = new ScaleGestureDetector(mContext, new WeekViewGestureListener());
}
private void resetHomeDate() {
Calendar newHomeDate = today();
if (mMinDate != null && newHomeDate.before(mMinDate)) {
newHomeDate = (Calendar) mMinDate.clone();
}
if (mMaxDate != null && newHomeDate.after(mMaxDate)) {
newHomeDate = (Calendar) mMaxDate.clone();
}
if (mMaxDate != null) {
Calendar date = (Calendar) mMaxDate.clone();
date.add(Calendar.DATE, 1 - getRealNumberOfVisibleDays());
while (date.before(mMinDate)) {
date.add(Calendar.DATE, 1);
}
if (newHomeDate.after(date)) {
newHomeDate = date;
}
}
mHomeDate = newHomeDate;
}
private float getXOriginForDate(Calendar date) {
return -daysBetween(mHomeDate, date) * (mWidthPerDay + mColumnGap);
}
private int getNumberOfPeriods() {
return (int) ((mMaxTime - mMinTime) * (60.0 / mTimeColumnResolution));
}
private float getYMinLimit() {
return -(mHourHeight * (mMaxTime - mMinTime)
+ mHeaderHeight
+ mHeaderRowPadding * 2
+ mHeaderMarginBottom
+ mTimeTextHeight / 2
- getHeight());
}
private float getYMaxLimit() {
return 0;
}
private float getXMinLimit() {
if (mMaxDate == null) {
return Integer.MIN_VALUE;
} else {
Calendar date = (Calendar) mMaxDate.clone();
date.add(Calendar.DATE, 1 - getRealNumberOfVisibleDays());
while (date.before(mMinDate)) {
date.add(Calendar.DATE, 1);
}
return getXOriginForDate(date);
}
}
private float getXMaxLimit() {
if (mMinDate == null) {
return Integer.MAX_VALUE;
} else {
return getXOriginForDate(mMinDate);
}
}
// fix rotation changes
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mAreDimensionsInvalid = true;
}
/**
* Initialize time column width. Calculate value with all possible hours (supposed widest text).
*/
private void initTextTimeWidth() {
mTimeTextWidth = 0;
for (int i = 0; i < getNumberOfPeriods(); i++) {
// Measure time string and get max width.
String time = getDateTimeInterpreter().interpretTime(i, (i % 2) * 30);
if (time == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null time");
mTimeTextWidth = Math.max(mTimeTextWidth, mTimeTextPaint.measureText(time));
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the header row.
drawHeaderRowAndEvents(canvas);
// Draw the time column and all the axes/separators.
drawTimeColumnAndAxes(canvas);
}
private void calculateHeaderHeight() {
//Make sure the header is the right size (depends on AllDay events)
boolean containsAllDayEvent = false;
if (mEventRects != null && mEventRects.size() > 0) {
for (int dayNumber = 0;
dayNumber < getRealNumberOfVisibleDays();
dayNumber++) {
Calendar day = (Calendar) getFirstVisibleDay().clone();
day.add(Calendar.DATE, dayNumber);
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), day) && mEventRects.get(i).event.isAllDay()) {
containsAllDayEvent = true;
break;
}
}
if (containsAllDayEvent) {
break;
}
}
}
if (containsAllDayEvent) {
mHeaderHeight = mHeaderTextHeight + (mAllDayEventHeight + mHeaderMarginBottom);
} else {
mHeaderHeight = mHeaderTextHeight;
}
}
private void drawTimeColumnAndAxes(Canvas canvas) {
// Draw the background color for the header column.
canvas.drawRect(0, mHeaderHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), mHeaderColumnBackgroundPaint);
// Clip to paint in left column only.
canvas.clipRect(0, mHeaderHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), Region.Op.REPLACE);
for (int i = 0; i < getNumberOfPeriods(); i++) {
// If we are showing half hours (eg. 5:30am), space the times out by half the hour height
// and need to provide 30 minutes on each odd period, otherwise, minutes is always 0.
float timeSpacing;
int minutes;
int hour;
float timesPerHour = (float) 60.0 / mTimeColumnResolution;
timeSpacing = mHourHeight / timesPerHour;
hour = mMinTime + i / (int) (timesPerHour);
minutes = i % ((int) timesPerHour) * (60 / (int) timesPerHour);
// Calculate the top of the rectangle where the time text will go
float top = mHeaderHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + timeSpacing * i + mHeaderMarginBottom;
// Get the time to be displayed, as a String.
String time = getDateTimeInterpreter().interpretTime(hour, minutes);
// Draw the text if its y position is not outside of the visible area. The pivot point of the text is the point at the bottom-right corner.
if (time == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null time");
if (top < getHeight())
canvas.drawText(time, mTimeTextWidth + mHeaderColumnPadding, top + mTimeTextHeight, mTimeTextPaint);
}
}
private void drawHeaderRowAndEvents(Canvas canvas) {
// Calculate the available width for each day.
mHeaderColumnWidth = mTimeTextWidth + mHeaderColumnPadding * 2;
mWidthPerDay = getWidth() - mHeaderColumnWidth - mColumnGap * (getRealNumberOfVisibleDays() - 1);
mWidthPerDay = mWidthPerDay / getRealNumberOfVisibleDays();
calculateHeaderHeight(); //Make sure the header is the right size (depends on AllDay events)
Calendar today = today();
if (mAreDimensionsInvalid) {
mEffectiveMinHourHeight = Math.max(mMinHourHeight, (int) ((getHeight() - mHeaderHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom) / (mMaxTime - mMinTime)));
mAreDimensionsInvalid = false;
if (mScrollToDay != null)
goToDate(mScrollToDay);
mAreDimensionsInvalid = false;
if (mScrollToHour >= 0)
goToHour(mScrollToHour);
mScrollToDay = null;
mScrollToHour = -1;
mAreDimensionsInvalid = false;
}
if (mIsFirstDraw) {
mIsFirstDraw = false;
// If the week view is being drawn for the first time, then consider the first day of the week.
if (getRealNumberOfVisibleDays() >= 7 && mHomeDate.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek && mShowFirstDayOfWeekFirst) {
int difference = (mHomeDate.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek);
mCurrentOrigin.x += (mWidthPerDay + mColumnGap) * difference;
}
setLimitTime(mMinTime, mMaxTime);
}
// Calculate the new height due to the zooming.
if (mNewHourHeight > 0) {
if (mNewHourHeight < mEffectiveMinHourHeight)
mNewHourHeight = mEffectiveMinHourHeight;
else if (mNewHourHeight > mMaxHourHeight)
mNewHourHeight = mMaxHourHeight;
mHourHeight = mNewHourHeight;
mNewHourHeight = -1;
}
// If the new mCurrentOrigin.y is invalid, make it valid.
if (mCurrentOrigin.y < getHeight() - mHourHeight * (mMaxTime - mMinTime) - mHeaderHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom - mTimeTextHeight / 2)
mCurrentOrigin.y = getHeight() - mHourHeight * (mMaxTime - mMinTime) - mHeaderHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom - mTimeTextHeight / 2;
// Don't put an "else if" because it will trigger a glitch when completely zoomed out and
// scrolling vertically.
if (mCurrentOrigin.y > 0) {
mCurrentOrigin.y = 0;
}
int leftDaysWithGaps = getLeftDaysWithGaps();
// Consider scroll offset.
float startFromPixel = getXStartPixel();
float startPixel = startFromPixel;
// Prepare to iterate for each day.
Calendar day = (Calendar) today.clone();
day.add(Calendar.HOUR_OF_DAY, 6);
// Prepare to iterate for each hour to draw the hour lines.
int lineCount = (int) ((getHeight() - mHeaderHeight - mHeaderRowPadding * 2 -
mHeaderMarginBottom) / mHourHeight) + 1;
lineCount = (lineCount) * (getRealNumberOfVisibleDays() + 1);
float[] hourLines = new float[lineCount * 4];
// Clear the cache for event rectangles.
if (mEventRects != null) {
for (EventRect eventRect : mEventRects) {
eventRect.rectF = null;
}
}
// Clip to paint events only.
canvas.clipRect(mHeaderColumnWidth, mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight / 2, getWidth(), getHeight(), Region.Op.REPLACE);
// Iterate through each day.
Calendar oldFirstVisibleDay = mFirstVisibleDay;
mFirstVisibleDay = (Calendar) mHomeDate.clone();
mFirstVisibleDay.add(Calendar.DATE, -(Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap))));
if (!mFirstVisibleDay.equals(oldFirstVisibleDay) && mScrollListener != null) {
mScrollListener.onFirstVisibleDayChanged(mFirstVisibleDay, oldFirstVisibleDay);
}
if (mAutoLimitTime) {
List<Calendar> days = new ArrayList<>();
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + getRealNumberOfVisibleDays();
dayNumber++) {
day = (Calendar) mHomeDate.clone();
day.add(Calendar.DATE, dayNumber - 1);
days.add(day);
}
limitEventTime(days);
}
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + getRealNumberOfVisibleDays() + 1;
dayNumber++) {
// Check if the day is today.
day = (Calendar) mHomeDate.clone();
mLastVisibleDay = (Calendar) day.clone();
day.add(Calendar.DATE, dayNumber - 1);
mLastVisibleDay.add(Calendar.DATE, dayNumber - 2);
boolean isToday = isSameDay(day, today);
// Don't draw days which are outside requested range
if (!dateIsValid(day)) {
continue;
}
// Get more events if necessary. We want to store the events 3 months beforehand. Get
// events only when it is the first iteration of the loop.
if (mEventRects == null || mRefreshEvents ||
(dayNumber == leftDaysWithGaps + 1 && mFetchedPeriod != (int) mWeekViewLoader.toWeekViewPeriodIndex(day) &&
Math.abs(mFetchedPeriod - mWeekViewLoader.toWeekViewPeriodIndex(day)) > 0.5)) {
getMoreEvents(day);
mRefreshEvents = false;
}
// Draw background color for each day.
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start > 0) {
if (mShowDistinctPastFutureColor) {
boolean isWeekend = day.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || day.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
Paint pastPaint = isWeekend && mShowDistinctWeekendColor ? mPastWeekendBackgroundPaint : mPastBackgroundPaint;
Paint futurePaint = isWeekend && mShowDistinctWeekendColor ? mFutureWeekendBackgroundPaint : mFutureBackgroundPaint;
float startY = mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom + mCurrentOrigin.y;
if (isToday) {
Calendar now = Calendar.getInstance();
float beforeNow = (now.get(Calendar.HOUR_OF_DAY) - mMinTime + now.get(Calendar.MINUTE) / 60.0f) * mHourHeight;
canvas.drawRect(start, startY, startPixel + mWidthPerDay, startY + beforeNow, pastPaint);
canvas.drawRect(start, startY + beforeNow, startPixel + mWidthPerDay, getHeight(), futurePaint);
} else if (day.before(today)) {
canvas.drawRect(start, startY, startPixel + mWidthPerDay, getHeight(), pastPaint);
} else {
canvas.drawRect(start, startY, startPixel + mWidthPerDay, getHeight(), futurePaint);
}
} else {
canvas.drawRect(start, mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom, startPixel + mWidthPerDay, getHeight(), isToday ? mTodayBackgroundPaint : mDayBackgroundPaint);
}
}
// Prepare the separator lines for hours.
int i = 0;
for (int hourNumber = mMinTime; hourNumber < mMaxTime; hourNumber++) {
float top = mHeaderHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * (hourNumber - mMinTime) + mTimeTextHeight / 2 + mHeaderMarginBottom;
if (top > mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom - mHourSeparatorHeight && top < getHeight() && startPixel + mWidthPerDay - start > 0) {
hourLines[i * 4] = start;
hourLines[i * 4 + 1] = top;
hourLines[i * 4 + 2] = startPixel + mWidthPerDay;
hourLines[i * 4 + 3] = top;
i++;
}
}
// Draw the lines for hours.
canvas.drawLines(hourLines, mHourSeparatorPaint);
// Draw the events.
drawEvents(day, startPixel, canvas);
// Draw the line at the current time.
if (mShowNowLine && isToday) {
float startY = mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom + mCurrentOrigin.y;
Calendar now = Calendar.getInstance();
float beforeNow = (now.get(Calendar.HOUR_OF_DAY) - mMinTime + now.get(Calendar.MINUTE) / 60.0f) * mHourHeight;
float top = startY + beforeNow;
canvas.drawLine(start, top, startPixel + mWidthPerDay, top, mNowLinePaint);
}
// In the next iteration, start from the next day.
startPixel += mWidthPerDay + mColumnGap;
}
// Hide everything in the first cell (top left corner).
canvas.clipRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderHeight + mHeaderRowPadding * 2, Region.Op.REPLACE);
canvas.drawRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Clip to paint header row only.
canvas.clipRect(mHeaderColumnWidth, 0, getWidth(), mHeaderHeight + mHeaderRowPadding * 2, Region.Op.REPLACE);
// Draw the header background.
canvas.drawRect(0, 0, getWidth(), mHeaderHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row texts.
startPixel = startFromPixel;
for (int dayNumber = leftDaysWithGaps + 1; dayNumber <= leftDaysWithGaps + getRealNumberOfVisibleDays() + 1; dayNumber++) {
// Check if the day is today.
day = (Calendar) mHomeDate.clone();
day.add(Calendar.DATE, dayNumber - 1);
boolean isToday = isSameDay(day, today);
// Don't draw days which are outside requested range
if (!dateIsValid(day))
continue;
// Draw the day labels.
String dayLabel = getDateTimeInterpreter().interpretDate(day);
if (dayLabel == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null date");
canvas.drawText(dayLabel, startPixel + mWidthPerDay / 2, mHeaderTextHeight + mHeaderRowPadding, isToday ? mTodayHeaderTextPaint : mHeaderTextPaint);
drawAllDayEvents(day, startPixel, canvas);
startPixel += mWidthPerDay + mColumnGap;
}
}
/**
* Get the time and date where the user clicked on.
*
* @param x The x position of the touch event.
* @param y The y position of the touch event.
* @return The time and date at the clicked position.
*/
private Calendar getTimeFromPoint(float x, float y) {
int leftDaysWithGaps = getLeftDaysWithGaps();
float startPixel = getXStartPixel();
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + getRealNumberOfVisibleDays() + 1;
dayNumber++) {
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start > 0 && x > start && x < startPixel + mWidthPerDay) {
Calendar day = (Calendar) mHomeDate.clone();
day.add(Calendar.DATE, dayNumber - 1);
float pixelsFromZero = y - mCurrentOrigin.y - mHeaderHeight
- mHeaderRowPadding * 2 - mTimeTextHeight / 2 - mHeaderMarginBottom;
int hour = (int) (pixelsFromZero / mHourHeight);
int minute = (int) (60 * (pixelsFromZero - hour * mHourHeight) / mHourHeight);
day.add(Calendar.HOUR_OF_DAY, hour + mMinTime);
day.set(Calendar.MINUTE, minute);
return day;
}
startPixel += mWidthPerDay + mColumnGap;
}
return null;
}
/**
* limit current time of event by update mMinTime & mMaxTime
* find smallest of start time & latest of end time
*/
private void limitEventTime(List<Calendar> dates) {
if (mEventRects != null && mEventRects.size() > 0) {
Calendar startTime = null;
Calendar endTime = null;
for (EventRect eventRect : mEventRects) {
for (Calendar date : dates) {
if (isSameDay(eventRect.event.getStartTime(), date) && !eventRect.event.isAllDay()) {
if (startTime == null || getPassedMinutesInDay(startTime) > getPassedMinutesInDay(eventRect.event.getStartTime())) {
startTime = eventRect.event.getStartTime();
}
if (endTime == null || getPassedMinutesInDay(endTime) < getPassedMinutesInDay(eventRect.event.getEndTime())) {
endTime = eventRect.event.getEndTime();
}
}
}
}
if (startTime != null && endTime != null && startTime.before(endTime)) {
setLimitTime(Math.max(0, startTime.get(Calendar.HOUR_OF_DAY)),
Math.min(24, endTime.get(Calendar.HOUR_OF_DAY) + 1));
return;
}
}
}
private int getMinHourOffset(){
return mHourHeight * mMinTime;
}
private float getEventsTop(){
// Calculate top.
return mCurrentOrigin.y + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight / 2 + mEventMarginVertical - getMinHourOffset();
}
private int getLeftDaysWithGaps(){
return (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
}
private float getXStartPixel(){
return mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * getLeftDaysWithGaps() +
mHeaderColumnWidth;
}
/**
* Draw all the events of a particular day.
*
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date) && !mEventRects.get(i).event.isAllDay()) {
float top = mHourHeight * mEventRects.get(i).top / 60 + getEventsTop();
float bottom = mHourHeight * mEventRects.get(i).bottom / 60 + getEventsTop();
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
// Draw the event and the event name on top of it.
if (left < right &&
left < getWidth() &&
top < getHeight() &&
right > mHeaderColumnWidth &&
bottom > mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom
) {
mEventRects.get(i).rectF = new RectF(left, top, right, bottom);
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
mEventBackgroundPaint.setShader(mEventRects.get(i).event.getShader());
canvas.drawRoundRect(mEventRects.get(i).rectF, mEventCornerRadius, mEventCornerRadius, mEventBackgroundPaint);
float topToUse = top;
if (mEventRects.get(i).event.getStartTime().get(Calendar.HOUR_OF_DAY) < mMinTime)
topToUse = mHourHeight * getPassedMinutesInDay(mMinTime, 0) / 60 + getEventsTop();
if (!mNewEventIdentifier.equals(mEventRects.get(i).event.getIdentifier()))
drawEventTitle(mEventRects.get(i).event, mEventRects.get(i).rectF, canvas, topToUse, left);
else
drawEmptyImage(mEventRects.get(i).event, mEventRects.get(i).rectF, canvas, topToUse, left);
} else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw all the Allday-events of a particular day.
*
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawAllDayEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date) && mEventRects.get(i).event.isAllDay()) {
// Calculate top.
float top = mHeaderRowPadding * 2 + mHeaderMarginBottom + +mTimeTextHeight / 2 + mEventMarginVertical;
// Calculate bottom.
float bottom = top + mEventRects.get(i).bottom;
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
// Draw the event and the event name on top of it.
if (left < right &&
left < getWidth() &&
top < getHeight() &&
right > mHeaderColumnWidth &&
bottom > 0
) {
mEventRects.get(i).rectF = new RectF(left, top, right, bottom);
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
mEventBackgroundPaint.setShader(mEventRects.get(i).event.getShader());
canvas.drawRoundRect(mEventRects.get(i).rectF, mEventCornerRadius, mEventCornerRadius, mEventBackgroundPaint);
drawEventTitle(mEventRects.get(i).event, mEventRects.get(i).rectF, canvas, top, left);
} else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw the name of the event on top of the event rectangle.
*
* @param event The event of which the title (and location) should be drawn.
* @param rect The rectangle on which the text is to be drawn.
* @param canvas The canvas to draw upon.
* @param originalTop The original top position of the rectangle. The rectangle may have some of its portion outside of the visible area.
* @param originalLeft The original left position of the rectangle. The rectangle may have some of its portion outside of the visible area.
*/
private void drawEventTitle(WeekViewEvent event, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
if (rect.bottom - rect.top - mEventPadding * 2 < 0) return;
// Prepare the name of the event.
SpannableStringBuilder bob = new SpannableStringBuilder();
if (!TextUtils.isEmpty(event.getName())) {
bob.append(event.getName());
bob.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, bob.length(), 0);
}
// Prepare the location of the event.
if (!TextUtils.isEmpty(event.getLocation())) {
if (bob.length() > 0)
bob.append(' ');
bob.append(event.getLocation());
}
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int availableWidth = (int) (rect.right - originalLeft - mEventPadding * 2);
// Get text color if necessary
if (textColorPicker != null) {
mEventTextPaint.setColor(textColorPicker.getTextColor(event));
}
// Get text dimensions.
StaticLayout textLayout = new StaticLayout(bob, mEventTextPaint, availableWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (textLayout.getLineCount() > 0) {
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (availableHeight >= lineHeight) {
// Calculate available number of line counts.
int availableLineCount = availableHeight / lineHeight;
do {
// Ellipsize text to fit into event rect.
if (!mNewEventIdentifier.equals(event.getIdentifier()))
textLayout = new StaticLayout(TextUtils.ellipsize(bob, mEventTextPaint, availableLineCount * availableWidth, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Reduce line count.
availableLineCount
// Repeat until text is short enough.
} while (textLayout.getHeight() > availableHeight);
// Draw text.
canvas.save();
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding);
textLayout.draw(canvas);
canvas.restore();
}
}
}
/**
* Draw the text on top of the rectangle in the empty event.
*/
private void drawEmptyImage(WeekViewEvent event, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
int size = Math.max(1, (int) Math.floor(Math.min(0.8 * rect.height(), 0.8 * rect.width())));
if (mNewEventIconDrawable == null)
mNewEventIconDrawable = getResources().getDrawable(android.R.drawable.ic_input_add);
Bitmap icon = ((BitmapDrawable) mNewEventIconDrawable).getBitmap();
icon = Bitmap.createScaledBitmap(icon, size, size, false);
canvas.drawBitmap(icon, originalLeft + (rect.width() - icon.getWidth()) / 2, originalTop + (rect.height() - icon.getHeight()) / 2, new Paint());
}
/**
* A class to hold reference to the events and their visual representation. An EventRect is
* actually the rectangle that is drawn on the calendar for a given event. There may be more
* than one rectangle for a single event (an event that expands more than one day). In that
* case two instances of the EventRect will be used for a single event. The given event will be
* stored in "originalEvent". But the event that corresponds to rectangle the rectangle
* instance will be stored in "event".
*/
private class EventRect {
public WeekViewEvent event;
public WeekViewEvent originalEvent;
public RectF rectF;
public float left;
public float width;
public float top;
public float bottom;
/**
* Create a new instance of event rect. An EventRect is actually the rectangle that is drawn
* on the calendar for a given event. There may be more than one rectangle for a single
* event (an event that expands more than one day). In that case two instances of the
* EventRect will be used for a single event. The given event will be stored in
* "originalEvent". But the event that corresponds to rectangle the rectangle instance will
* be stored in "event".
*
* @param event Represents the event which this instance of rectangle represents.
* @param originalEvent The original event that was passed by the user.
* @param rectF The rectangle.
*/
public EventRect(WeekViewEvent event, WeekViewEvent originalEvent, RectF rectF) {
this.event = event;
this.rectF = rectF;
this.originalEvent = originalEvent;
}
}
/**
* Gets more events of one/more month(s) if necessary. This method is called when the user is
* scrolling the week view. The week view stores the events of three months: the visible month,
* the previous month, the next month.
*
* @param day The day where the user is currently is.
*/
private void getMoreEvents(Calendar day) {
// Get more events if the month is changed.
if (mEventRects == null)
mEventRects = new ArrayList<>();
if (mEvents == null)
mEvents = new ArrayList<>();
if (mWeekViewLoader == null && !isInEditMode())
throw new IllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if (mRefreshEvents) {
this.clearEvents();
mFetchedPeriod = -1;
}
if (mWeekViewLoader != null) {
int periodToFetch = (int) mWeekViewLoader.toWeekViewPeriodIndex(day);
if (!isInEditMode() && (mFetchedPeriod < 0 || mFetchedPeriod != periodToFetch || mRefreshEvents)) {
List<? extends WeekViewEvent> newEvents = mWeekViewLoader.onLoad(periodToFetch);
// Clear events.
this.clearEvents();
cacheAndSortEvents(newEvents);
calculateHeaderHeight();
mFetchedPeriod = periodToFetch;
}
}
// Prepare to calculate positions of each events.
List<EventRect> tempEvents = mEventRects;
mEventRects = new ArrayList<>();
// Iterate through each day with events to calculate the position of the events.
while (tempEvents.size() > 0) {
ArrayList<EventRect> eventRects = new ArrayList<>(tempEvents.size());
// Get first event for a day.
EventRect eventRect1 = tempEvents.remove(0);
eventRects.add(eventRect1);
int i = 0;
while (i < tempEvents.size()) {
// Collect all other events for same day.
EventRect eventRect2 = tempEvents.get(i);
if (isSameDay(eventRect1.event.getStartTime(), eventRect2.event.getStartTime())) {
tempEvents.remove(i);
eventRects.add(eventRect2);
} else {
i++;
}
}
computePositionOfEvents(eventRects);
}
}
private void clearEvents() {
mEventRects.clear();
mEvents.clear();
}
/**
* Cache the event for smooth scrolling functionality.
*
* @param event The event to cache.
*/
private void cacheEvent(WeekViewEvent event) {
if (event.getStartTime().compareTo(event.getEndTime()) >= 0)
return;
List<WeekViewEvent> splitedEvents = event.splitWeekViewEvents();
for (WeekViewEvent splitedEvent : splitedEvents) {
mEventRects.add(new EventRect(splitedEvent, event, null));
}
mEvents.add(event);
}
/**
* Cache and sort events.
*
* @param events The events to be cached and sorted.
*/
private void cacheAndSortEvents(List<? extends WeekViewEvent> events) {
for (WeekViewEvent event : events) {
cacheEvent(event);
}
sortEventRects(mEventRects);
}
/**
* Sorts the events in ascending order.
*
* @param eventRects The events to be sorted.
*/
private void sortEventRects(List<EventRect> eventRects) {
Collections.sort(eventRects, new Comparator<EventRect>() {
@Override
public int compare(EventRect left, EventRect right) {
long start1 = left.event.getStartTime().getTimeInMillis();
long start2 = right.event.getStartTime().getTimeInMillis();
int comparator = start1 > start2 ? 1 : (start1 < start2 ? -1 : 0);
if (comparator == 0) {
long end1 = left.event.getEndTime().getTimeInMillis();
long end2 = right.event.getEndTime().getTimeInMillis();
comparator = end1 > end2 ? 1 : (end1 < end2 ? -1 : 0);
}
return comparator;
}
});
}
/**
* Calculates the left and right positions of each events. This comes handy specially if events
* are overlapping.
*
* @param eventRects The events along with their wrapper class.
*/
private void computePositionOfEvents(List<EventRect> eventRects) {
// Make "collision groups" for all events that collide with others.
List<List<EventRect>> collisionGroups = new ArrayList<List<EventRect>>();
for (EventRect eventRect : eventRects) {
boolean isPlaced = false;
outerLoop:
for (List<EventRect> collisionGroup : collisionGroups) {
for (EventRect groupEvent : collisionGroup) {
if (isEventsCollide(groupEvent.event, eventRect.event) && groupEvent.event.isAllDay() == eventRect.event.isAllDay()) {
collisionGroup.add(eventRect);
isPlaced = true;
break outerLoop;
}
}
}
if (!isPlaced) {
List<EventRect> newGroup = new ArrayList<EventRect>();
newGroup.add(eventRect);
collisionGroups.add(newGroup);
}
}
for (List<EventRect> collisionGroup : collisionGroups) {
expandEventsToMaxWidth(collisionGroup);
}
}
/**
* Expands all the events to maximum possible width. The events will try to occupy maximum
* space available horizontally.
*
* @param collisionGroup The group of events which overlap with each other.
*/
private void expandEventsToMaxWidth(List<EventRect> collisionGroup) {
// Expand the events to maximum possible width.
List<List<EventRect>> columns = new ArrayList<List<EventRect>>();
columns.add(new ArrayList<EventRect>());
for (EventRect eventRect : collisionGroup) {
boolean isPlaced = false;
for (List<EventRect> column : columns) {
if (column.size() == 0) {
column.add(eventRect);
isPlaced = true;
} else if (!isEventsCollide(eventRect.event, column.get(column.size() - 1).event)) {
column.add(eventRect);
isPlaced = true;
break;
}
}
if (!isPlaced) {
List<EventRect> newColumn = new ArrayList<EventRect>();
newColumn.add(eventRect);
columns.add(newColumn);
}
}
// Calculate left and right position for all the events.
// Get the maxRowCount by looking in all columns.
int maxRowCount = 0;
for (List<EventRect> column : columns) {
maxRowCount = Math.max(maxRowCount, column.size());
}
for (int i = 0; i < maxRowCount; i++) {
// Set the left and right values of the event.
float j = 0;
for (List<EventRect> column : columns) {
if (column.size() >= i + 1) {
EventRect eventRect = column.get(i);
eventRect.width = 1f / columns.size();
eventRect.left = j / columns.size();
if (!eventRect.event.isAllDay()) {
eventRect.top = getPassedMinutesInDay(eventRect.event.getStartTime());
eventRect.bottom = getPassedMinutesInDay(eventRect.event.getEndTime());
} else {
eventRect.top = 0;
eventRect.bottom = mAllDayEventHeight;
}
mEventRects.add(eventRect);
}
j++;
}
}
}
/**
* Checks if two events overlap.
*
* @param event1 The first event.
* @param event2 The second event.
* @return true if the events overlap.
*/
private boolean isEventsCollide(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long end1 = event1.getEndTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
long minOverlappingMillis = mMinOverlappingMinutes * 60 * 1000;
return !((start1 + minOverlappingMillis >= end2) || (end1 <= start2 + minOverlappingMillis));
}
/**
* Checks if time1 occurs after (or at the same time) time2.
*
* @param time1 The time to check.
* @param time2 The time to check against.
* @return true if time1 and time2 are equal or if time1 is after time2. Otherwise false.
*/
private boolean isTimeAfterOrEquals(Calendar time1, Calendar time2) {
return !(time1 == null || time2 == null) && time1.getTimeInMillis() >= time2.getTimeInMillis();
}
@Override
public void invalidate() {
super.invalidate();
mAreDimensionsInvalid = true;
}
// Functions related to setting and getting the properties.
public void setOnEventClickListener(EventClickListener listener) {
this.mEventClickListener = listener;
}
public void setDropListener(DropListener dropListener) {
this.mDropListener = dropListener;
}
public EventClickListener getEventClickListener() {
return mEventClickListener;
}
public
@Nullable
MonthLoader.MonthChangeListener getMonthChangeListener() {
if (mWeekViewLoader instanceof MonthLoader)
return ((MonthLoader) mWeekViewLoader).getOnMonthChangeListener();
return null;
}
public void setMonthChangeListener(MonthLoader.MonthChangeListener monthChangeListener) {
this.mWeekViewLoader = new MonthLoader(monthChangeListener);
}
/**
* Get event loader in the week view. Event loaders define the interval after which the events
* are loaded in week view. For a MonthLoader events are loaded for every month. You can define
* your custom event loader by extending WeekViewLoader.
*
* @return The event loader.
*/
public WeekViewLoader getWeekViewLoader() {
return mWeekViewLoader;
}
/**
* Set event loader in the week view. For example, a MonthLoader. Event loaders define the
* interval after which the events are loaded in week view. For a MonthLoader events are loaded
* for every month. You can define your custom event loader by extending WeekViewLoader.
*
* @param loader The event loader.
*/
public void setWeekViewLoader(WeekViewLoader loader) {
this.mWeekViewLoader = loader;
}
public EventLongPressListener getEventLongPressListener() {
return mEventLongPressListener;
}
public void setEventLongPressListener(EventLongPressListener eventLongPressListener) {
this.mEventLongPressListener = eventLongPressListener;
}
public void setEmptyViewClickListener(EmptyViewClickListener emptyViewClickListener) {
this.mEmptyViewClickListener = emptyViewClickListener;
}
public EmptyViewClickListener getEmptyViewClickListener() {
return mEmptyViewClickListener;
}
public void setEmptyViewLongPressListener(EmptyViewLongPressListener emptyViewLongPressListener) {
this.mEmptyViewLongPressListener = emptyViewLongPressListener;
}
public EmptyViewLongPressListener getEmptyViewLongPressListener() {
return mEmptyViewLongPressListener;
}
public void setScrollListener(ScrollListener scrolledListener) {
this.mScrollListener = scrolledListener;
}
public ScrollListener getScrollListener() {
return mScrollListener;
}
public void setTimeColumnResolution(int resolution) {
mTimeColumnResolution = resolution;
}
public int getTimeColumnResolution() {
return mTimeColumnResolution;
}
public void setAddEventClickListener(AddEventClickListener addEventClickListener) {
this.mAddEventClickListener = addEventClickListener;
}
public AddEventClickListener getAddEventClickListener() {
return mAddEventClickListener;
}
/**
* Get the interpreter which provides the text to show in the header column and the header row.
*
* @return The date, time interpreter.
*/
public DateTimeInterpreter getDateTimeInterpreter() {
if (mDateTimeInterpreter == null) {
mDateTimeInterpreter = new DateTimeInterpreter() {
@Override
public String interpretDate(Calendar date) {
try {
SimpleDateFormat sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE M/dd", Locale.getDefault()) : new SimpleDateFormat("EEE M/dd", Locale.getDefault());
return sdf.format(date.getTime()).toUpperCase();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
@Override
public String interpretTime(int hour, int minutes) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minutes);
try {
SimpleDateFormat sdf;
if (DateFormat.is24HourFormat(getContext())) {
sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
} else {
if ((mTimeColumnResolution % 60 != 0)) {
sdf = new SimpleDateFormat("hh:mm a", Locale.getDefault());
} else {
sdf = new SimpleDateFormat("hh a", Locale.getDefault());
}
}
return sdf.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
};
}
return mDateTimeInterpreter;
}
/**
* Set the interpreter which provides the text to show in the header column and the header row.
*
* @param dateTimeInterpreter The date, time interpreter.
*/
public void setDateTimeInterpreter(DateTimeInterpreter dateTimeInterpreter) {
this.mDateTimeInterpreter = dateTimeInterpreter;
// Refresh time column width.
initTextTimeWidth();
}
/**
* Get the real number of visible days
* If the amount of days between max date and min date is smaller, that value is returned
*
* @return The real number of visible days
*/
public int getRealNumberOfVisibleDays() {
if (mMinDate == null || mMaxDate == null)
return getNumberOfVisibleDays();
return Math.min(mNumberOfVisibleDays, daysBetween(mMinDate, mMaxDate) + 1);
}
/**
* Get the number of visible days
*
* @return The set number of visible days.
*/
public int getNumberOfVisibleDays() {
return mNumberOfVisibleDays;
}
/**
* Set the number of visible days in a week.
*
* @param numberOfVisibleDays The number of visible days in a week.
*/
public void setNumberOfVisibleDays(int numberOfVisibleDays) {
this.mNumberOfVisibleDays = numberOfVisibleDays;
resetHomeDate();
mCurrentOrigin.x = 0;
mCurrentOrigin.y = 0;
invalidate();
}
public int getHourHeight() {
return mHourHeight;
}
public void setHourHeight(int hourHeight) {
mNewHourHeight = hourHeight;
invalidate();
}
public int getColumnGap() {
return mColumnGap;
}
public void setColumnGap(int columnGap) {
mColumnGap = columnGap;
invalidate();
}
public int getFirstDayOfWeek() {
return mFirstDayOfWeek;
}
/**
* Set the first day of the week. First day of the week is used only when the week view is first
* drawn. It does not of any effect after user starts scrolling horizontally.
* <p>
* <b>Note:</b> This method will only work if the week view is set to display more than 6 days at
* once.
* </p>
*
* @param firstDayOfWeek The supported values are {@link java.util.Calendar#SUNDAY},
* {@link java.util.Calendar#MONDAY}, {@link java.util.Calendar#TUESDAY},
* {@link java.util.Calendar#WEDNESDAY}, {@link java.util.Calendar#THURSDAY},
* {@link java.util.Calendar#FRIDAY}.
*/
public void setFirstDayOfWeek(int firstDayOfWeek) {
mFirstDayOfWeek = firstDayOfWeek;
invalidate();
}
public boolean isShowFirstDayOfWeekFirst() {
return mShowFirstDayOfWeekFirst;
}
public void setShowFirstDayOfWeekFirst(boolean show) {
mShowFirstDayOfWeekFirst = show;
}
public int getTextSize() {
return mTextSize;
}
public void setTextSize(int textSize) {
mTextSize = textSize;
mTodayHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setTextSize(mTextSize);
invalidate();
}
public int getHeaderColumnPadding() {
return mHeaderColumnPadding;
}
public void setHeaderColumnPadding(int headerColumnPadding) {
mHeaderColumnPadding = headerColumnPadding;
invalidate();
}
public int getHeaderColumnTextColor() {
return mHeaderColumnTextColor;
}
public void setHeaderColumnTextColor(int headerColumnTextColor) {
mHeaderColumnTextColor = headerColumnTextColor;
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
invalidate();
}
public void setTypeface(Typeface typeface) {
if (typeface != null) {
mEventTextPaint.setTypeface(typeface);
mTodayHeaderTextPaint.setTypeface(typeface);
mTimeTextPaint.setTypeface(typeface);
mTypeface = typeface;
init();
}
}
public int getHeaderRowPadding() {
return mHeaderRowPadding;
}
public void setHeaderRowPadding(int headerRowPadding) {
mHeaderRowPadding = headerRowPadding;
invalidate();
}
public int getHeaderRowBackgroundColor() {
return mHeaderRowBackgroundColor;
}
public void setHeaderRowBackgroundColor(int headerRowBackgroundColor) {
mHeaderRowBackgroundColor = headerRowBackgroundColor;
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
invalidate();
}
public int getDayBackgroundColor() {
return mDayBackgroundColor;
}
public void setDayBackgroundColor(int dayBackgroundColor) {
mDayBackgroundColor = dayBackgroundColor;
mDayBackgroundPaint.setColor(mDayBackgroundColor);
invalidate();
}
public int getHourSeparatorColor() {
return mHourSeparatorColor;
}
public void setHourSeparatorColor(int hourSeparatorColor) {
mHourSeparatorColor = hourSeparatorColor;
mHourSeparatorPaint.setColor(mHourSeparatorColor);
invalidate();
}
public int getTodayBackgroundColor() {
return mTodayBackgroundColor;
}
public void setTodayBackgroundColor(int todayBackgroundColor) {
mTodayBackgroundColor = todayBackgroundColor;
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
invalidate();
}
public int getHourSeparatorHeight() {
return mHourSeparatorHeight;
}
public void setHourSeparatorHeight(int hourSeparatorHeight) {
mHourSeparatorHeight = hourSeparatorHeight;
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
invalidate();
}
public int getTodayHeaderTextColor() {
return mTodayHeaderTextColor;
}
public void setTodayHeaderTextColor(int todayHeaderTextColor) {
mTodayHeaderTextColor = todayHeaderTextColor;
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
invalidate();
}
public int getEventTextSize() {
return mEventTextSize;
}
public void setEventTextSize(int eventTextSize) {
mEventTextSize = eventTextSize;
mEventTextPaint.setTextSize(mEventTextSize);
invalidate();
}
public int getEventTextColor() {
return mEventTextColor;
}
public void setEventTextColor(int eventTextColor) {
mEventTextColor = eventTextColor;
mEventTextPaint.setColor(mEventTextColor);
invalidate();
}
public void setTextColorPicker(TextColorPicker textColorPicker) {
this.textColorPicker = textColorPicker;
}
public TextColorPicker getTextColorPicker() {
return textColorPicker;
}
public int getEventPadding() {
return mEventPadding;
}
public void setEventPadding(int eventPadding) {
mEventPadding = eventPadding;
invalidate();
}
public int getHeaderColumnBackgroundColor() {
return mHeaderColumnBackgroundColor;
}
public void setHeaderColumnBackgroundColor(int headerColumnBackgroundColor) {
mHeaderColumnBackgroundColor = headerColumnBackgroundColor;
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
invalidate();
}
public int getDefaultEventColor() {
return mDefaultEventColor;
}
public void setDefaultEventColor(int defaultEventColor) {
mDefaultEventColor = defaultEventColor;
invalidate();
}
public int getNewEventColor() {
return mNewEventColor;
}
public void setNewEventColor(int defaultNewEventColor) {
mNewEventColor = defaultNewEventColor;
invalidate();
}
public String getNewEventIdentifier() {
return mNewEventIdentifier;
}
@Deprecated
public int getNewEventId() {
return Integer.parseInt(mNewEventIdentifier);
}
public void setNewEventIdentifier(String newEventId) {
this.mNewEventIdentifier = newEventId;
}
@Deprecated
public void setNewEventId(int newEventId) {
this.mNewEventIdentifier = String.valueOf(newEventId);
}
public int getNewEventLengthInMinutes() {
return mNewEventLengthInMinutes;
}
public void setNewEventLengthInMinutes(int newEventLengthInMinutes) {
this.mNewEventLengthInMinutes = newEventLengthInMinutes;
}
public int getNewEventTimeResolutionInMinutes() {
return mNewEventTimeResolutionInMinutes;
}
public void setNewEventTimeResolutionInMinutes(int newEventTimeResolutionInMinutes) {
this.mNewEventTimeResolutionInMinutes = newEventTimeResolutionInMinutes;
}
/**
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} and
* {@link #getDateTimeInterpreter()} instead.
*
* @return Either long or short day name is being used.
*/
@Deprecated
public int getDayNameLength() {
return mDayNameLength;
}
/**
* Set the length of the day name displayed in the header row. Example of short day names is
* 'M' for 'Monday' and example of long day names is 'Mon' for 'Monday'.
* <p>
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} instead.
* </p>
*
* @param length Supported values are {@link com.alamkanak.weekview.WeekView#LENGTH_SHORT} and
* {@link com.alamkanak.weekview.WeekView#LENGTH_LONG}.
*/
@Deprecated
public void setDayNameLength(int length) {
if (length != LENGTH_LONG && length != LENGTH_SHORT) {
throw new IllegalArgumentException("length parameter must be either LENGTH_LONG or LENGTH_SHORT");
}
this.mDayNameLength = length;
}
public int getOverlappingEventGap() {
return mOverlappingEventGap;
}
/**
* Set the gap between overlapping events.
*
* @param overlappingEventGap The gap between overlapping events.
*/
public void setOverlappingEventGap(int overlappingEventGap) {
this.mOverlappingEventGap = overlappingEventGap;
invalidate();
}
public int getEventCornerRadius() {
return mEventCornerRadius;
}
/**
* Set corner radius for event rect.
*
* @param eventCornerRadius the radius in px.
*/
public void setEventCornerRadius(int eventCornerRadius) {
mEventCornerRadius = eventCornerRadius;
}
public int getEventMarginVertical() {
return mEventMarginVertical;
}
/**
* Set the top and bottom margin of the event. The event will release this margin from the top
* and bottom edge. This margin is useful for differentiation consecutive events.
*
* @param eventMarginVertical The top and bottom margin.
*/
public void setEventMarginVertical(int eventMarginVertical) {
this.mEventMarginVertical = eventMarginVertical;
invalidate();
}
/**
* Returns the first visible day in the week view.
*
* @return The first visible day in the week view.
*/
public Calendar getFirstVisibleDay() {
return mFirstVisibleDay;
}
/**
* Returns the last visible day in the week view.
*
* @return The last visible day in the week view.
*/
public Calendar getLastVisibleDay() {
return mLastVisibleDay;
}
/**
* Get the scrolling speed factor in horizontal direction.
*
* @return The speed factor in horizontal direction.
*/
public float getXScrollingSpeed() {
return mXScrollingSpeed;
}
/**
* Sets the speed for horizontal scrolling.
*
* @param xScrollingSpeed The new horizontal scrolling speed.
*/
public void setXScrollingSpeed(float xScrollingSpeed) {
this.mXScrollingSpeed = xScrollingSpeed;
}
/**
* Get the earliest day that can be displayed. Will return null if no minimum date is set.
*
* @return the earliest day that can be displayed, null if no minimum date set
*/
public Calendar getMinDate() {
return mMinDate;
}
/**
* Set the earliest day that can be displayed. This will determine the left horizontal scroll
* limit. The default value is null (allow unlimited scrolling into the past).
*
* @param minDate The new minimum date (pass null for no minimum)
*/
public void setMinDate(Calendar minDate) {
if (minDate != null) {
minDate.set(Calendar.HOUR_OF_DAY, 0);
minDate.set(Calendar.MINUTE, 0);
minDate.set(Calendar.SECOND, 0);
minDate.set(Calendar.MILLISECOND, 0);
if (mMaxDate != null && minDate.after(mMaxDate)) {
throw new IllegalArgumentException("minDate cannot be later than maxDate");
}
}
mMinDate = minDate;
resetHomeDate();
mCurrentOrigin.x = 0;
invalidate();
}
/**
* Get the latest day that can be displayed. Will return null if no maximum date is set.
*
* @return the latest day the can be displayed, null if no max date set
*/
public Calendar getMaxDate() {
return mMaxDate;
}
/**
* Set the latest day that can be displayed. This will determine the right horizontal scroll
* limit. The default value is null (allow unlimited scrolling in to the future).
*
* @param maxDate The new maximum date (pass null for no maximum)
*/
public void setMaxDate(Calendar maxDate) {
if (maxDate != null) {
maxDate.set(Calendar.HOUR_OF_DAY, 0);
maxDate.set(Calendar.MINUTE, 0);
maxDate.set(Calendar.SECOND, 0);
maxDate.set(Calendar.MILLISECOND, 0);
if (mMinDate != null && maxDate.before(mMinDate)) {
throw new IllegalArgumentException("maxDate has to be after minDate");
}
}
mMaxDate = maxDate;
resetHomeDate();
mCurrentOrigin.x = 0;
invalidate();
}
/**
* Whether weekends should have a background color different from the normal day background
* color. The weekend background colors are defined by the attributes
* `futureWeekendBackgroundColor` and `pastWeekendBackgroundColor`.
*
* @return True if weekends should have different background colors.
*/
public boolean isShowDistinctWeekendColor() {
return mShowDistinctWeekendColor;
}
/**
* Set whether weekends should have a background color different from the normal day background
* color. The weekend background colors are defined by the attributes
* `futureWeekendBackgroundColor` and `pastWeekendBackgroundColor`.
*
* @param showDistinctWeekendColor True if weekends should have different background colors.
*/
public void setShowDistinctWeekendColor(boolean showDistinctWeekendColor) {
this.mShowDistinctWeekendColor = showDistinctWeekendColor;
invalidate();
}
/**
* auto calculate limit time on events in visible days.
*/
public void setAutoLimitTime(boolean isAuto) {
this.mAutoLimitTime = isAuto;
invalidate();
}
private void recalculateHourHeight() {
int height = (int) ((getHeight() - (mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom)) / (this.mMaxTime - this.mMinTime));
if (height > mHourHeight) {
if (height > mMaxHourHeight)
mMaxHourHeight = height;
mNewHourHeight = height;
}
}
/**
* Set visible time span.
*
* @param startHour limit time display on top (between 0~24)
* @param endHour limit time display at bottom (between 0~24 and larger than startHour)
*/
public void setLimitTime(int startHour, int endHour) {
if (endHour <= startHour) {
throw new IllegalArgumentException("endHour must larger startHour.");
} else if (startHour < 0) {
throw new IllegalArgumentException("startHour must be at least 0.");
} else if (endHour > 24) {
throw new IllegalArgumentException("endHour can't be higher than 24.");
}
this.mMinTime = startHour;
this.mMaxTime = endHour;
recalculateHourHeight();
invalidate();
}
/**
* Set minimal shown time
*
* @param startHour limit time display on top (between 0~24) and smaller than endHour
*/
public void setMinTime(int startHour) {
if (mMaxTime <= startHour) {
throw new IllegalArgumentException("startHour must smaller than endHour");
} else if (startHour < 0) {
throw new IllegalArgumentException("startHour must be at least 0.");
}
this.mMinTime = startHour;
recalculateHourHeight();
}
/**
* Set highest shown time
*
* @param endHour limit time display at bottom (between 0~24 and larger than startHour)
*/
public void setMaxTime(int endHour) {
if (endHour <= mMinTime) {
throw new IllegalArgumentException("endHour must larger startHour.");
} else if (endHour > 24) {
throw new IllegalArgumentException("endHour can't be higher than 24.");
}
this.mMaxTime = endHour;
recalculateHourHeight();
invalidate();
}
/**
* Whether past and future days should have two different background colors. The past and
* future day colors are defined by the attributes `futureBackgroundColor` and
* `pastBackgroundColor`.
*
* @return True if past and future days should have two different background colors.
*/
public boolean isShowDistinctPastFutureColor() {
return mShowDistinctPastFutureColor;
}
/**
* Set whether weekends should have a background color different from the normal day background
* color. The past and future day colors are defined by the attributes `futureBackgroundColor`
* and `pastBackgroundColor`.
*
* @param showDistinctPastFutureColor True if past and future should have two different
* background colors.
*/
public void setShowDistinctPastFutureColor(boolean showDistinctPastFutureColor) {
this.mShowDistinctPastFutureColor = showDistinctPastFutureColor;
invalidate();
}
/**
* Get whether "now" line should be displayed. "Now" line is defined by the attributes
* `nowLineColor` and `nowLineThickness`.
*
* @return True if "now" line should be displayed.
*/
public boolean isShowNowLine() {
return mShowNowLine;
}
/**
* Set whether "now" line should be displayed. "Now" line is defined by the attributes
* `nowLineColor` and `nowLineThickness`.
*
* @param showNowLine True if "now" line should be displayed.
*/
public void setShowNowLine(boolean showNowLine) {
this.mShowNowLine = showNowLine;
invalidate();
}
/**
* Get the "now" line color.
*
* @return The color of the "now" line.
*/
public int getNowLineColor() {
return mNowLineColor;
}
/**
* Set the "now" line color.
*
* @param nowLineColor The color of the "now" line.
*/
public void setNowLineColor(int nowLineColor) {
this.mNowLineColor = nowLineColor;
invalidate();
}
/**
* Get the "now" line thickness.
*
* @return The thickness of the "now" line.
*/
public int getNowLineThickness() {
return mNowLineThickness;
}
/**
* Set the "now" line thickness.
*
* @param nowLineThickness The thickness of the "now" line.
*/
public void setNowLineThickness(int nowLineThickness) {
this.mNowLineThickness = nowLineThickness;
invalidate();
}
/**
* Get whether the week view should fling horizontally.
*
* @return True if the week view has horizontal fling enabled.
*/
public boolean isHorizontalFlingEnabled() {
return mHorizontalFlingEnabled;
}
/**
* Set whether the week view should fling horizontally.
*
* @param enabled whether the week view should fling horizontally
*/
public void setHorizontalFlingEnabled(boolean enabled) {
mHorizontalFlingEnabled = enabled;
}
/**
* Get whether the week view should fling vertically.
*
* @return True if the week view has vertical fling enabled.
*/
public boolean isVerticalFlingEnabled() {
return mVerticalFlingEnabled;
}
/**
* Set whether the week view should fling vertically.
*
* @param enabled whether the week view should fling vertically
*/
public void setVerticalFlingEnabled(boolean enabled) {
mVerticalFlingEnabled = enabled;
}
/**
* Get the height of AllDay-events.
*
* @return Height of AllDay-events.
*/
public int getAllDayEventHeight() {
return mAllDayEventHeight;
}
/**
* Set the height of AllDay-events.
*
* @param height the new height of AllDay-events
*/
public void setAllDayEventHeight(int height) {
mAllDayEventHeight = height;
}
/**
* Enable zoom focus point
* If you set this to false the `zoomFocusPoint` won't take effect any more while zooming.
* The zoom will always be focused at the center of your gesture.
*
* @param zoomFocusPointEnabled whether the zoomFocusPoint is enabled
*/
public void setZoomFocusPointEnabled(boolean zoomFocusPointEnabled) {
mZoomFocusPointEnabled = zoomFocusPointEnabled;
}
/*
* Is focus point enabled
* @return fixed focus point enabled?
*/
public boolean isZoomFocusPointEnabled() {
return mZoomFocusPointEnabled;
}
/*
* Get focus point
* 0 = top of view, 1 = bottom of view
* The focused point (multiplier of the view height) where the week view is zoomed around.
* This point will not move while zooming.
* @return focus point
*/
public float getZoomFocusPoint() {
return mZoomFocusPoint;
}
/**
* Set focus point
* 0 = top of view, 1 = bottom of view
* The focused point (multiplier of the view height) where the week view is zoomed around.
* This point will not move while zooming.
*
* @param zoomFocusPoint the new zoomFocusPoint
*/
public void setZoomFocusPoint(float zoomFocusPoint) {
if (0 > zoomFocusPoint || zoomFocusPoint > 1)
throw new IllegalStateException("The zoom focus point percentage has to be between 0 and 1");
mZoomFocusPoint = zoomFocusPoint;
}
/**
* Get scroll duration
*
* @return scroll duration
*/
public int getScrollDuration() {
return mScrollDuration;
}
/**
* Set the scroll duration
*
* @param scrollDuration the new scrollDuraction
*/
public void setScrollDuration(int scrollDuration) {
mScrollDuration = scrollDuration;
}
public int getMaxHourHeight() {
return mMaxHourHeight;
}
public void setMaxHourHeight(int maxHourHeight) {
mMaxHourHeight = maxHourHeight;
}
public int getMinHourHeight() {
return mMinHourHeight;
}
public void setMinHourHeight(int minHourHeight) {
this.mMinHourHeight = minHourHeight;
}
public int getPastBackgroundColor() {
return mPastBackgroundColor;
}
public void setPastBackgroundColor(int pastBackgroundColor) {
this.mPastBackgroundColor = pastBackgroundColor;
mPastBackgroundPaint.setColor(mPastBackgroundColor);
}
public int getFutureBackgroundColor() {
return mFutureBackgroundColor;
}
public void setFutureBackgroundColor(int futureBackgroundColor) {
this.mFutureBackgroundColor = futureBackgroundColor;
mFutureBackgroundPaint.setColor(mFutureBackgroundColor);
}
public int getPastWeekendBackgroundColor() {
return mPastWeekendBackgroundColor;
}
public void setPastWeekendBackgroundColor(int pastWeekendBackgroundColor) {
this.mPastWeekendBackgroundColor = pastWeekendBackgroundColor;
this.mPastWeekendBackgroundPaint.setColor(mPastWeekendBackgroundColor);
}
public int getFutureWeekendBackgroundColor() {
return mFutureWeekendBackgroundColor;
}
public void setFutureWeekendBackgroundColor(int futureWeekendBackgroundColor) {
this.mFutureWeekendBackgroundColor = futureWeekendBackgroundColor;
this.mFutureWeekendBackgroundPaint.setColor(mFutureWeekendBackgroundColor);
}
public Drawable getNewEventIconDrawable() {
return mNewEventIconDrawable;
}
public void setNewEventIconDrawable(Drawable newEventIconDrawable) {
this.mNewEventIconDrawable = newEventIconDrawable;
}
public void enableDropListener() {
this.mEnableDropListener = true;
//set drag and drop listener, required Honeycomb+ Api level
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setOnDragListener(new DragListener());
}
}
public void disableDropListener() {
this.mEnableDropListener = false;
//set drag and drop listener, required Honeycomb+ Api level
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setOnDragListener(null);
}
}
public boolean isDropListenerEnabled() {
return this.mEnableDropListener;
}
public void setMinOverlappingMinutes(int minutes) {
this.mMinOverlappingMinutes = minutes;
}
public int getMinOverlappingMinutes() {
return this.mMinOverlappingMinutes;
}
// Functions related to scrolling.
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
boolean val = mGestureDetector.onTouchEvent(event);
// Check after call of mGestureDetector, so mCurrentFlingDirection and mCurrentScrollDirection are set.
if (event.getAction() == MotionEvent.ACTION_UP && !mIsZooming && mCurrentFlingDirection == Direction.NONE) {
if (mCurrentScrollDirection == Direction.RIGHT || mCurrentScrollDirection == Direction.LEFT) {
goToNearestOrigin();
}
mCurrentScrollDirection = Direction.NONE;
}
return val;
}
private void goToNearestOrigin() {
double leftDays = mCurrentOrigin.x / (mWidthPerDay + mColumnGap);
if (mCurrentFlingDirection != Direction.NONE) {
// snap to nearest day
leftDays = Math.round(leftDays);
} else if (mCurrentScrollDirection == Direction.LEFT) {
// snap to last day
leftDays = Math.floor(leftDays);
} else if (mCurrentScrollDirection == Direction.RIGHT) {
// snap to next day
leftDays = Math.ceil(leftDays);
} else {
// snap to nearest day
leftDays = Math.round(leftDays);
}
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay + mColumnGap));
boolean mayScrollHorizontal = mCurrentOrigin.x - nearestOrigin < getXMaxLimit()
&& mCurrentOrigin.x - nearestOrigin > getXMinLimit();
if (mayScrollHorizontal) {
mScroller.startScroll((int) mCurrentOrigin.x, (int) mCurrentOrigin.y, -nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
if (nearestOrigin != 0 && mayScrollHorizontal) {
// Stop current animation.
mScroller.forceFinished(true);
// Snap to date.
mScroller.startScroll((int) mCurrentOrigin.x, (int) mCurrentOrigin.y, -nearestOrigin, 0, (int) (Math.abs(nearestOrigin) / mWidthPerDay * mScrollDuration));
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
// Reset scrolling and fling direction.
mCurrentScrollDirection = mCurrentFlingDirection = Direction.NONE;
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.isFinished()) {
if (mCurrentFlingDirection != Direction.NONE) {
// Snap to day after fling is finished.
goToNearestOrigin();
}
} else {
if (mCurrentFlingDirection != Direction.NONE && forceFinishScroll()) {
goToNearestOrigin();
} else if (mScroller.computeScrollOffset()) {
mCurrentOrigin.y = mScroller.getCurrY();
mCurrentOrigin.x = mScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
}
/**
* Check if scrolling should be stopped.
*
* @return true if scrolling should be stopped before reaching the end of animation.
*/
private boolean forceFinishScroll() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// current velocity only available since api 14
return mScroller.getCurrVelocity() <= mMinimumFlingVelocity;
} else {
return false;
}
}
// Public methods.
/**
* Show today on the week view.
*/
public void goToToday() {
Calendar today = Calendar.getInstance();
goToDate(today);
}
/**
* Show a specific day on the week view.
*
* @param date The date to show.
*/
public void goToDate(Calendar date) {
mScroller.forceFinished(true);
mCurrentScrollDirection = mCurrentFlingDirection = Direction.NONE;
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
if (mAreDimensionsInvalid) {
mScrollToDay = date;
return;
}
mRefreshEvents = true;
mCurrentOrigin.x = -daysBetween(mHomeDate, date) * (mWidthPerDay + mColumnGap);
invalidate();
}
/**
* Refreshes the view and loads the events again.
*/
public void notifyDatasetChanged() {
mRefreshEvents = true;
invalidate();
}
/**
* Vertically scroll to a specific hour in the week view.
*
* @param hour The hour to scroll to in 24-hour format. Supported values are 0-24.
*/
public void goToHour(double hour) {
if (mAreDimensionsInvalid) {
mScrollToHour = hour;
return;
}
int verticalOffset = 0;
if (hour > mMaxTime)
verticalOffset = mHourHeight * (mMaxTime - mMinTime);
else if (hour > mMinTime)
verticalOffset = (int) (mHourHeight * hour);
if (verticalOffset > mHourHeight * (mMaxTime - mMinTime) - getHeight() + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)
verticalOffset = (int) (mHourHeight * (mMaxTime - mMinTime) - getHeight() + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom);
mCurrentOrigin.y = -verticalOffset;
invalidate();
}
/**
* Get the first hour that is visible on the screen.
*
* @return The first hour that is visible.
*/
public double getFirstVisibleHour() {
return -mCurrentOrigin.y / mHourHeight;
}
/**
* Determine whether a given calendar day falls within the scroll limits set for this view.
*
* @param day the day to check
* @return True if there are no limit or the date is within the limits.
* @see #setMinDate(Calendar)
* @see #setMaxDate(Calendar)
*/
public boolean dateIsValid(Calendar day) {
if (mMinDate != null && day.before(mMinDate)) {
return false;
}
if (mMaxDate != null && day.after(mMaxDate)) {
return false;
}
return true;
}
// Interfaces.
public interface DropListener {
void onDrop(View view, Calendar date);
}
public interface EventClickListener {
/**
* Triggered when clicked on one existing event
*
* @param event: event clicked.
* @param eventRect: view containing the clicked event.
*/
void onEventClick(WeekViewEvent event, RectF eventRect);
}
public interface EventLongPressListener {
/**
* Similar to {@link com.alamkanak.weekview.WeekView.EventClickListener} but with a long press.
*
* @param event: event clicked.
* @param eventRect: view containing the clicked event.
*/
void onEventLongPress(WeekViewEvent event, RectF eventRect);
}
public interface EmptyViewClickListener {
void onEmptyViewClicked(Calendar date);
}
public interface EmptyViewLongPressListener {
/**
* Similar to {@link com.alamkanak.weekview.WeekView.EmptyViewClickListener} but with long press.
*
* @param time: {@link Calendar} object set with the date and time of the long pressed position on the view.
*/
void onEmptyViewLongPress(Calendar time);
}
public interface ScrollListener {
/**
* Called when the first visible day has changed.
* <p>
* (this will also be called during the first draw of the weekview)
*
* @param newFirstVisibleDay The new first visible day
* @param oldFirstVisibleDay The old first visible day (is null on the first call).
*/
void onFirstVisibleDayChanged(Calendar newFirstVisibleDay, Calendar oldFirstVisibleDay);
}
public interface AddEventClickListener {
/**
* Triggered when the users clicks to create a new event.
*
* @param startTime The startTime of a new event
* @param endTime The endTime of a new event
*/
void onAddEventClicked(Calendar startTime, Calendar endTime);
}
/**
* A simple GestureListener that holds the focused hour while scaling.
*/
private class WeekViewGestureListener implements ScaleGestureDetector.OnScaleGestureListener {
float mFocusedPointY;
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
mIsZooming = false;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mIsZooming = true;
goToNearestOrigin();
// Calculate focused point for scale action
if (mZoomFocusPointEnabled) {
// Use fractional focus, percentage of height
mFocusedPointY = (getHeight() - mHeaderHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom) * mZoomFocusPoint;
} else {
// Grab focus
mFocusedPointY = detector.getFocusY();
}
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
final float scale = detector.getScaleFactor();
mNewHourHeight = Math.round(mHourHeight * scale);
// Calculating difference
float diffY = mFocusedPointY - mCurrentOrigin.y;
// Scaling difference
diffY = diffY * scale - diffY;
// Updating week view origin
mCurrentOrigin.y -= diffY;
invalidate();
return true;
}
}
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
private class DragListener implements View.OnDragListener {
@Override
public boolean onDrag(View v, DragEvent e) {
switch (e.getAction()) {
case DragEvent.ACTION_DROP:
if (e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
mDropListener.onDrop(v, selectedTime);
}
}
break;
}
return true;
}
}
}
|
package com.alamkanak.weekview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.widget.OverScroller;
import android.widget.Scroller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class WeekView extends View {
@Deprecated
public static final int LENGTH_SHORT = 1;
@Deprecated
public static final int LENGTH_LONG = 2;
private final Context mContext;
private Calendar mHomeDate;
private Calendar mMinDate;
private Calendar mMaxDate;
private Paint mTimeTextPaint;
private float mTimeTextWidth;
private float mTimeTextHeight;
private Paint mHeaderTextPaint;
private float mHeaderTextHeight;
private GestureDetectorCompat mGestureDetector;
private OverScroller mScroller;
private PointF mCurrentOrigin = new PointF(0f, 0f);
private Direction mCurrentScrollDirection = Direction.NONE;
private Paint mHeaderBackgroundPaint;
private float mWidthPerDay;
private Paint mDayBackgroundPaint;
private Paint mHourSeparatorPaint;
private float mHeaderMarginBottom;
private Paint mTodayBackgroundPaint;
private Paint mTodayHeaderTextPaint;
private Paint mEventBackgroundPaint;
private float mHeaderColumnWidth;
private List<EventRect> mEventRects;
private TextPaint mEventTextPaint;
private Paint mHeaderColumnBackgroundPaint;
private Scroller mStickyScroller;
private int mFetchedMonths[] = new int[3];
private boolean mRefreshEvents = false;
private float mDistanceY = 0;
private float mDistanceX = 0;
private Direction mCurrentFlingDirection = Direction.NONE;
// Attributes and their default values.
private int mHourHeight = 50;
private int mColumnGap = 10;
private int mFirstDayOfWeek = Calendar.MONDAY;
private int mTextSize = 12;
private int mHeaderColumnPadding = 10;
private int mHeaderColumnTextColor = Color.BLACK;
private int mNumberOfVisibleDays = 3;
private int mHeaderRowPadding = 10;
private int mHeaderRowBackgroundColor = Color.WHITE;
private int mDayBackgroundColor = Color.rgb(245, 245, 245);
private int mHourSeparatorColor = Color.rgb(230, 230, 230);
private int mTodayBackgroundColor = Color.rgb(239, 247, 254);
private int mHourSeparatorHeight = 2;
private int mTodayHeaderTextColor = Color.rgb(39, 137, 228);
private int mEventTextSize = 12;
private int mEventTextColor = Color.BLACK;
private int mEventPadding = 8;
private int mHeaderColumnBackgroundColor = Color.WHITE;
private int mDefaultEventColor;
private boolean mIsFirstDraw = true;
private boolean mAreDimensionsInvalid = true;
@Deprecated private int mDayNameLength = LENGTH_LONG;
private int mOverlappingEventGap = 0;
private int mEventMarginVertical = 0;
private float mXScrollingSpeed = 1f;
private Calendar mFirstVisibleDay;
private Calendar mLastVisibleDay;
private Calendar mScrollToDay = null;
private double mScrollToHour = -1;
// Listeners.
private EventClickListener mEventClickListener;
private EventLongPressListener mEventLongPressListener;
private MonthChangeListener mMonthChangeListener;
private EmptyViewClickListener mEmptyViewClickListener;
private EmptyViewLongPressListener mEmptyViewLongPressListener;
private DateTimeInterpreter mDateTimeInterpreter;
private ScrollListener mScrollListener;
private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (mCurrentScrollDirection == Direction.NONE) {
if (Math.abs(distanceX) > Math.abs(distanceY)){
mCurrentScrollDirection = Direction.HORIZONTAL;
mCurrentFlingDirection = Direction.HORIZONTAL;
}
else {
mCurrentFlingDirection = Direction.VERTICAL;
mCurrentScrollDirection = Direction.VERTICAL;
}
}
mDistanceX = distanceX * mXScrollingSpeed;
mDistanceY = distanceY;
// Update the origin, enforcing the scroll limits
if (mCurrentScrollDirection == Direction.HORIZONTAL) {
float minX = getXMinLimit(), maxX = getXMaxLimit();
if (mCurrentOrigin.x - mDistanceX > maxX)
mCurrentOrigin.x = maxX;
else if (mCurrentOrigin.x - mDistanceX < minX)
mCurrentOrigin.x = minX;
else
mCurrentOrigin.x -= mDistanceX;
} else if (mCurrentScrollDirection == Direction.VERTICAL) {
float minY = getYMinLimit(), maxY = getYMaxLimit();
if (mCurrentOrigin.y - mDistanceY > maxY)
mCurrentOrigin.y = maxY;
else if (mCurrentOrigin.y - mDistanceY < minY)
mCurrentOrigin.y = minY;
else
mCurrentOrigin.y -= mDistanceY;
}
invalidate();
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
if (mCurrentFlingDirection == Direction.HORIZONTAL){
mScroller.fling((int) mCurrentOrigin.x, 0, (int) (velocityX * mXScrollingSpeed), 0, (int) getXMinLimit(), (int) getXMaxLimit(), 0, 0);
}
else if (mCurrentFlingDirection == Direction.VERTICAL){
mScroller.fling(0, (int) mCurrentOrigin.y, 0, (int) velocityY, 0, 0, (int) getYMinLimit(), (int) getYMaxLimit());
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// If the tap was on an event then trigger the callback.
if (mEventRects != null && mEventClickListener != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventClickListener.onEventClick(event.originalEvent, event.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
return super.onSingleTapConfirmed(e);
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewClickListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mEmptyViewClickListener.onEmptyViewClicked(selectedTime);
}
}
return super.onSingleTapConfirmed(e);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
if (mEventLongPressListener != null && mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventLongPressListener.onEventLongPress(event.originalEvent, event.rectF);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return;
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewLongPressListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
mEmptyViewLongPressListener.onEmptyViewLongPress(selectedTime);
}
}
}
};
private enum Direction {
NONE, HORIZONTAL, VERTICAL
}
public WeekView(Context context) {
this(context, null);
}
public WeekView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WeekView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Hold references.
mContext = context;
// Get the attribute values (if any).
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WeekView, 0, 0);
try {
mFirstDayOfWeek = a.getInteger(R.styleable.WeekView_firstDayOfWeek, mFirstDayOfWeek);
mHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourHeight, mHourHeight);
mTextSize = a.getDimensionPixelSize(R.styleable.WeekView_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, context.getResources().getDisplayMetrics()));
mHeaderColumnPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerColumnPadding, mHeaderColumnPadding);
mColumnGap = a.getDimensionPixelSize(R.styleable.WeekView_columnGap, mColumnGap);
mHeaderColumnTextColor = a.getColor(R.styleable.WeekView_headerColumnTextColor, mHeaderColumnTextColor);
mNumberOfVisibleDays = a.getInteger(R.styleable.WeekView_noOfVisibleDays, mNumberOfVisibleDays);
mHeaderRowPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerRowPadding, mHeaderRowPadding);
mHeaderRowBackgroundColor = a.getColor(R.styleable.WeekView_headerRowBackgroundColor, mHeaderRowBackgroundColor);
mDayBackgroundColor = a.getColor(R.styleable.WeekView_dayBackgroundColor, mDayBackgroundColor);
mHourSeparatorColor = a.getColor(R.styleable.WeekView_hourSeparatorColor, mHourSeparatorColor);
mTodayBackgroundColor = a.getColor(R.styleable.WeekView_todayBackgroundColor, mTodayBackgroundColor);
mHourSeparatorHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mHourSeparatorHeight);
mTodayHeaderTextColor = a.getColor(R.styleable.WeekView_todayHeaderTextColor, mTodayHeaderTextColor);
mEventTextSize = a.getDimensionPixelSize(R.styleable.WeekView_eventTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mEventTextSize, context.getResources().getDisplayMetrics()));
mEventTextColor = a.getColor(R.styleable.WeekView_eventTextColor, mEventTextColor);
mEventPadding = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mEventPadding);
mHeaderColumnBackgroundColor = a.getColor(R.styleable.WeekView_headerColumnBackground, mHeaderColumnBackgroundColor);
mDayNameLength = a.getInteger(R.styleable.WeekView_dayNameLength, mDayNameLength);
mOverlappingEventGap = a.getDimensionPixelSize(R.styleable.WeekView_overlappingEventGap, mOverlappingEventGap);
mEventMarginVertical = a.getDimensionPixelSize(R.styleable.WeekView_eventMarginVertical, mEventMarginVertical);
mXScrollingSpeed = a.getFloat(R.styleable.WeekView_xScrollingSpeed, mXScrollingSpeed);
} finally {
a.recycle();
}
init();
}
private void init() {
// Initialize the home date, which will be day zero for layout purposes (other days have a
// positive or negative offset relative to the home date)
resetHomeDate();
// Scrolling initialization.
mGestureDetector = new GestureDetectorCompat(mContext, mGestureListener);
mScroller = new OverScroller(mContext);
mStickyScroller = new Scroller(mContext);
// Measure settings for time column.
mTimeTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTimeTextPaint.setTextAlign(Paint.Align.RIGHT);
mTimeTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
Rect rect = new Rect();
mTimeTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mTimeTextWidth = mTimeTextPaint.measureText("00 PM");
mTimeTextHeight = rect.height();
mHeaderMarginBottom = mTimeTextHeight / 2;
// Measure settings for header row.
mHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mHeaderTextHeight = rect.height();
mHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
// Prepare header background paint.
mHeaderBackgroundPaint = new Paint();
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
// Prepare day background color paint.
mDayBackgroundPaint = new Paint();
mDayBackgroundPaint.setColor(mDayBackgroundColor);
// Prepare hour separator color paint.
mHourSeparatorPaint = new Paint();
mHourSeparatorPaint.setStyle(Paint.Style.STROKE);
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
mHourSeparatorPaint.setColor(mHourSeparatorColor);
// Prepare today background color paint.
mTodayBackgroundPaint = new Paint();
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
// Prepare today header text color paint.
mTodayHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTodayHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mTodayHeaderTextPaint.setTextSize(mTextSize);
mTodayHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
// Prepare event background color.
mEventBackgroundPaint = new Paint();
mEventBackgroundPaint.setColor(Color.rgb(174, 208, 238));
// Prepare header column background color.
mHeaderColumnBackgroundPaint = new Paint();
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
// Prepare event text size and color.
mEventTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
mEventTextPaint.setStyle(Paint.Style.FILL);
mEventTextPaint.setColor(mEventTextColor);
mEventTextPaint.setTextSize(mEventTextSize);
// Set default event color.
mDefaultEventColor = Color.parseColor("#9fc6e7");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the header row.
drawHeaderRowAndEvents(canvas);
// Draw the time column and all the axes/separators.
drawTimeColumnAndAxes(canvas);
// Hide everything in the first cell (top left corner).
canvas.drawRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Hide anything that is in the bottom margin of the header row.
canvas.drawRect(mHeaderColumnWidth, mHeaderTextHeight + mHeaderRowPadding * 2, getWidth(), mHeaderRowPadding * 2 + mHeaderTextHeight + mHeaderMarginBottom + mTimeTextHeight/2 - mHourSeparatorHeight / 2, mHeaderColumnBackgroundPaint);
}
private void drawTimeColumnAndAxes(Canvas canvas) {
// Draw the background color for the header column.
canvas.drawRect(0, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), mHeaderColumnBackgroundPaint);
for (int i = 0; i < 24; i++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * i + mHeaderMarginBottom;
// Draw the text if its y position is not outside of the visible area. The pivot point of the text is the point at the bottom-right corner.
String time = getDateTimeInterpreter().interpretTime(i);
if (time == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null time");
if (top < getHeight()) canvas.drawText(time, mTimeTextWidth + mHeaderColumnPadding, top + mTimeTextHeight, mTimeTextPaint);
}
}
private void drawHeaderRowAndEvents(Canvas canvas) {
// Calculate the available width for each day.
mHeaderColumnWidth = mTimeTextWidth + mHeaderColumnPadding *2;
mWidthPerDay = getWidth() - mHeaderColumnWidth - mColumnGap * (mNumberOfVisibleDays - 1);
mWidthPerDay = mWidthPerDay/mNumberOfVisibleDays;
if (mAreDimensionsInvalid) {
mAreDimensionsInvalid = false;
if(mScrollToDay != null)
goToDate(mScrollToDay);
mAreDimensionsInvalid = false;
if(mScrollToHour >= 0)
goToHour(mScrollToHour);
mScrollToDay = null;
mScrollToHour = -1;
mAreDimensionsInvalid = false;
}
if (mIsFirstDraw){
mIsFirstDraw = false;
// If the week view is being drawn for the first time, then consider the first day of the week.
if(mNumberOfVisibleDays >= 7 && mHomeDate.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek) {
int difference = (7 + (mHomeDate.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek)) % 7;
mCurrentOrigin.x += (mWidthPerDay + mColumnGap) * difference;
}
}
// Consider scroll offset.
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startFromPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
float startPixel = startFromPixel;
// Get today's date for highlighting purposes
Calendar today = Calendar.getInstance();
// Prepare to iterate for each hour to draw the hour lines.
int lineCount = (int) ((getHeight() - mHeaderTextHeight - mHeaderRowPadding * 2 -
mHeaderMarginBottom) / mHourHeight) + 1;
lineCount = (lineCount) * (mNumberOfVisibleDays+1);
float[] hourLines = new float[lineCount * 4];
// Clear the cache for event rectangles.
if (mEventRects != null) {
for (EventRect eventRect: mEventRects) {
eventRect.rectF = null;
}
}
// Iterate through each day.
Calendar day;
Calendar oldFirstVisibleDay = mFirstVisibleDay;
mFirstVisibleDay = (Calendar) mHomeDate.clone();
mFirstVisibleDay.add(Calendar.DATE, leftDaysWithGaps);
if(!mFirstVisibleDay.equals(oldFirstVisibleDay) && mScrollListener != null){
mScrollListener.onFirstVisibleDayChanged(mFirstVisibleDay, oldFirstVisibleDay);
}
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
// Check if the day is today.
day = (Calendar) mHomeDate.clone();
mLastVisibleDay = (Calendar) day.clone();
day.add(Calendar.DATE, dayNumber - 1);
mLastVisibleDay.add(Calendar.DATE, dayNumber - 2);
boolean isToday = isSameDay(day, today);
// Get more events if necessary. We want to store the events 3 months beforehand. Get
// events only when it is the first iteration of the loop.
if (mEventRects == null || mRefreshEvents || (dayNumber == leftDaysWithGaps + 1 && mFetchedMonths[1] != day.get(Calendar.MONTH)+1 && day.get(Calendar.DAY_OF_MONTH) == 15)) {
getMoreEvents(day);
mRefreshEvents = false;
}
// Draw background color for each day.
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start> 0)
canvas.drawRect(start, mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom, startPixel + mWidthPerDay, getHeight(), isToday ? mTodayBackgroundPaint : mDayBackgroundPaint);
// Prepare the separator lines for hours.
int i = 0;
for (int hourNumber = 0; hourNumber < 24; hourNumber++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * hourNumber + mTimeTextHeight/2 + mHeaderMarginBottom;
if (top > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom - mHourSeparatorHeight && top < getHeight() && startPixel + mWidthPerDay - start > 0){
hourLines[i * 4] = start;
hourLines[i * 4 + 1] = top;
hourLines[i * 4 + 2] = startPixel + mWidthPerDay;
hourLines[i * 4 + 3] = top;
i++;
}
}
// Draw the lines for hours.
canvas.drawLines(hourLines, mHourSeparatorPaint);
// Draw the events.
drawEvents(day, startPixel, canvas);
// In the next iteration, start from the next day.
startPixel += mWidthPerDay + mColumnGap;
}
// Draw the header background.
canvas.drawRect(0, 0, getWidth(), mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row texts.
startPixel = startFromPixel;
for (int dayNumber=leftDaysWithGaps+1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) {
// Check if the day is today.
day = (Calendar) mHomeDate.clone();
day.add(Calendar.DATE, dayNumber - 1);
boolean isToday = isSameDay(day, today);
// Draw the day labels.
String dayLabel = getDateTimeInterpreter().interpretDate(day);
if (dayLabel == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null date");
canvas.drawText(dayLabel, startPixel + mWidthPerDay / 2, mHeaderTextHeight + mHeaderRowPadding, isToday ? mTodayHeaderTextPaint : mHeaderTextPaint);
startPixel += mWidthPerDay + mColumnGap;
}
}
/**
* Get the time and date where the user clicked on.
* @param x The x position of the touch event.
* @param y The y position of the touch event.
* @return The time and date at the clicked position.
*/
private Calendar getTimeFromPoint(float x, float y){
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start> 0
&& x>start && x<startPixel + mWidthPerDay){
Calendar day = (Calendar) mHomeDate.clone();
day.add(Calendar.DATE, dayNumber - 1);
float pixelsFromZero = y - mCurrentOrigin.y - mHeaderTextHeight
- mHeaderRowPadding * 2 - mTimeTextHeight/2 - mHeaderMarginBottom;
int hour = (int)(pixelsFromZero / mHourHeight);
int minute = (int) (60 * (pixelsFromZero - hour * mHourHeight) / mHourHeight);
day.add(Calendar.HOUR, hour);
day.set(Calendar.MINUTE, minute);
return day;
}
startPixel += mWidthPerDay + mColumnGap;
}
return null;
}
/**
* Draw all the events of a particular day.
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date)) {
// Calculate top.
float top = mHourHeight * 24 * mEventRects.get(i).top / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 + mEventMarginVertical;
float originalTop = top;
if (top < mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2)
top = mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2;
// Calculate bottom.
float bottom = mEventRects.get(i).bottom;
bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - mEventMarginVertical;
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float originalLeft = left;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
if (left < mHeaderColumnWidth) left = mHeaderColumnWidth;
// Draw the event and the event name on top of it.
RectF eventRectF = new RectF(left, top, right, bottom);
if (bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 && left < right &&
eventRectF.right > mHeaderColumnWidth &&
eventRectF.left < getWidth() &&
eventRectF.bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom &&
eventRectF.top < getHeight() &&
left < right
) {
mEventRects.get(i).rectF = eventRectF;
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
canvas.drawRect(mEventRects.get(i).rectF, mEventBackgroundPaint);
drawText(mEventRects.get(i).event.getName(), mEventRects.get(i).rectF, canvas, originalTop, originalLeft);
}
else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw the name of the event on top of the event rectangle.
* @param text The text to draw.
* @param rect The rectangle on which the text is to be drawn.
* @param canvas The canvas to draw upon.
* @param originalTop The original top position of the rectangle. The rectangle may have some of its portion outside of the visible area.
* @param originalLeft The original left position of the rectangle. The rectangle may have some of its portion outside of the visible area.
*/
private void drawText(String text, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
// Get text dimensions
StaticLayout textLayout = new StaticLayout(text, mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Crop height
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (lineHeight < availableHeight && textLayout.getHeight() > rect.height() - mEventPadding * 2) {
int lineCount = textLayout.getLineCount();
int availableLineCount = (int) Math.floor(lineCount * availableHeight / textLayout.getHeight());
float widthAvailable = (rect.right - originalLeft - mEventPadding * 2) * availableLineCount;
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, widthAvailable, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
else if (lineHeight >= availableHeight) {
int width = (int) (rect.right - originalLeft - mEventPadding * 2);
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, width, TextUtils.TruncateAt.END), mEventTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false);
}
// Draw text
canvas.save();
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding);
textLayout.draw(canvas);
canvas.restore();
}
/**
* A class to hold reference to the events and their visual representation. An EventRect is
* actually the rectangle that is drawn on the calendar for a given event. There may be more
* than one rectangle for a single event (an event that expands more than one day). In that
* case two instances of the EventRect will be used for a single event. The given event will be
* stored in "originalEvent". But the event that corresponds to rectangle the rectangle
* instance will be stored in "event".
*/
private class EventRect {
public WeekViewEvent event;
public WeekViewEvent originalEvent;
public RectF rectF;
public float left;
public float width;
public float top;
public float bottom;
/**
* Create a new instance of event rect. An EventRect is actually the rectangle that is drawn
* on the calendar for a given event. There may be more than one rectangle for a single
* event (an event that expands more than one day). In that case two instances of the
* EventRect will be used for a single event. The given event will be stored in
* "originalEvent". But the event that corresponds to rectangle the rectangle instance will
* be stored in "event".
* @param event Represents the event which this instance of rectangle represents.
* @param originalEvent The original event that was passed by the user.
* @param rectF The rectangle.
*/
public EventRect(WeekViewEvent event, WeekViewEvent originalEvent, RectF rectF) {
this.event = event;
this.rectF = rectF;
this.originalEvent = originalEvent;
}
}
/**
* Gets more events of one/more month(s) if necessary. This method is called when the user is
* scrolling the week view. The week view stores the events of three months: the visible month,
* the previous month, the next month.
* @param day The day where the user is currently is.
*/
private void getMoreEvents(Calendar day) {
// Delete all events if its not current month +- 1.
deleteFarMonths(day);
// Get more events if the month is changed.
if (mEventRects == null)
mEventRects = new ArrayList<EventRect>();
if (mMonthChangeListener == null && !isInEditMode())
throw new IllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if (mRefreshEvents) {
mEventRects.clear();
mFetchedMonths = new int[3];
}
// Get events of previous month.
int previousMonth = (day.get(Calendar.MONTH) == 0?12:day.get(Calendar.MONTH));
int nextMonth = (day.get(Calendar.MONTH)+2 == 13 ?1:day.get(Calendar.MONTH)+2);
int[] lastFetchedMonth = mFetchedMonths.clone();
if (mFetchedMonths[0] < 1 || mFetchedMonths[0] != previousMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, previousMonth) && !isInEditMode()){
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange((previousMonth==12)?day.get(Calendar.YEAR)-1:day.get(Calendar.YEAR), previousMonth);
sortEvents(events);
for (WeekViewEvent event: events) {
cacheEvent(event);
}
}
mFetchedMonths[0] = previousMonth;
}
// Get events of this month.
if (mFetchedMonths[1] < 1 || mFetchedMonths[1] != day.get(Calendar.MONTH)+1 || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, day.get(Calendar.MONTH)+1) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(day.get(Calendar.YEAR), day.get(Calendar.MONTH) + 1);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[1] = day.get(Calendar.MONTH)+1;
}
// Get events of next month.
if (mFetchedMonths[2] < 1 || mFetchedMonths[2] != nextMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, nextMonth) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(nextMonth == 1 ? day.get(Calendar.YEAR) + 1 : day.get(Calendar.YEAR), nextMonth);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[2] = nextMonth;
}
// Prepare to calculate positions of each events.
ArrayList<EventRect> tempEvents = new ArrayList<EventRect>(mEventRects);
mEventRects = new ArrayList<EventRect>();
Calendar dayCounter = (Calendar) day.clone();
dayCounter.add(Calendar.MONTH, -1);
dayCounter.set(Calendar.DAY_OF_MONTH, 1);
Calendar maxDay = (Calendar) day.clone();
maxDay.add(Calendar.MONTH, 1);
maxDay.set(Calendar.DAY_OF_MONTH, maxDay.getActualMaximum(Calendar.DAY_OF_MONTH));
// Iterate through each day to calculate the position of the events.
while (dayCounter.getTimeInMillis() <= maxDay.getTimeInMillis()) {
ArrayList<EventRect> eventRects = new ArrayList<EventRect>();
for (EventRect eventRect : tempEvents) {
if (isSameDay(eventRect.event.getStartTime(), dayCounter))
eventRects.add(eventRect);
}
computePositionOfEvents(eventRects);
dayCounter.add(Calendar.DATE, 1);
}
}
/**
* Cache the event for smooth scrolling functionality.
* @param event The event to cache.
*/
private void cacheEvent(WeekViewEvent event) {
if (!isSameDay(event.getStartTime(), event.getEndTime())) {
Calendar endTime = (Calendar) event.getStartTime().clone();
endTime.set(Calendar.HOUR_OF_DAY, 23);
endTime.set(Calendar.MINUTE, 59);
Calendar startTime = (Calendar) event.getEndTime().clone();
startTime.set(Calendar.HOUR_OF_DAY, 0);
startTime.set(Calendar.MINUTE, 0);
WeekViewEvent event1 = new WeekViewEvent(event.getId(), event.getName(), event.getStartTime(), endTime);
event1.setColor(event.getColor());
WeekViewEvent event2 = new WeekViewEvent(event.getId(), event.getName(), startTime, event.getEndTime());
event2.setColor(event.getColor());
mEventRects.add(new EventRect(event1, event, null));
mEventRects.add(new EventRect(event2, event, null));
}
else
mEventRects.add(new EventRect(event, event, null));
}
/**
* Sorts the events in ascending order.
* @param events The events to be sorted.
*/
private void sortEvents(List<WeekViewEvent> events) {
Collections.sort(events, new Comparator<WeekViewEvent>() {
@Override
public int compare(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
int comparator = start1 > start2 ? 1 : (start1 < start2 ? -1 : 0);
if (comparator == 0) {
long end1 = event1.getEndTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
comparator = end1 > end2 ? 1 : (end1 < end2 ? -1 : 0);
}
return comparator;
}
});
}
/**
* Calculates the left and right positions of each events. This comes handy specially if events
* are overlapping.
* @param eventRects The events along with their wrapper class.
*/
private void computePositionOfEvents(List<EventRect> eventRects) {
// Make "collision groups" for all events that collide with others.
List<List<EventRect>> collisionGroups = new ArrayList<List<EventRect>>();
for (EventRect eventRect : eventRects) {
boolean isPlaced = false;
outerLoop:
for (List<EventRect> collisionGroup : collisionGroups) {
for (EventRect groupEvent : collisionGroup) {
if (isEventsCollide(groupEvent.event, eventRect.event)) {
collisionGroup.add(eventRect);
isPlaced = true;
break outerLoop;
}
}
}
if (!isPlaced) {
List<EventRect> newGroup = new ArrayList<EventRect>();
newGroup.add(eventRect);
collisionGroups.add(newGroup);
}
}
for (List<EventRect> collisionGroup : collisionGroups) {
expandEventsToMaxWidth(collisionGroup);
}
}
/**
* Expands all the events to maximum possible width. The events will try to occupy maximum
* space available horizontally.
* @param collisionGroup The group of events which overlap with each other.
*/
private void expandEventsToMaxWidth(List<EventRect> collisionGroup) {
// Expand the events to maximum possible width.
List<List<EventRect>> columns = new ArrayList<List<EventRect>>();
columns.add(new ArrayList<EventRect>());
for (EventRect eventRect : collisionGroup) {
boolean isPlaced = false;
for (List<EventRect> column : columns) {
if (column.size() == 0) {
column.add(eventRect);
isPlaced = true;
}
else if (!isEventsCollide(eventRect.event, column.get(column.size()-1).event)) {
column.add(eventRect);
isPlaced = true;
break;
}
}
if (!isPlaced) {
List<EventRect> newColumn = new ArrayList<EventRect>();
newColumn.add(eventRect);
columns.add(newColumn);
}
}
// Calculate left and right position for all the events.
// Get the maxRowCount by looking in all columns.
int maxRowCount = 0;
for (List<EventRect> column : columns){
maxRowCount = Math.max(maxRowCount, column.size());
}
for (int i = 0; i < maxRowCount; i++) {
// Set the left and right values of the event.
float j = 0;
for (List<EventRect> column : columns) {
if (column.size() >= i+1) {
EventRect eventRect = column.get(i);
eventRect.width = 1f / columns.size();
eventRect.left = j / columns.size();
eventRect.top = eventRect.event.getStartTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getStartTime().get(Calendar.MINUTE);
eventRect.bottom = eventRect.event.getEndTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getEndTime().get(Calendar.MINUTE);
mEventRects.add(eventRect);
}
j++;
}
}
}
/**
* Checks if two events overlap.
* @param event1 The first event.
* @param event2 The second event.
* @return true if the events overlap.
*/
private boolean isEventsCollide(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long end1 = event1.getEndTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
return !((start1 >= end2) || (end1 <= start2));
}
/**
* Checks if time1 occurs after (or at the same time) time2.
* @param time1 The time to check.
* @param time2 The time to check against.
* @return true if time1 and time2 are equal or if time1 is after time2. Otherwise false.
*/
private boolean isTimeAfterOrEquals(Calendar time1, Calendar time2) {
return !(time1 == null || time2 == null) && time1.getTimeInMillis() >= time2.getTimeInMillis();
}
/**
* Deletes the events of the months that are too far away from the current month.
* @param currentDay The current day.
*/
private void deleteFarMonths(Calendar currentDay) {
if (mEventRects == null) return;
Calendar nextMonth = (Calendar) currentDay.clone();
nextMonth.add(Calendar.MONTH, 1);
nextMonth.set(Calendar.DAY_OF_MONTH, nextMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
nextMonth.set(Calendar.HOUR_OF_DAY, 12);
nextMonth.set(Calendar.MINUTE, 59);
nextMonth.set(Calendar.SECOND, 59);
Calendar prevMonth = (Calendar) currentDay.clone();
prevMonth.add(Calendar.MONTH, -1);
prevMonth.set(Calendar.DAY_OF_MONTH, 1);
prevMonth.set(Calendar.HOUR_OF_DAY, 0);
prevMonth.set(Calendar.MINUTE, 0);
prevMonth.set(Calendar.SECOND, 0);
List<EventRect> newEvents = new ArrayList<EventRect>();
for (EventRect eventRect : mEventRects) {
boolean isFarMonth = eventRect.event.getStartTime().getTimeInMillis() > nextMonth.getTimeInMillis() || eventRect.event.getEndTime().getTimeInMillis() < prevMonth.getTimeInMillis();
if (!isFarMonth) newEvents.add(eventRect);
}
mEventRects.clear();
mEventRects.addAll(newEvents);
}
@Override
public void invalidate() {
super.invalidate();
mAreDimensionsInvalid = true;
}
/**
* Reset day zero to the current day.
*/
private void resetHomeDate() {
mHomeDate = Calendar.getInstance();
mHomeDate.set(Calendar.HOUR_OF_DAY, 0);
mHomeDate.set(Calendar.MINUTE, 0);
mHomeDate.set(Calendar.SECOND, 0);
}
/**
* @return The scroll offset (on the X axis) where the given day starts
*/
private float getXOriginForDate(Calendar date) {
int dateDifference = (int) (date.getTimeInMillis() - mHomeDate.getTimeInMillis()) / (1000 * 60 * 60 * 24);
return - dateDifference * (mWidthPerDay + mColumnGap);
}
private float getYMinLimit() {
return -(mHourHeight * 24
+ mHeaderTextHeight
+ mHeaderRowPadding * 2
- getHeight());
}
private float getYMaxLimit() {
return 0;
}
private float getXMinLimit() {
if (mMaxDate == null)
return Integer.MIN_VALUE;
else
return getXOriginForDate(mMaxDate);
}
private float getXMaxLimit() {
if (mMinDate == null)
return Integer.MAX_VALUE;
else
return getXOriginForDate(mMinDate);
}
// Functions related to setting and getting the properties.
public void setOnEventClickListener (EventClickListener listener) {
this.mEventClickListener = listener;
}
public EventClickListener getEventClickListener() {
return mEventClickListener;
}
public MonthChangeListener getMonthChangeListener() {
return mMonthChangeListener;
}
public void setMonthChangeListener(MonthChangeListener monthChangeListener) {
this.mMonthChangeListener = monthChangeListener;
}
public EventLongPressListener getEventLongPressListener() {
return mEventLongPressListener;
}
public void setEventLongPressListener(EventLongPressListener eventLongPressListener) {
this.mEventLongPressListener = eventLongPressListener;
}
public void setEmptyViewClickListener(EmptyViewClickListener emptyViewClickListener){
this.mEmptyViewClickListener = emptyViewClickListener;
}
public EmptyViewClickListener getEmptyViewClickListener(){
return mEmptyViewClickListener;
}
public void setEmptyViewLongPressListener(EmptyViewLongPressListener emptyViewLongPressListener){
this.mEmptyViewLongPressListener = emptyViewLongPressListener;
}
public EmptyViewLongPressListener getEmptyViewLongPressListener(){
return mEmptyViewLongPressListener;
}
public void setScrollListener(ScrollListener scrolledListener){
this.mScrollListener = scrolledListener;
}
public ScrollListener getScrollListener(){
return mScrollListener;
}
/**
* Get the interpreter which provides the text to show in the header column and the header row.
* @return The date, time interpreter.
*/
public DateTimeInterpreter getDateTimeInterpreter() {
if (mDateTimeInterpreter == null) {
mDateTimeInterpreter = new DateTimeInterpreter() {
@Override
public String interpretDate(Calendar date) {
SimpleDateFormat sdf;
sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE") : new SimpleDateFormat("EEE");
try{
String dayName = sdf.format(date.getTime()).toUpperCase();
return String.format("%s %d/%02d", dayName, date.get(Calendar.MONTH) + 1, date.get(Calendar.DAY_OF_MONTH));
}catch (Exception e){
e.printStackTrace();
return "";
}
}
@Override
public String interpretTime(int hour) {
String amPm;
if (hour >= 0 && hour < 12) amPm = "AM";
else amPm = "PM";
if (hour == 0) hour = 12;
if (hour > 12) hour -= 12;
return String.format("%02d %s", hour, amPm);
}
};
}
return mDateTimeInterpreter;
}
/**
* Set the interpreter which provides the text to show in the header column and the header row.
* @param dateTimeInterpreter The date, time interpreter.
*/
public void setDateTimeInterpreter(DateTimeInterpreter dateTimeInterpreter){
this.mDateTimeInterpreter = dateTimeInterpreter;
}
/**
* Get the number of visible days in a week.
* @return The number of visible days in a week.
*/
public int getNumberOfVisibleDays() {
return mNumberOfVisibleDays;
}
/**
* Set the number of visible days in a week.
* @param numberOfVisibleDays The number of visible days in a week.
*/
public void setNumberOfVisibleDays(int numberOfVisibleDays) {
this.mNumberOfVisibleDays = numberOfVisibleDays;
mCurrentOrigin.x = 0;
mCurrentOrigin.y = 0;
invalidate();
}
public int getHourHeight() {
return mHourHeight;
}
public void setHourHeight(int hourHeight) {
mHourHeight = hourHeight;
invalidate();
}
public int getColumnGap() {
return mColumnGap;
}
public void setColumnGap(int columnGap) {
mColumnGap = columnGap;
invalidate();
}
public int getFirstDayOfWeek() {
return mFirstDayOfWeek;
}
/**
* Set the first day of the week. First day of the week is used only when the week view is first
* drawn. It does not of any effect after user starts scrolling horizontally.
* <p>
* <b>Note:</b> This method will only work if the week view is set to display more than 6 days at
* once.
* </p>
* @param firstDayOfWeek The supported values are {@link java.util.Calendar#SUNDAY},
* {@link java.util.Calendar#MONDAY}, {@link java.util.Calendar#TUESDAY},
* {@link java.util.Calendar#WEDNESDAY}, {@link java.util.Calendar#THURSDAY},
* {@link java.util.Calendar#FRIDAY}.
*/
public void setFirstDayOfWeek(int firstDayOfWeek) {
mFirstDayOfWeek = firstDayOfWeek;
invalidate();
}
public int getTextSize() {
return mTextSize;
}
public void setTextSize(int textSize) {
mTextSize = textSize;
mTodayHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setTextSize(mTextSize);
invalidate();
}
public int getHeaderColumnPadding() {
return mHeaderColumnPadding;
}
public void setHeaderColumnPadding(int headerColumnPadding) {
mHeaderColumnPadding = headerColumnPadding;
invalidate();
}
public int getHeaderColumnTextColor() {
return mHeaderColumnTextColor;
}
public void setHeaderColumnTextColor(int headerColumnTextColor) {
mHeaderColumnTextColor = headerColumnTextColor;
invalidate();
}
public int getHeaderRowPadding() {
return mHeaderRowPadding;
}
public void setHeaderRowPadding(int headerRowPadding) {
mHeaderRowPadding = headerRowPadding;
invalidate();
}
public int getHeaderRowBackgroundColor() {
return mHeaderRowBackgroundColor;
}
public void setHeaderRowBackgroundColor(int headerRowBackgroundColor) {
mHeaderRowBackgroundColor = headerRowBackgroundColor;
invalidate();
}
public int getDayBackgroundColor() {
return mDayBackgroundColor;
}
public void setDayBackgroundColor(int dayBackgroundColor) {
mDayBackgroundColor = dayBackgroundColor;
invalidate();
}
public int getHourSeparatorColor() {
return mHourSeparatorColor;
}
public void setHourSeparatorColor(int hourSeparatorColor) {
mHourSeparatorColor = hourSeparatorColor;
invalidate();
}
public int getTodayBackgroundColor() {
return mTodayBackgroundColor;
}
public void setTodayBackgroundColor(int todayBackgroundColor) {
mTodayBackgroundColor = todayBackgroundColor;
invalidate();
}
public int getHourSeparatorHeight() {
return mHourSeparatorHeight;
}
public void setHourSeparatorHeight(int hourSeparatorHeight) {
mHourSeparatorHeight = hourSeparatorHeight;
invalidate();
}
public int getTodayHeaderTextColor() {
return mTodayHeaderTextColor;
}
public void setTodayHeaderTextColor(int todayHeaderTextColor) {
mTodayHeaderTextColor = todayHeaderTextColor;
invalidate();
}
public int getEventTextSize() {
return mEventTextSize;
}
public void setEventTextSize(int eventTextSize) {
mEventTextSize = eventTextSize;
mEventTextPaint.setTextSize(mEventTextSize);
invalidate();
}
public int getEventTextColor() {
return mEventTextColor;
}
public void setEventTextColor(int eventTextColor) {
mEventTextColor = eventTextColor;
invalidate();
}
public int getEventPadding() {
return mEventPadding;
}
public void setEventPadding(int eventPadding) {
mEventPadding = eventPadding;
invalidate();
}
public int getHeaderColumnBackgroundColor() {
return mHeaderColumnBackgroundColor;
}
public void setHeaderColumnBackgroundColor(int headerColumnBackgroundColor) {
mHeaderColumnBackgroundColor = headerColumnBackgroundColor;
invalidate();
}
public int getDefaultEventColor() {
return mDefaultEventColor;
}
public void setDefaultEventColor(int defaultEventColor) {
mDefaultEventColor = defaultEventColor;
invalidate();
}
/**
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} and
* {@link #getDateTimeInterpreter()} instead.
* @return Either long or short day name is being used.
*/
@Deprecated
public int getDayNameLength() {
return mDayNameLength;
}
/**
* Set the length of the day name displayed in the header row. Example of short day names is
* 'M' for 'Monday' and example of long day names is 'Mon' for 'Monday'.
* <p>
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} instead.
* </p>
* @param length Supported values are {@link com.alamkanak.weekview.WeekView#LENGTH_SHORT} and
* {@link com.alamkanak.weekview.WeekView#LENGTH_LONG}.
*/
@Deprecated
public void setDayNameLength(int length) {
if (length != LENGTH_LONG && length != LENGTH_SHORT) {
throw new IllegalArgumentException("length parameter must be either LENGTH_LONG or LENGTH_SHORT");
}
this.mDayNameLength = length;
}
public int getOverlappingEventGap() {
return mOverlappingEventGap;
}
/**
* Set the gap between overlapping events.
* @param overlappingEventGap The gap between overlapping events.
*/
public void setOverlappingEventGap(int overlappingEventGap) {
this.mOverlappingEventGap = overlappingEventGap;
invalidate();
}
public int getEventMarginVertical() {
return mEventMarginVertical;
}
/**
* Set the top and bottom margin of the event. The event will release this margin from the top
* and bottom edge. This margin is useful for differentiation consecutive events.
* @param eventMarginVertical The top and bottom margin.
*/
public void setEventMarginVertical(int eventMarginVertical) {
this.mEventMarginVertical = eventMarginVertical;
invalidate();
}
/**
* Returns the first visible day in the week view.
* @return The first visible day in the week view.
*/
public Calendar getFirstVisibleDay() {
return mFirstVisibleDay;
}
/**
* Returns the last visible day in the week view.
* @return The last visible day in the week view.
*/
public Calendar getLastVisibleDay() {
return mLastVisibleDay;
}
/**
* Get the scrolling speed factor in horizontal direction.
* @return The speed factor in horizontal direction.
*/
public float getXScrollingSpeed() {
return mXScrollingSpeed;
}
/**
* Sets the speed for horizontal scrolling.
* @param xScrollingSpeed The new horizontal scrolling speed.
*/
public void setXScrollingSpeed(float xScrollingSpeed) {
this.mXScrollingSpeed = xScrollingSpeed;
}
/**
* Get the earliest day that can be displayed. Will return null if no minimum date is set.
*/
public Calendar getMinDate() {
return mMinDate;
}
/**
* Set the earliest day that can be displayed. This will determine the left horizontal scroll
* limit. The default value is null (allow unlimited scrolling into the past).
*
* @param minDate The new minimum date (pass null for no minimum)
*/
public void setMinDate(Calendar minDate) {
if (minDate == null) {
resetHomeDate();
} else {
minDate.set(Calendar.HOUR_OF_DAY, 0);
minDate.set(Calendar.MINUTE, 0);
minDate.set(Calendar.SECOND, 0);
if (mMaxDate != null && minDate.after(mMaxDate)) {
throw new IllegalArgumentException("minDate cannot be later than maxDate");
}
mHomeDate = minDate;
}
mMinDate = minDate;
mCurrentOrigin.x = 0;
invalidate();
}
/**
* Get the latest day that can be displayed. Will return null if no maximum date is set.
*/
public Calendar getMaxDate() {
return mMaxDate;
}
/**
* Set the latest day that can be displayed. This will determine the right horizontal scroll
* limit. The default value is null (allow unlimited scrolling into the future).
*
* @param maxDate The new maximum date (pass null for no maximum)
*/
public void setMaxDate(Calendar maxDate) {
if (maxDate == null) {
if (mMinDate == null) {
resetHomeDate();
}
} else {
maxDate.set(Calendar.HOUR_OF_DAY, 0);
maxDate.set(Calendar.MINUTE, 0);
maxDate.set(Calendar.SECOND, 0);
if (mMinDate != null && maxDate.before(mMinDate)) {
throw new IllegalArgumentException("maxDate cannot be earlier than minDate");
}
if (mHomeDate.after(maxDate))
mHomeDate = maxDate;
}
mMaxDate = maxDate;
mCurrentOrigin.x = 0;
invalidate();
}
// Functions related to scrolling.
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mCurrentScrollDirection == Direction.HORIZONTAL) {
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
mCurrentScrollDirection = Direction.NONE;
}
return mGestureDetector.onTouchEvent(event);
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
if (Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) < mWidthPerDay + mColumnGap && Math.abs(mScroller.getFinalX() - mScroller.getStartX()) != 0) {
mScroller.forceFinished(true);
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
if(mScroller.getFinalX() < mScroller.getCurrX())
leftDays
else
leftDays++;
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
else {
if (mCurrentFlingDirection == Direction.VERTICAL) mCurrentOrigin.y = mScroller.getCurrY();
else mCurrentOrigin.x = mScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
if (mStickyScroller.computeScrollOffset()) {
mCurrentOrigin.x = mStickyScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
// Public methods.
/**
* Show today on the week view.
*/
public void goToToday() {
Calendar today = Calendar.getInstance();
goToDate(today);
}
/**
* Show a specific day on the week view.
* @param date The date to show.
*/
public void goToDate(Calendar date) {
mScroller.forceFinished(true);
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
if(mAreDimensionsInvalid) {
mScrollToDay = date;
return;
}
mRefreshEvents = true;
mCurrentOrigin.x = getXOriginForDate(date);
invalidate();
}
/**
* Refreshes the view and loads the events again.
*/
public void notifyDatasetChanged(){
mRefreshEvents = true;
invalidate();
}
/**
* Vertically scroll to a specific hour in the week view.
* @param hour The hour to scroll to in 24-hour format. Supported values are 0-24.
*/
public void goToHour(double hour){
if (mAreDimensionsInvalid) {
mScrollToHour = hour;
return;
}
int verticalOffset = 0;
if (hour > 24)
verticalOffset = mHourHeight * 24;
else if (hour > 0)
verticalOffset = (int) (mHourHeight * hour);
if (verticalOffset > mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)
verticalOffset = (int)(mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom);
mCurrentOrigin.y = -verticalOffset;
invalidate();
}
/**
* Get the first hour that is visible on the screen.
* @return The first hour that is visible.
*/
public double getFirstVisibleHour(){
return -mCurrentOrigin.y / mHourHeight;
}
// Interfaces.
public interface EventClickListener {
public void onEventClick(WeekViewEvent event, RectF eventRect);
}
public interface MonthChangeListener {
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth);
}
public interface EventLongPressListener {
public void onEventLongPress(WeekViewEvent event, RectF eventRect);
}
public interface EmptyViewClickListener {
public void onEmptyViewClicked(Calendar time);
}
public interface EmptyViewLongPressListener {
public void onEmptyViewLongPress(Calendar time);
}
public interface ScrollListener {
/**
* Called when the first visible day has changed.
*
* (this will also be called during the first draw of the weekview)
* @param newFirstVisibleDay The new first visible day
* @param oldFirstVisibleDay The old first visible day (is null on the first call).
*/
public void onFirstVisibleDayChanged(Calendar newFirstVisibleDay, Calendar oldFirstVisibleDay);
}
// Helper methods.
/**
* Checks if an integer array contains a particular value.
* @param list The haystack.
* @param value The needle.
* @return True if the array contains the value. Otherwise returns false.
*/
private boolean containsValue(int[] list, int value) {
for (int i = 0; i < list.length; i++){
if (list[i] == value)
return true;
}
return false;
}
/**
* Checks if two times are on the same day.
* @param dayOne The first day.
* @param dayTwo The second day.
* @return Whether the times are on the same day.
*/
private boolean isSameDay(Calendar dayOne, Calendar dayTwo) {
return dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR) && dayOne.get(Calendar.DAY_OF_YEAR) == dayTwo.get(Calendar.DAY_OF_YEAR);
}
}
|
package COSE;
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* @author Jim
*/
public class ASN1 {
/**
* This class is used internal to the ASN.1 decoding functions.
* After decoding there will be one of these for each item in the
* original in the encoded byte array
*/
public static class TagValue {
public int tag;
public byte[] value;
public ArrayList<TagValue> list;
public TagValue(int tagIn, byte[] valueIn) {
tag = tagIn;
value = valueIn;
}
public TagValue(int tagIn, ArrayList<TagValue> listIn) {
tag = tagIn;
list = listIn;
}
@Override
public String toString() {
String t = tagToString(tag);
if(list != null) {
return "TagValue{tag=" + t + ", size = " + list.size() + "}";
} else {
return "TagValue{tag=" + t + ", value=" + bytesToHex(value) + '}';
}
}
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for(byte b: bytes)
sb.append(String.format("%02x", b & 0xff));
return sb.toString();
}
private static String tagToString(int tag) {
switch (tag) {
case 0x2:
return "INTEGER";
case 0x3:
return "BITSTRING";
case 0x4:
return "OCTETSTRING";
case 0x5:
return "NULL";
case 0x6:
return "OBJECTIDENTIFIER";
case 0x30:
return "SEQUENCE";
default:
return Integer.toString(tag);
}
}
}
// 1.2.840.10045.3.1.7
public static final byte[] Oid_secp256r1 = new byte[]{0x06, 0x08, 0x2A, (byte) 0x86, 0x48, (byte) 0xCE, 0x3D, 0x03, 0x01, 0x07};
// 1.3.132.0.34
public static final byte[] Oid_secp384r1 = new byte[]{0x06, 0x05, 0x2B, (byte) 0x81, 0x04, 0x00, 0x22};
// 1.3.132.0.35
public static final byte[] Oid_secp521r1 = new byte[]{0x06, 0x05, 0x2B, (byte) 0x81, 0x04, 0x00, 0x23};
// 1.2.840.10045.2.1
public static final byte[] oid_ecPublicKey = new byte[]{0x06, 0x07, 0x2a, (byte) 0x86, 0x48, (byte) 0xce, 0x3d, 0x2, 0x1};
// 1.3.101.110
public static final byte[] Oid_X25519 = new byte[]{0x6, 3, 0x2b, 101, 110};
// 1.3.101.111
public static final byte[] Oid_X448 = new byte[]{0x6, 3, 0x2b, 101, 111};
// 1.3.101.112
public static final byte[] Oid_Ed25519 = new byte[]{0x6, 0x3, 0x2b, 101, 112};
// 1.3.101.113
public static final byte[] Oid_Ed448 = new byte[]{0x6, 0x3, 0x2b, 101, 113};
// 1.2.840.113549.1.1.1
public static final byte[] Oid_rsaEncryption = new byte[]{0x06, 0x09, 0x2A, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xF7, 0x0D, 0x01, 0x01, 0x01};
private static final byte[] SequenceTag = new byte[]{0x30};
private static final byte[] OctetStringTag = new byte[]{0x4};
private static final byte[] BitStringTag = new byte[]{0x3};
private static final int IntegerTag = 2;
public static boolean isEcdhEddsaOid(byte[] oid) {
return Arrays.equals(oid, ASN1.Oid_Ed25519) || Arrays.equals(oid, ASN1.Oid_Ed448)
|| Arrays.equals(oid, ASN1.Oid_X25519) || Arrays.equals(oid, ASN1.Oid_X448);
}
/**
* Encode a subject public key info structure from an OID and the data bytes
* for the key
* This function assumes that we are encoding an EC Public key.d
*
* @param algorithm - encoded Object Identifier
* @param keyBytes - encoded key bytes
* @return - encoded SPKI
* @throws CoseException - ASN encoding error.
*/
public static byte[] EncodeSubjectPublicKeyInfo(byte[] algorithm, byte[] keyBytes) throws CoseException
{
// SPKI ::= SEQUENCE {
// algorithm SEQUENCE {
// oid = id-ecPublicKey {1 2 840 10045 2}
// namedCurve = oid for algorithm
// subjectPublicKey BIT STRING CONTAINS key bytes
try {
ArrayList<byte[]> xxx = new ArrayList<byte[]>();
xxx.add(algorithm);
xxx.add(new byte[]{3});
xxx.add(ComputeLength(keyBytes.length+1));
xxx.add(new byte[]{0});
xxx.add(keyBytes);
return Sequence(xxx);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.print(e.toString());
throw e;
}
}
/**
* Encode an EC Private key
* @param oid - curve to use
* @param keyBytes - bytes of the key
* @param spki - optional SPKI
* @return encoded private key
* @throws CoseException - from lower level
*/
public static byte[] EncodeEcPrivateKey(byte[] oid, byte[] keyBytes, byte[] spki) throws CoseException
{
// ECPrivateKey ::= SEQUENCE {
// version INTEGER {1}
// privateKey OCTET STRING
// parameters [0] OBJECT IDENTIFIER = named curve
// public key [1] BIT STRING OPTIONAL
ArrayList<byte[]> xxx = new ArrayList<byte[]>();
xxx.add(new byte[]{2, 1, 1});
xxx.add(OctetStringTag);
xxx.add(ComputeLength(keyBytes.length));
xxx.add(keyBytes);
xxx.add(new byte[]{(byte)0xa0});
xxx.add(ComputeLength(oid.length));
xxx.add(oid);
if (spki != null) {
xxx.add(new byte[]{(byte)0xa1});
xxx.add(ComputeLength(spki.length+1));
xxx.add(new byte[]{0});
xxx.add(spki);
}
byte[] ecPrivateKey = Sequence(xxx);
return ecPrivateKey;
}
/*
* Decode an object which is supposed to be a SubjectPublicKeyInfo strucuture
* and check that the right set of fields are in the right place
*
* @param encoding encoded byte string to decode
* @return decoded structure
* @throws CoseException
*/
public static ArrayList<TagValue> DecodeSubjectPublicKeyInfo(byte[] encoding) throws CoseException
{
TagValue spki = DecodeCompound(0, encoding);
if (spki.tag != 0x30) throw new CoseException("Invalid SPKI");
ArrayList<TagValue> tvl = spki.list;
if (tvl.size() != 2) throw new CoseException("Invalid SPKI");
if (tvl.get(0).tag != 0x30) throw new CoseException("Invalid SPKI");
if (tvl.get(0).list.isEmpty() || tvl.get(0).list.size() > 2) {
throw new CoseException("Invalid SPKI");
}
if (tvl.get(0).list.get(0).tag != 6) throw new CoseException("Invalid SPKI");
// tvl.get(0).list.get(1).tag is an ANY so needs to be checked elsewhere
if (tvl.get(1).tag != 3) throw new CoseException("Invalid SPKI");
return tvl;
}
/**
* Decode an array of bytes which is supposed to be an ASN.1 encoded structure.
* This code does the decoding w/o any reference to a schema for what is being
* decoded so it returns type and value pairs rather than converting the values
* to the correct underlying data type.
*
* One oddity that needs to be observed is that Object Identifiers do not have
* the type and length removed from them. This is because we do a byte wise comparison
* and started doing the entire item rather than just the value portion.
*
* M00BUG - we should check that we don't overflow during the decoding process.
*
* @param offset - starting offset in array to begin decoding
* @param encoding - bytes of the ASN.1 encoded value
* @return Decoded structure
* @throws CoseException - ASN.1 encoding errors
*/
public static TagValue DecodeCompound(int offset, byte[] encoding) throws CoseException
{
ArrayList<TagValue> result = new ArrayList<TagValue>();
int retTag = encoding[offset];
// We only decode objects which are compound objects. That means that this bit must be set
if ((encoding[offset] & 0x20) != 0x20) throw new CoseException("Invalid structure");
int[] l = DecodeLength(offset+1, encoding);
int sequenceLength = l[1];
if (offset + sequenceLength > encoding.length) throw new CoseException("Invalid sequence");
offset += l[0]+1;
while (sequenceLength > 0) {
int tag = encoding[offset];
l = DecodeLength(offset+1, encoding);
if (l[1] > sequenceLength) throw new CoseException("Invalid sequence");
if ((tag & 0x20) != 0) {
result.add(DecodeCompound(offset, encoding));
offset += 1 + l[0] + l[1];
sequenceLength -= 1 + l[0] + l[1];
}
else {
// At some point we might want to fix this.
if (tag == 6) {
result.add(new TagValue(tag, Arrays.copyOfRange(encoding, offset, offset+l[1]+l[0]+1)));
}
else {
result.add(new TagValue(tag, Arrays.copyOfRange(encoding, offset+l[0]+1, offset+1+l[0]+l[1])));
}
offset += 1 + l[0] + l[1];
sequenceLength -= 1 + l[0] + l[1];
}
}
return new TagValue(retTag, result);
}
/**
* Decode an array of bytes which is supposed to be an ASN.1 encoded octet string.
*
* @param offset - starting offset in array to begin decoding
* @param encoding - bytes of the ASN.1 encoded value
* @return Decoded structure
* @throws CoseException - ASN.1 encoding errors
*/
public static TagValue DecodeSimple(int offset, byte[] encoding) throws CoseException {
ArrayList<TagValue> result = new ArrayList<TagValue>();
int retTag = encoding[offset];
if (encoding[offset] != 0x04)
throw new CoseException("Invalid structure");
int[] l = DecodeLength(offset + 1, encoding);
int sequenceLength = l[1];
if (offset + 2 + sequenceLength != encoding.length)
throw new CoseException("Invalid sequence");
int tag = encoding[offset];
offset += 1 + l[0];
result.add(new TagValue(tag, Arrays.copyOfRange(encoding, offset, offset + l[1])));
return new TagValue(retTag, result);
}
/**
* Encode a private key into a PKCS#8 private key structure.
*
* @param algorithm - EC curve OID
* @param keyBytes - raw bytes of the key
* @param spki - optional subject public key info structure to include
* @return byte array of encoded bytes
* @throws CoseException - ASN.1 encoding errors
*/
public static byte[] EncodePKCS8(byte[] algorithm, byte[] keyBytes, byte[] spki) throws CoseException
{
// PKCS#8 ::= SEQUENCE {
// version INTEGER {0}
// privateKeyALgorithm SEQUENCE {
// algorithm OID,
// parameters ANY
// privateKey ECPrivateKey,
// attributes [0] IMPLICIT Attributes OPTIONAL
// publicKey [1] IMPLICIT BIT STRING OPTIONAL
try {
ArrayList<byte[]> xxx = new ArrayList<byte[]>();
xxx.add(new byte[]{2, 1, 0});
xxx.add(algorithm);
xxx.add(OctetStringTag);
xxx.add(ComputeLength(keyBytes.length));
xxx.add(keyBytes);
return Sequence(xxx);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.print(e.toString());
throw e;
}
}
/**
*
* Decode a PKCS#8 private key structure, leaving the private key as an octetstring.
* @param encodedData bytes containing the private key
* @return tag/value from the decoded object
* @throws CoseException - ASN.1 encoding errors
*/
public static ArrayList<TagValue> DecodePKCS8Structure(byte[] encodedData) throws CoseException
{
TagValue pkcs8 = DecodeCompound(0, encodedData);
if (pkcs8.tag != 0x30) throw new CoseException("Invalid PKCS8 structure");
ArrayList<TagValue> retValue = pkcs8.list;
if (retValue.size() != 3 && retValue.size() != 4) {
throw new CoseException("Invalid PKCS8 structure");
}
// Version number - we currently only support one version
if (retValue.get(0).tag != IntegerTag && retValue.get(0).value[0] != 0) {
throw new CoseException("Invalid PKCS8 structure");
}
// Algorithm identifier
if (retValue.get(1).tag != 0x30) throw new CoseException("Invalid PKCS8 structure");
if (retValue.get(1).list.isEmpty() || retValue.get(1).list.size() > 2) {
throw new CoseException("Invalid PKCS8 structure");
}
if (retValue.get(1).list.get(0).tag != 6) throw new CoseException("Invalid PKCS8 structure");
// Dont check the next item as it is an ANY
if (retValue.get(2).tag != 4) throw new CoseException("Invalid PKCS8 structure");
// This is attributes, but we are not going to check for correctness.
if (retValue.size() == 4 && retValue.get(3).tag != 0xa0) {
throw new CoseException("Invalid PKCS8 structure");
}
return retValue;
}
/**
* Decode a RSA PKCS#8 private key octet string
*
* @param pkcs8 The decoded PKCS#8 structure
* @return tag/value from the decoded object
* @throws CoseException - ASN.1 encoding errors
*/
public static ArrayList<TagValue> DecodePKCS8RSA(ArrayList<TagValue> pkcs8) throws CoseException {
// Decode the contents of the octet string PrivateKey
byte[] pk = pkcs8.get(2).value;
TagValue pkd = DecodeCompound(0, pk);
ArrayList<TagValue> pkdl = pkd.list;
if (pkd.tag != 0x30) throw new CoseException("Invalid RSAPrivateKey");
if (pkdl.size() < 8 || pkdl.size() > 11) throw new CoseException("Invalid RSAPrivateKey");
// We don't support multi-prime decoding (version 1), but we do support single prime (version 0)
if (pkdl.get(0).tag != IntegerTag && pkcs8.get(0).value[0] != 1) {
throw new CoseException("Invalid RSAPrivateKey");
}
for (TagValue tagValue : pkd.list) {
if(tagValue.tag != IntegerTag) throw new CoseException("Invalid RSAPrivateKey");
}
return pkdl;
}
/**
* Decode an EC PKCS#8 private key octet string
*
* @param pkcs8 The decoded PKCS#8 structure
* @return tag/value from the decoded object
* @throws CoseException - ASN.1 encoding errors
*/
public static ArrayList<TagValue> DecodePKCS8EC(ArrayList<TagValue> pkcs8) throws CoseException {
// Decode the contents of the octet string PrivateKey
byte[] pk = pkcs8.get(2).value;
TagValue pkd;
// First check if it can be decoded as a simple value
if (pk[0] == 0x04) { // ASN.1 Octet string
pkd = DecodeSimple(0, pk);
return pkd.list;
}
// Otherwise proceed to parse as compound value
pkd = DecodeCompound(0, pk);
ArrayList<TagValue> pkdl = pkd.list;
if (pkd.tag != 0x30) throw new CoseException("Invalid ECPrivateKey");
if (pkdl.size() < 2 || pkdl.size() > 4) throw new CoseException("Invalid ECPrivateKey");
if (pkdl.get(0).tag != 2 && pkcs8.get(0).value[0] != 1) {
throw new CoseException("Invalid ECPrivateKey");
}
if (pkdl.get(1).tag != 4) throw new CoseException("Invalid ECPrivateKey");
if (pkdl.size() > 2) {
if ((pkdl.get(2).tag & 0xff) != 0xA0) {
if (pkdl.size() != 3 || (pkdl.get(2).tag & 0xff) != 0xa1) {
throw new CoseException("Invalid ECPrivateKey");
}
} else {
if (pkdl.size() == 4 && (pkdl.get(3).tag & 0xff) != 0xa1) throw new CoseException("Invalid ECPrivateKey");
}
}
return pkdl;
}
public static byte[] EncodeSignature(byte[] r, byte[] s) throws CoseException {
ArrayList<byte[]> x = new ArrayList<byte[]>();
x.add(UnsignedInteger(r));
x.add(UnsignedInteger(s));
return Sequence(x);
}
public static byte[] EncodeOctetString(byte[] data) throws CoseException {
ArrayList<byte[]> x = new ArrayList<byte[]>();
x.add(OctetStringTag);
x.add(ComputeLength(data.length));
x.add(data);
return ToBytes(x);
}
public static byte[] AlgorithmIdentifier(byte[] oid, byte[] params) throws CoseException
{
ArrayList<byte[]> xxx = new ArrayList<byte[]>();
xxx.add(oid);
if (params != null) {
xxx.add(params);
}
return Sequence(xxx);
}
private static byte[] Sequence(ArrayList<byte[]> members) throws CoseException
{
byte[] y = ToBytes(members);
ArrayList<byte[]> x = new ArrayList<byte[]>();
x.add(SequenceTag);
x.add(ComputeLength(y.length));
x.add(y);
return ToBytes(x);
}
private static byte[] UnsignedInteger(byte[] i) throws CoseException {
int pad = 0, offset = 0;
while (offset < i.length && i[offset] == 0) {
offset++;
}
if (offset == i.length) {
return new byte[] {0x02, 0x01, 0x00};
}
if ((i[offset] & 0x80) != 0) {
pad++;
}
// M00BUG if the integer is > 127 bytes long with padding
int length = i.length - offset;
byte[] der = new byte[2 + length + pad];
der[0] = 0x02;
der[1] = (byte)(length + pad);
System.arraycopy(i, offset, der, 2 + pad, length);
return der;
}
private static byte[] ComputeLength(int x) throws CoseException
{
if (x <= 127) {
return new byte[]{(byte)x};
}
else if ( x < 256) {
return new byte[]{(byte) 0x81, (byte) x};
}
throw new CoseException("Error in ASN1.GetLength");
}
private static int[] DecodeLength(int offset, byte[] data) throws CoseException
{
int length;
int i;
if ((data[offset] & 0x80) == 0) return new int[]{1, data[offset]};
if (data[offset] == 0x80) {
throw new CoseException("Indefinite length encoding not supported");
}
length = data[offset] & 0x7f;
int retValue = 0;
for (i=0; i<length; i++) {
retValue = retValue*256 + (data[i+offset+1] & 0xff);
}
return new int[]{length+1, retValue};
}
private static byte[] ToBytes(ArrayList<byte[]> x)
{
int l = 0;
l = x.stream().map((r) -> r.length).reduce(l, Integer::sum);
byte[] b = new byte[l];
l = 0;
for (byte[] r : x) {
System.arraycopy(r, 0, b, l, r.length);
l += r.length;
}
return b;
}
}
|
package Game;
import java.util.*;
public class Game {
private ArrayList<Team> teams;
private ArrayList<Player> players;
private ArrayList<Instruction> instructions;
private ArrayList<Panel> panels;
private ArrayList<String> playerScores;
Team team1;
Team team2;
private int timeRound;
private int bonusCorrectInstructions;
private int substractCorrectInstructions;
public Game(){
final int STARTLEVENS = 3;
final int STARTTIMEROUND = 9;
teams = new ArrayList<Team>();
players = new ArrayList<Player>();
instructions = new ArrayList<Instruction>();
panels = new ArrayList<Panel>();
bonusCorrectInstructions = 3;
substractCorrectInstructions = 5;
team1 = new Team(STARTTIMEROUND, STARTLEVENS);
team2 = new Team(STARTTIMEROUND, STARTLEVENS);
teams.add(team1);
teams.add(team2);
}
/**
* Is called at the beginning of the game
* Check if both teams have the same amount of players
* @return true if they are the same
*/
public boolean startGame(){
// Check if both teams are the same size
if (team1.getPlayers().size() == team2.getPlayers().size()) {
// Panels are given to the teams that compete
return true;
}else {
throw new IllegalArgumentException ("wrong sizes");
}
}
/**
* Call this method to start a new round
* Every value in the game gets a reset
*/
public boolean newRound(){
// returns default values
reset();
team1.setPlayerPanels(panels);
team2.setPlayerPanels(panels);
return false;
}
/**
*
* @param team The team that won the game
* @return a list of players from the winning team + there score
*/
public ArrayList<String> endGame(Team team){
// Sorts the players by score
playerScores = new ArrayList<String>();
List<Player> sortedWinningTeam = team.sortedPlayerByScore();
if (teams.size() <= 0)
playerScores.add("You won!");
else
playerScores.add("You lost!");
if (sortedWinningTeam != null) {
for (Player p : sortedWinningTeam) {
playerScores.add(p.getName() + ": " + p.getScore());
}
return playerScores;
}
else
return null;
}
/**
* When joinin a lobby the joinen player is set into the team with the least amount of players
*
* @param player De player that is joining the lobby
*
*/
public boolean addPlayerToTeam(Player player){
// Adds players automaticly to a team when they join a lobby
Team team = null;
teams.size();
for(int i=0; i<teams.size()-1; i++){
team = teams.get(i);
if (teams.get(i).getPlayers().size() > teams.get(i+1).getPlayers().size()){
team = teams.get(i+1);
}
}
return team.addPlayerToTeam(player);
}
/**
* Changing the player to the other team
* @param player The player that wants to join the other team
*/
public boolean changeTeam(Player player){
Team currentTeam = player.getTeam();
int idTeam = teams.indexOf(currentTeam);
if (currentTeam.removePlayer(player)){
if (idTeam+1 < teams.size()) {
return teams.get(idTeam+1).addPlayerToTeam(player);
}else {
return teams.get(0).addPlayerToTeam(player);
}
}else {
return false;
}
}
/**
* When a team reaches a certain winstreak the game checks if they should recieve bonus time
* @param team The team that gets checked
*/
private boolean addTime(Team team){
if (team.getCorrectInstruction() == bonusCorrectInstructions){
team.setTime(team.getTime() + 1);
return true;
}
return false;
}
/**
* When the team has las then 3 seconds it should lose a life
* @param losingTeam The team that gets a check if they should lose a life
* @return true if the given time had less then 3 seconds
*/
public boolean subtractLives(Team losingTeam){
if (losingTeam.getTime() <= 3) {
losingTeam.substractLives();
if (losingTeam.getLives() <= 0) {
// Remove the team from the teams in the game
teams.remove(losingTeam);
// End the game for the given team
endGame(losingTeam);
}
else{
newRound();
}
return true;
}
else
return false;
}
/**
* If the team has a certain winstreak the other them should get less time for there upcomming instructions
* @param currentTeam The team that gets checked
*/
public boolean subtractTime(Team currentTeam){
for (Team t : teams) {
// Check if the team has got enough correct awnsers
if (!t.equals(currentTeam) && currentTeam.getCorrectInstruction() >= substractCorrectInstructions){
Team otherTeam = t;
// Other team gets a time penalty
otherTeam.setTime(otherTeam.getTime() - 1);
// Check if it is game over for the other team
subtractLives(otherTeam);
// Reset correct constructions to 0
currentTeam.setCorrectInstruction(0);
break;
}
}
return true;
}
/**
* Check if the executed instrucctions was correct and give the player a new one
* @param donePanel The panel that has been pressed
* @param player The player that gets checked
*/
public boolean checkInstruction(Panel donePanel, Player player){ //player kan gevonden worden door op panel te zoeken
Team t = player.getTeam();
int currentCorrect = t.getCorrectInstruction();
boolean instructionCorrect = false;
for (Player p : t.getPlayers()) {
if (p.checkCorrectPanel(donePanel)) {
t.setCorrectInstruction(currentCorrect + 1);
addTime(t);
instructionCorrect = true;
} else {
t.setCorrectInstruction(0);
}
}
return instructionCorrect;
}
/**
* Reset values from both teams
*/
private boolean reset(){
// Voor alle teams de waardes naar standaard terug zetten
for (Team t : teams) {
if (!t.resetTeam()){
return false;
}
}
return true;
}
/**
* Gives a player a new instruction
* @param player The player that needs a new instruction
*/
private Instruction givePlayerInstructions(Player player) {
Team playerTeam = player.getTeam();
int maxSize = playerTeam.getPlayerPanels().size();
Random random = new Random();
// Panels that are in use
ArrayList<Panel> usedPanelNumbers = new ArrayList<Panel>();
// Panels that are not in use and that cannot be chosen
ArrayList<Panel> unusedPanelNumbers = playerTeam.getPlayerPanels();
// Gets all the panels wich are used by the team of the player
for (Player p : playerTeam.getPlayers()) {
usedPanelNumbers.add(p.getInstructions().getPanel());
}
// Removes all the panels that are in use so only the available panels remain
for (Panel p : usedPanelNumbers) {
unusedPanelNumbers.remove(p);
}
// gets a random panel from the list of panels
Panel panel = unusedPanelNumbers.get(random.nextInt(maxSize));
// Add the random instruction to the player
Instruction instuction = panel.getInstruction();
player.setInstructions(instuction);
// Returns the instruction
return instuction;
}
}
|
package uworkers.tests;
import uworkers.api.Subscriber;
import uworkers.api.Worker;
public class Consumers {
@Worker( name = "test.worker" )
public void receiveWorker( SearchMessage message ) {
System.out.println( message.query() );
}
@Subscriber( topic = "test.subscriber", name = "secret")
public void subscribeFor( SearchMessage message ) {
System.out.println( message.query() );
}
}
|
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
import static spark.Spark.get;
import spark.Request;
public class MapServer {
public MapServer(){
// CreateSampleData();
getCountryInfo();
}
public HashMap<String,CountryInfo> CreateSampleData()
{
CountryInfo china = new CountryInfo("China","136,782,000","Asia","Beijing","Mandarin","RMB","Shanghai","Guangzhou","The Great Wall","the Palace Museum");
CountryInfo us = new CountryInfo("United States of America","322,369,319","North America","Washington, D.C.","English","United States dollar","New York City","Los Angeles","Grand Canyon","Statue of Liberty");
CountryInfo canada = new CountryInfo("Canada","36,048,521","North America","Ottawa","English and French","Canadian dollar","Vancouver","Toronto","Niagara Falls","Churchill");
HashMap<String,CountryInfo> countryList = new HashMap<>();
countryList.put(china.getcName(), china);
countryList.put(us.getcName(), us);
countryList.put(canada.getcName(), canada);
return countryList;
}
private void getCountryInfo(){
get("/api/mapInfo/:name", (req, res) -> {
String name = req.params(":name");
HashMap<String,CountryInfo> countryList = new HashMap<>();
countryList = CreateSampleData();
CountryInfo country = new CountryInfo();
if(!countryList.containsKey(name))
{
country = null;
}
else
{
country = countryList.get(name);
}
String xml = "";
try {
if(null != country)
{
xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Country>" +
"<name>"+country.getcName()+"</name>" +
"<population>"+country.getPopulation()+"</populatino>" +
"<continent>"+country.getContinent()+"</continet>" +
"<capital>"+country.getCapital()+"</capital>" +
"<language>"+country.getLanguage()+"</language>" +
"<currency>"+country.getCurrency()+"</currency>" +
"<poi1>"+country.getPoi1()+"</poi1>" +
"<poi2>"+country.getPoi2()+"</poi2>" +
"<poi3>"+country.getPoi3()+"</poi3>" +
"<poi4>"+country.getPoi4()+"</poi4>" +
"</Country>";
}
else
{
xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Country>" +
"<name>information is not available yet</name>" +
"<population>information is not available yet</population>" +
"<continent>information is not available yet</continet>" +
"<capital>information is not available yet</capital>" +
"<language>information is not available yet</language>" +
"<currency>information is not available yet</currency>" +
"<poi1>information is not available yet</poi1>" +
"<poi2>information is not available yet</poi2>" +
"<poi3>information is not available yet</poi3>" +
"<poi4>information is not available yet</poi4>" +
"</Country>";
}
}
catch (NullPointerException e)
{
System.out.println("Object=null");
}
res.type("text/xml");
return xml;
});
}
}
|
package com.jetbrains.python.validation;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.actions.*;
import com.jetbrains.python.console.PydevConsoleRunner;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyQualifiedName;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
/**
* User : catherine
*/
public abstract class CompatibilityVisitor extends PyAnnotator {
protected List<LanguageLevel> myVersionsToProcess;
private String myCommonMessage = "Python version ";
public CompatibilityVisitor(List<LanguageLevel> versionsToProcess) {
myVersionsToProcess = versionsToProcess;
}
@Override
public void visitPyDictCompExpression(PyDictCompExpression node) {
super.visitPyDictCompExpression(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (!languageLevel.supportsSetLiterals()) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
commonRegisterProblem(message, " not support dictionary comprehensions", len, node, new ConvertDictCompQuickFix(), false);
}
@Override
public void visitPySetLiteralExpression(PySetLiteralExpression node) {
super.visitPySetLiteralExpression(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (!languageLevel.supportsSetLiterals()) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
commonRegisterProblem(message, " not support set literal expressions", len, node, new ConvertSetLiteralQuickFix(), false);
}
@Override
public void visitPySetCompExpression(PySetCompExpression node) {
super.visitPySetCompExpression(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (!languageLevel.supportsSetLiterals()) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
commonRegisterProblem(message, " not support set comprehensions", len, node, null, false);
}
@Override
public void visitPyExceptBlock(PyExceptPart node) {
super.visitPyExceptBlock(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
PyExpression exceptClass = node.getExceptClass();
if (exceptClass != null) {
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24) || myVersionsToProcess.contains(LanguageLevel.PYTHON25)) {
PsiElement element = exceptClass.getNextSibling();
while (element instanceof PsiWhiteSpace) {
element = element.getNextSibling();
}
if (element != null && "as".equals(element.getText())) {
registerProblem(node, myCommonMessage + "2.4, 2.5 do not support this syntax.");
}
}
int len = 0;
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (languageLevel.isPy3K()) {
PsiElement element = exceptClass.getNextSibling();
while (element instanceof PsiWhiteSpace) {
element = element.getNextSibling();
}
if (element != null && ",".equals(element.getText())) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
}
commonRegisterProblem(message, " not support this syntax.", len, node, new ReplaceExceptPartQuickFix());
}
}
@Override
public void visitPyImportStatement(PyImportStatement node) {
super.visitPyImportStatement(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
PyIfStatement ifParent = PsiTreeUtil.getParentOfType(node, PyIfStatement.class);
if (ifParent != null)
return;
PyImportElement[] importElements = node.getImportElements();
int len = 0;
String moduleName = "";
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
for (PyImportElement importElement : importElements) {
final PyQualifiedName qName = importElement.getImportedQName();
if (qName != null) {
if (!languageLevel.isPy3K()) {
if (qName.matches("builtins")) {
len = appendLanguageLevel(message, len, languageLevel);
moduleName = "builtins";
}
}
else {
if (qName.matches("__builtin__")) {
len = appendLanguageLevel(message, len, languageLevel);
moduleName = "__builtin__";
}
}
}
}
}
commonRegisterProblem(message, " not have module " + moduleName, len, node, new ReplaceBuiltinsQuickFix());
}
@Override
public void visitPyStarExpression(PyStarExpression node) {
super.visitPyStarExpression(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (!languageLevel.isPy3K()) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
commonRegisterProblem(message, " not support this syntax. Starred expressions are not allowed as assignment targets in Python 2",
len, node, null);
}
@Override
public void visitPyBinaryExpression(PyBinaryExpression node) {
super.visitPyBinaryExpression(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
if (node.isOperator("<>")) {
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (languageLevel.isPy3K()) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
commonRegisterProblem(message, " not support <>, use != instead.", len, node, new ReplaceNotEqOperatorQuickFix());
}
}
@Override
public void visitPyNumericLiteralExpression(final PyNumericLiteralExpression node) {
super.visitPyNumericLiteralExpression(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
LocalQuickFix quickFix = null;
StringBuilder message = new StringBuilder(myCommonMessage);
String suffix = "";
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (languageLevel.isPy3K()) {
if (!node.isIntegerLiteral()) {
continue;
}
final String text = node.getText();
if (text.endsWith("l") || text.endsWith("L")) {
len = appendLanguageLevel(message, len, languageLevel);
suffix = " not support a trailing \'l\' or \'L\'.";
quickFix = new RemoveTrailingLQuickFix();
}
if (text.length() > 1 && text.charAt(0) == '0') {
final char c = Character.toLowerCase(text.charAt(1));
if (c != 'o' && c != 'b' && c != 'x') {
boolean isNull = true;
for (char a : text.toCharArray()) {
if ( a != '0') {
isNull = false;
break;
}
}
if (!isNull) {
len = appendLanguageLevel(message, len, languageLevel);
quickFix = new ReplaceOctalNumericLiteralQuickFix();
suffix = " not support this syntax. It requires '0o' prefix for octal literals";
}
}
}
}
}
commonRegisterProblem(message, suffix, len, node, quickFix);
}
@Override
public void visitPyStringLiteralExpression(final PyStringLiteralExpression node) {
super.visitPyStringLiteralExpression(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (languageLevel.isPy3K()) {
final String text = node.getText();
if (text.startsWith("u") || text.startsWith("U")) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
}
commonRegisterProblem(message, " not support a leading \'u\' or \'U\'.", len, node, new RemoveLeadingUQuickFix());
}
@Override
public void visitPyListCompExpression(final PyListCompExpression node) {
super.visitPyListCompExpression(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
boolean tmp = UnsupportedFeaturesUtil.visitPyListCompExpression(node, languageLevel);
if (tmp) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
for (ComprhForComponent forComponent : node.getForComponents()) {
final PyExpression iteratedList = forComponent.getIteratedList();
commonRegisterProblem(message, " not support this syntax in list comprehensions.", len, iteratedList,
new ReplaceListComprehensionsQuickFix());
}
}
@Override
public void visitPyRaiseStatement(PyRaiseStatement node) {
super.visitPyRaiseStatement(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
boolean hasNoArgs = UnsupportedFeaturesUtil.raiseHasNoArgs(node, languageLevel);
if (hasNoArgs) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
commonRegisterProblem(message, " not support this syntax. Raise with no arguments can only be used in an except block",
len, node, null);
len = 0;
message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
boolean hasTwoArgs = UnsupportedFeaturesUtil.raiseHasMoreThenOneArg(node, languageLevel);
if (hasTwoArgs) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
commonRegisterProblem(message, " not support this syntax.",
len, node, new ReplaceRaiseStatementQuickFix());
}
@Override
public void visitPyReprExpression(PyReprExpression node) {
super.visitPyReprExpression(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (languageLevel.isPy3K()) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
commonRegisterProblem(message, " not support backquotes, use repr() instead",
len, node, new ReplaceBackquoteExpressionQuickFix());
}
@Override
public void visitPyWithStatement(PyWithStatement node) {
super.visitPyWithStatement(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
Set<PyWithItem> problemItems = new HashSet<PyWithItem>();
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (languageLevel == LanguageLevel.PYTHON24) {
registerProblem(node, "Python version 2.4 doesn't support this syntax.");
}
else if (!languageLevel.supportsSetLiterals()) {
final PyWithItem[] items = node.getWithItems();
if (items.length > 1) {
for (int j = 1; j < items.length; j++) {
if (!problemItems.isEmpty())
message.append(", ");
message.append(languageLevel.toString());
problemItems.add(items [j]);
}
}
}
}
message.append(" do not support multiple context managers");
for (PyWithItem item : problemItems) {
registerProblem(item, message.toString());
}
}
@Override
public void visitPyClass(PyClass node) { //PY-2719
super.visitPyClass(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
PyArgumentList list = node.getSuperClassExpressionList();
if (list != null && list.getArguments().length == 0)
registerProblem(list, "Python version 2.4 does not support this syntax.");
}
}
@Override
public void visitPyPrintStatement(PyPrintStatement node) {
super.visitPyPrintStatement(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
if (shouldBeCompatibleWithPy3()) {
boolean hasProblem = false;
PsiElement[] arguments = node.getChildren();
for (PsiElement element : arguments) {
if (!((element instanceof PyParenthesizedExpression) || (element instanceof PyTupleExpression))) {
hasProblem = true;
break;
}
}
if (hasProblem || arguments.length == 0)
registerProblem(node, "Python version >= 3.0 do not support this syntax. The print statement has been replaced with a print() function",
new CompatibilityPrintCallQuickFix());
}
}
@Override
public void visitPyFromImportStatement(PyFromImportStatement node) {
super.visitPyFromImportStatement(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
PyReferenceExpression importSource = node.getImportSource();
if (importSource != null) {
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) { //PY-2793
PsiElement prev = importSource.getPrevSibling();
if (prev != null && prev.getNode().getElementType() == PyTokenTypes.DOT)
registerProblem(node, "Python version 2.4 doesn't support this syntax.");
}
}
else {
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24))
registerProblem(node, "Python version 2.4 doesn't support this syntax.");
}
}
@Override
public void visitPyAssignmentStatement(PyAssignmentStatement node) {
super.visitPyAssignmentStatement(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
PyExpression assignedValue = node.getAssignedValue();
if (assignedValue instanceof PyConditionalExpression) // PY-2792
registerProblem(node, "Python version 2.4 doesn't support this syntax.");
Stack<PsiElement> st = new Stack<PsiElement>(); // PY-2796
if (assignedValue != null)
st.push(assignedValue);
while (!st.isEmpty()) {
PsiElement el = st.pop();
if (el instanceof PyYieldExpression)
registerProblem(node, "Python version 2.4 doesn't support this syntax. " +
"In Python <= 2.4, yield was a statement; it didn't return any value.");
else {
for (PsiElement e : el.getChildren())
st.push(e);
}
}
}
}
@Override
public void visitPyTryExceptStatement(PyTryExceptStatement node) { // PY-2795
super.visitPyTryExceptStatement(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
PyExceptPart[] excepts = node.getExceptParts();
PyFinallyPart finallyPart = node.getFinallyPart();
if (excepts.length != 0 && finallyPart != null)
registerProblem(node, "Python version 2.4 doesn't support this syntax. You could use a finally block to ensure " +
"that code is always executed, or one or more except blocks to catch specific exceptions.");
}
}
@Override
public void visitPyReferenceExpression(PyReferenceExpression node) {
super.visitPyElement(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
if (shouldBeCompatibleWithPy3()) {
if (PyNames.BASESTRING.equals(node.getText())) {
PsiElement res = node.getReference().resolve();
if (res != null) {
ProjectFileIndex ind = ProjectRootManager.getInstance(node.getProject()).getFileIndex();
PsiFile file = res.getContainingFile();
if (file != null && ind.isInLibraryClasses(file.getVirtualFile())) {
registerProblem(node, "basestring type is not available in py3");
}
} else {
registerProblem(node, "basestring type is not available in py3");
}
}
}
}
@Override
public void visitPyCallExpression(PyCallExpression node) {
super.visitPyCallExpression(node);
if (PydevConsoleRunner.isInPydevConsole(node)) return;
int len = 0;
StringBuilder message = new StringBuilder(myCommonMessage);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (!languageLevel.isPy3K()) {
final PsiElement firstChild = node.getFirstChild();
if (firstChild != null) {
final String name = firstChild.getText();
if (PyNames.SUPER.equals(name)) {
final PyArgumentList argumentList = node.getArgumentList();
if (argumentList != null && argumentList.getArguments().length == 0) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
}
}
}
commonRegisterProblem(message, " not support this syntax. super() should have arguments in Python 2",
len, node, null);
}
private boolean shouldBeCompatibleWithPy3() {
if (myVersionsToProcess.contains(LanguageLevel.PYTHON30) || myVersionsToProcess.contains(LanguageLevel.PYTHON31)
|| myVersionsToProcess.contains(LanguageLevel.PYTHON32))
return true;
return false;
}
protected abstract void registerProblem(PsiElement node, String s, LocalQuickFix localQuickFix, boolean asError);
protected void registerProblem(PsiElement node, String s, LocalQuickFix localQuickFix) {
registerProblem(node, s, localQuickFix, true);
}
protected void registerProblem(PsiElement node, String s) {
registerProblem(node, s, null);
}
protected void setVersionsToProcess(List<LanguageLevel> versionsToProcess) {
myVersionsToProcess = versionsToProcess;
}
protected void commonRegisterProblem(StringBuilder initMessage, String suffix,
int len, PyElement node, LocalQuickFix localQuickFix) {
commonRegisterProblem(initMessage, suffix, len, node, localQuickFix, true);
}
protected void commonRegisterProblem(StringBuilder initMessage, String suffix,
int len, PyElement node, LocalQuickFix localQuickFix, boolean asError) {
initMessage.append(" do");
if (len == 1)
initMessage.append("es");
initMessage.append(suffix);
if (len != 0)
registerProblem(node, initMessage.toString(), localQuickFix, asError);
}
protected static int appendLanguageLevel(StringBuilder message, int len, LanguageLevel languageLevel) {
if (len != 0)
message.append(", ");
message.append(languageLevel.toString());
return ++len;
}
@Override
public void visitPyNonlocalStatement(PyNonlocalStatement node) {
if (PydevConsoleRunner.isInPydevConsole(node)) return;
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24) || myVersionsToProcess.contains(LanguageLevel.PYTHON25) ||
myVersionsToProcess.contains(LanguageLevel.PYTHON26) || myVersionsToProcess.contains(LanguageLevel.PYTHON27)) {
registerProblem(node, "nonlocal keyword available only since py3", null, false);
}
}
}
|
package com.aldebaran.qi;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.aldebaran.qi.serialization.SignatureUtilities;
/**
* Class that exposes directly an {@link AnyObject} that can be manipulated.
* <p>
* There is only one {@link AnyObject} per DynamicObjectBuilder, the object
* method always returns the same instance.
* <p>
* This class is typically used to subscribe a new {@link QiService} to a
* {@link Session}
*/
public class DynamicObjectBuilder {
static {
// Loading native C++ libraries.
if (!EmbeddedTools.LOADED_EMBEDDED_LIBRARY) {
EmbeddedTools loader = new EmbeddedTools();
loader.loadEmbeddedLibraries();
}
}
private final long _p;
private native long create();
private native void destroy(long pObject);
private native AnyObject object(long pObjectBuilder);
private native void advertiseMethod(long pObjectBuilder, String method, Object instance, String className,
String description) throws AdvertisementException;
private native void advertiseSignal(long pObjectBuilder, String eventSignature) throws AdvertisementException;
private native void advertiseProperty(long pObjectBuilder, String name, Class<?> propertyBase)
throws AdvertisementException;
private native void setThreadSafeness(long pObjectBuilder, boolean isThreadSafe);
// / Possible thread models for an object
/**
* Enum to declare the thread-safeness state of an {@link AnyObject}
* instance.
* <p>
* Use <b>MultiThread</b> if your object is expected to be thread-safe.
* Method calls will potentially occur in parallel in multiple threads.
* <p>
* Use <b>SingleThread</b> to make your object non-thread-safe. All method
* calls must occur in the same thread.
*/
public enum ObjectThreadingModel {
/**
* AnyObject is not thread safe, all method calls must occur in the same
* thread
**/
SingleThread,
/**
* AnyObject is thread safe, multiple calls can occur in different
* threads in parallel
**/
MultiThread
}
/**
* Create the builder
*/
public DynamicObjectBuilder() {
_p = create();
}
/**
* Bind method from a qimessaging.service to GenericObject.<br>
* The given signature <b>MUST</b> be a libqi type signature <b>AND</b> use
* Java compatible types :<br>
* <table border=1>
* <tr>
* <th>libqi</th>
* <th>Java</th>
* </tr>
* <tr>
* <td><center>b</center></td>
* <td>{@link Boolean}</td>
* </tr>
* <tr>
* <td><center>c</center></td>
* <td>{@link Character}</td>
* </tr>
* <tr>
* <td><center>v</center></td>
* <td>void</td>
* </tr>
* <tr>
* <td><center>i</center></td>
* <td>{@link Integer}</td>
* </tr>
* <tr>
* <td><center>l</center></td>
* <td>{@link Long}</td>
* </tr>
* <tr>
* <td><center>f</center></td>
* <td>{@link Float}</td>
* </tr>
* <tr>
* <td><center>d</center></td>
* <td>{@link Double}</td>
* </tr>
* <tr>
* <td><center>s</center></td>
* <td>{@link String}</td>
* </tr>
* <tr>
* <td><center>o</center></td>
* <td>{@link Object}</td>
* </tr>
* <tr>
* <td><center>m</center></td>
* <td>{@link Object} (dynamic)</td>
* </tr>
* <tr>
* <td><center>[<type>]</center></td>
* <td>{@link java.util.ArrayList}</td>
* </tr>
* <tr>
* <td><center>{<key><type>}</center></td>
* <td>{@link java.util.Map}</td>
* </tr>
* <tr>
* <td><center>(<type>....)</center></td>
* <td>{@link Tuple}</td>
* </tr>
* </table>
* <br>
* <b>WARNING</b> :
* <ul>
* <li>If method not found, nothing happen.</li>
* <li>Be sure the method is unique in name, if two methods with same name
* and different signature, you can't be sure it choose the good one</li>
* <li>If method choose (by name) have not the correct Java signature, it
* will crash later (when call)</li>
* </ul>
*
* @param methodSignature
* Signature of method to bind. It must be a valid libqi type
* signature
* @param service
* Service implementing method.
* @param description
* Method description
* @throws AdvertisementException
* If signature is not a valid libqi signature type.
* @throws SecurityException
* If given service instance of a class protect from reflection
*/
public void advertiseMethod(String methodSignature, QiService service, String description) {
final Class<?> serviceClass = service.getClass();
final Method[] methods = serviceClass.getDeclaredMethods();
final String serviceClassName = serviceClass.getName().replace('.', '/');
for (final Method method : methods) {
// FIXME this is very fragile
// If method name match signature
if (methodSignature.contains(method.getName())) {
advertiseMethod(_p, methodSignature, service, serviceClassName, description);
return;
}
}
}
/**
* Advertise a signal with its callback signature.<br>
* The given signature <b>MUST</b> be a libqi type signature
*
* @param signalSignature
* Signature of available callback.
* @throws AdvertisementException
* If signature not a valid libqi signature type.
* @throws Exception
* If GenericObject is not initialized internally.
*/
public void advertiseSignal(String signalSignature) throws Exception {
advertiseSignal(_p, signalSignature);
}
/**
* Advertise a property
*
* @param name
* Property name
* @param propertyBase
* Class warp the property
*/
public void advertiseProperty(String name, Class<?> propertyBase) {
advertiseProperty(_p, name, propertyBase);
}
/**
* Declare the thread-safeness state of an instance
*
* @param threadModel
* if set to ObjectThreadingModel.MultiThread, your object is
* expected to be thread safe, and calls to its method will
* potentially occur in parallel in multiple threads. If false,
* qimessaging will use a per-instance mutex to prevent multiple
* calls at the same time.
*/
public void setThreadingModel(ObjectThreadingModel threadModel) {
setThreadSafeness(_p, threadModel == ObjectThreadingModel.MultiThread);
}
/**
* Instantiate new AnyObject after builder template.
*
* @return AnyObject
* @see AnyObject
*/
public AnyObject object() {
return object(_p);
}
/**
* Called by garbage collector Finalize is overridden to manually delete C++
* data
*/
@Override
protected void finalize() throws Throwable {
destroy(_p);
super.finalize();
}
/**
* Advertise methods from interface.<br>
* All methods of given interface are automatically registered.<br>
* To specify a description on method add
* {@link AdvertisedMethodDescription} annotation on the method.
*
* @param <INTERFACE>
* Interface type that specifies the list of methods to expose.
* @param <INSTANCE>
* Instance type of interface.
* @param interfaceClass
* Interface that specifies the list of methods to expose.
* @param instance
* Instance of interface implementation.
* @return Interface implementation to use for call methods.
*/
@SuppressWarnings("unchecked")
public <INTERFACE, INSTANCE extends INTERFACE> INTERFACE advertiseMethods(final Class<INTERFACE> interfaceClass,
final INSTANCE instance) {
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(interfaceClass.getName() + " is not an interface!");
}
if (instance == null) {
throw new NullPointerException("instance MUST NOT be null!");
}
String description;
AdvertisedMethodDescription advertisedMethodDescription;
for (final Method method : interfaceClass.getDeclaredMethods()) {
description = method.toString();
advertisedMethodDescription = method.getAnnotation(AdvertisedMethodDescription.class);
if (advertisedMethodDescription != null) {
description = advertisedMethodDescription.value();
}
this.advertiseMethod(this._p, SignatureUtilities.computeSignatureForMethod(method), instance,
interfaceClass.getName(), description);
}
return (INTERFACE) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] { interfaceClass },
new AdvertisedMethodCaller<INTERFACE>(this));
}
}
|
package VASSAL.build.module.map;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.AutoConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.GameComponent;
import VASSAL.build.module.Map;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.command.Command;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.Configurer;
import VASSAL.configure.ConfigurerFactory;
import VASSAL.configure.IconConfigurer;
import VASSAL.configure.StringArrayConfigurer;
import VASSAL.configure.StringEnum;
import VASSAL.configure.VisibilityCondition;
import VASSAL.counters.Decorator;
import VASSAL.counters.GamePiece;
import VASSAL.counters.Stack;
import VASSAL.i18n.Resources;
import VASSAL.tools.LaunchButton;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.UniqueIdManager;
import VASSAL.tools.image.ImageUtils;
import VASSAL.tools.imageop.AbstractTileOpImpl;
import VASSAL.tools.imageop.ImageOp;
import VASSAL.tools.imageop.Op;
/**
* Draw shaded regions on a map.
*
* @author Brent Easton
*/
public class MapShader extends AbstractConfigurable implements GameComponent, Drawable, UniqueIdManager.Identifyable {
public static final String NAME = "name";
public static final String ALWAYS_ON = "alwaysOn";
public static final String STARTS_ON = "startsOn";
public static final String HOT_KEY = "hotkey";
public static final String ICON = "icon";
public static final String BUTTON_TEXT = "buttonText";
public static final String TOOLTIP = "tooltip";
public static final String BOARDS = "boards";
public static final String BOARD_LIST = "boardList";
public static final String ALL_BOARDS = "Yes";
public static final String EXC_BOARDS = "No, exclude Boards in list";
public static final String INC_BOARDS = "No, only shade Boards in List";
protected static UniqueIdManager idMgr = new UniqueIdManager("MapShader");
protected LaunchButton launch;
protected boolean alwaysOn = false;
protected boolean startsOn = false;
protected String boardSelection = ALL_BOARDS;
protected String[] boardList = new String[0];
protected boolean shadingVisible;
protected boolean scaleImage;
protected Map map;
protected String id;
protected Area boardClip = null;
public static final String TYPE = "type";
public static final String DRAW_OVER = "drawOver";
public static final String PATTERN = "pattern";
public static final String COLOR = "color";
public static final String IMAGE = "image";
public static final String SCALE_IMAGE = "scaleImage";
public static final String OPACITY = "opacity";
public static final String BORDER = "border";
public static final String BORDER_COLOR = "borderColor";
public static final String BORDER_WIDTH = "borderWidth";
public static final String BORDER_OPACITY = "borderOpacity";
public static final String BG_TYPE = "Background";
public static final String FG_TYPE = "Foreground";
public static final String TYPE_25_PERCENT = "25%";
public static final String TYPE_50_PERCENT = "50%";
public static final String TYPE_75_PERCENT = "75%";
public static final String TYPE_SOLID = "100% (Solid)";
public static final String TYPE_IMAGE = "Custom Image";
protected String imageName;
protected Color color = Color.BLACK;
protected String type = FG_TYPE;
protected boolean drawOver = false;
protected String pattern = TYPE_25_PERCENT;
protected int opacity = 100;
protected boolean border = false;
protected Color borderColor = Color.BLACK;
protected int borderWidth = 1;
protected int borderOpacity = 100;
protected Area shape;
protected Rectangle patternRect = new Rectangle();
protected ImageOp srcOp;
protected TexturePaint texture = null;
protected java.util.Map<Double,TexturePaint> textures = new HashMap<>();
protected AlphaComposite composite = null;
protected AlphaComposite borderComposite = null;
protected BasicStroke stroke = null;
public MapShader() {
launch = new LaunchButton(
"Shade", TOOLTIP, BUTTON_TEXT, HOT_KEY, ICON, e -> toggleShading()
);
launch.setEnabled(false);
setLaunchButtonVisibility();
setConfigureName("Shading");
reset();
}
@Override
public void draw(Graphics g, Map map) {
if (!shadingVisible) {
return;
}
Area area = getShadeShape(map);
if (area.isEmpty()) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final double zoom = map.getZoom() * os_scale;
if (zoom != 1.0) {
area = new Area(AffineTransform.getScaleInstance(zoom, zoom)
.createTransformedShape(area));
}
final Composite oldComposite = g2d.getComposite();
final Color oldColor = g2d.getColor();
final Paint oldPaint = g2d.getPaint();
g2d.setComposite(getComposite());
g2d.setColor(getColor());
g2d.setPaint(getTexture(zoom));
g2d.fill(area);
if (border) {
final Stroke oldStroke = g2d.getStroke();
g2d.setComposite(getBorderComposite());
g2d.setStroke(getStroke(zoom));
g2d.setColor(getBorderColor());
g2d.draw(area);
g2d.setStroke(oldStroke);
}
g2d.setComposite(oldComposite);
g2d.setColor(oldColor);
g2d.setPaint(oldPaint);
}
/**
* Get/Build the AlphaComposite used to draw the semi-transparent shade/
*/
protected AlphaComposite getComposite() {
if (composite == null) {
buildComposite();
}
return composite;
}
protected void buildComposite() {
composite =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity / 100.0f);
}
protected AlphaComposite getBorderComposite() {
if (borderComposite == null) {
borderComposite = buildBorderComposite();
}
return borderComposite;
}
protected AlphaComposite buildBorderComposite() {
return AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, borderOpacity / 100.0f);
}
/**
* Get/Build the shape of the shade.
*/
protected Area getShadeShape(Map map) {
final Area myShape = type.equals(FG_TYPE) ?
new Area() : new Area(getBoardClip());
Arrays.stream(map.getPieces()).forEach(p -> checkPiece(myShape, p));
return myShape;
}
protected void checkPiece(Area area, GamePiece piece) {
if (piece instanceof Stack) {
Stack s = (Stack) piece;
s.asList().forEach(gamePiece -> checkPiece(area, gamePiece));
}
else {
ShadedPiece shaded = (ShadedPiece) Decorator.getDecorator(piece,ShadedPiece.class);
if (shaded != null) {
Area shape = shaded.getArea(this);
if (shape != null) {
if (type.equals(FG_TYPE)) {
area.add(shape);
}
else {
area.subtract(shape);
}
}
}
}
}
/**
* Get/Build the repeating rectangle used to generate the shade texture
* pattern.
* @deprecated Use {@link #getShadePattern(double)} instead.
*/
@Deprecated
protected BufferedImage getShadePattern() {
return getShadePattern(1.0);
}
protected BufferedImage getShadePattern(double zoom) {
if (srcOp == null) {
buildShadePattern();
}
return (zoom == 1.0 ? srcOp : Op.scale(srcOp, zoom)).getImage();
}
/*
* @deprecated Use {@link #getPatternRect(double)} instead.
*/
@Deprecated
protected Rectangle getPatternRect() {
return patternRect;
}
protected Rectangle getPatternRect(double zoom) {
return zoom == 1.0 ? patternRect :
new Rectangle(
(int)Math.round(zoom * patternRect.width),
(int)Math.round(zoom * patternRect.height)
);
}
protected void buildShadePattern() {
srcOp = pattern.equals(TYPE_IMAGE) && imageName != null
? Op.load(imageName) : new PatternOp(color, pattern);
patternRect = new Rectangle(srcOp.getSize());
}
private static class PatternOp extends AbstractTileOpImpl {
private final Color color;
private final String pattern;
private final int hash;
public PatternOp(Color color, String pattern) {
if (color == null || pattern == null)
throw new IllegalArgumentException();
this.color = color;
this.pattern = pattern;
hash = new HashCodeBuilder().append(color).append(pattern).toHashCode();
}
@Override
public BufferedImage eval() throws Exception {
final BufferedImage im =
ImageUtils.createCompatibleTranslucentImage(2, 2);
final Graphics2D g = im.createGraphics();
g.setColor(color);
if (TYPE_25_PERCENT.equals(pattern)) {
g.drawLine(0, 0, 0, 0);
}
else if (TYPE_50_PERCENT.equals(pattern)) {
g.drawLine(0, 0, 0, 0);
g.drawLine(1, 1, 1, 1);
}
else if (TYPE_75_PERCENT.equals(pattern)) {
g.drawLine(0, 0, 1, 0);
g.drawLine(1, 1, 1, 1);
}
else {
g.drawLine(0, 0, 1, 0);
g.drawLine(0, 1, 1, 1);
}
g.dispose();
return im;
}
@Override
protected void fixSize() { }
@Override
public Dimension getSize() {
return new Dimension(2,2);
}
@Override
public int getWidth() {
return 2;
}
@Override
public int getHeight() {
return 2;
}
@Override
public List<VASSAL.tools.opcache.Op<?>> getSources() {
return Collections.emptyList();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PatternOp)) return false;
return color.equals(((PatternOp) o).color) &&
pattern.equals(((PatternOp) o).pattern);
}
@Override
public int hashCode() {
return hash;
}
}
protected BasicStroke getStroke(double zoom) {
if (stroke == null) {
buildStroke(zoom);
}
return stroke;
}
protected void buildStroke(double zoom) {
stroke = new BasicStroke((float) Math.min(borderWidth * zoom, 1.0),
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND);
}
public Color getBorderColor() {
return borderColor;
}
/**
* Get/Build the textured paint used to fill in the Shade
*/
protected TexturePaint getTexture() {
if (texture == null) {
buildTexture();
}
return texture;
}
protected TexturePaint getTexture(double zoom) {
final boolean usingScaledImage =
scaleImage && imageName != null && pattern.equals(TYPE_IMAGE);
if (!usingScaledImage || zoom == 1.0) {
return getTexture();
}
else {
TexturePaint texture = textures.get(zoom);
if (texture == null) {
final BufferedImage pat = getShadePattern(zoom);
if (pat != null) {
texture = new TexturePaint(pat, getPatternRect(zoom));
textures.put(zoom, texture);
}
}
return texture;
}
}
protected void buildTexture() {
final BufferedImage pat = getShadePattern(1.0);
if (pat != null) {
texture = new TexturePaint(pat, getPatternRect(1.0));
}
}
public Color getColor() {
return color;
}
/**
* Is this Shade drawn over or under counters?
*/
@Override
public boolean drawAboveCounters() {
return drawOver;
}
@Override
public String[] getAttributeNames() {
return new String[]{
NAME,
ALWAYS_ON,
STARTS_ON,
BUTTON_TEXT,
TOOLTIP,
ICON,
HOT_KEY,
BOARDS,
BOARD_LIST,
TYPE,
DRAW_OVER,
PATTERN,
COLOR,
IMAGE,
SCALE_IMAGE,
OPACITY,
BORDER,
BORDER_COLOR,
BORDER_WIDTH,
BORDER_OPACITY
};
}
@Override
public Class<?>[] getAttributeTypes() {
return new Class<?>[]{
String.class,
Boolean.class,
Boolean.class,
String.class,
String.class,
IconConfig.class,
NamedKeyStroke.class,
BoardPrompt.class,
String[].class,
TypePrompt.class,
Boolean.class,
PatternPrompt.class,
Color.class,
Image.class,
Boolean.class,
Integer.class,
Boolean.class,
Color.class,
Integer.class,
Integer.class
};
}
@Override
public String[] getAttributeDescriptions() {
return new String[]{
Resources.getString(Resources.NAME_LABEL),
Resources.getString("Editor.MapShader.shading_on"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.shading_start"), //$NON-NLS-1$
Resources.getString(Resources.BUTTON_TEXT),
Resources.getString(Resources.TOOLTIP_TEXT),
Resources.getString(Resources.BUTTON_ICON),
Resources.getString(Resources.HOTKEY_LABEL),
Resources.getString("Editor.MapShader.shade_boards"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.board_list"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.type"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.shade_top"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.pattern"), //$NON-NLS-1$
Resources.getString(Resources.COLOR_LABEL),
Resources.getString("Editor.MapShader.image"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.scale"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.opacity"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.border"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.border_color"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.border_width"), //$NON-NLS-1$
Resources.getString("Editor.MapShader.border_opacity"), //$NON-NLS-1$
};
}
public static class TypePrompt extends StringEnum {
@Override
public String[] getValidValues(AutoConfigurable target) {
return new String[]{FG_TYPE, BG_TYPE};
}
}
public static class PatternPrompt extends StringEnum {
@Override
public String[] getValidValues(AutoConfigurable target) {
return new String[]{TYPE_25_PERCENT, TYPE_50_PERCENT, TYPE_75_PERCENT, TYPE_SOLID, TYPE_IMAGE};
}
}
@Override
public Class<?>[] getAllowableConfigureComponents() {
return new Class<?>[0];
}
public static class BoardPrompt extends StringEnum {
@Override
public String[] getValidValues(AutoConfigurable target) {
return new String[]{ALL_BOARDS, EXC_BOARDS, INC_BOARDS};
}
}
public void reset() {
shadingVisible = isAlwaysOn() || isStartsOn();
}
protected void toggleShading() {
setShadingVisibility(!shadingVisible);
}
public void setShadingVisibility(boolean b) {
shadingVisible = b;
map.repaint();
}
protected boolean isAlwaysOn() {
return alwaysOn;
}
protected boolean isStartsOn() {
return startsOn;
}
protected Map getMap() {
return map;
}
public Area getBoardClip() {
buildBoardClip();
return boardClip;
}
/**
* Build a clipping region excluding boards that do not needed to be Shaded.
*/
protected void buildBoardClip() {
if (boardClip == null) {
boardClip = new Area();
for (Board b : map.getBoards()) {
String boardName = b.getName();
boolean doShade = false;
if (boardSelection.equals(ALL_BOARDS)) {
doShade = true;
}
else if (boardSelection.equals(EXC_BOARDS)) {
doShade = true;
for (int i = 0; i < boardList.length && doShade; i++) {
doShade = !boardList[i].equals(boardName);
}
}
else if (boardSelection.equals(INC_BOARDS)) {
for (int i = 0; i < boardList.length && !doShade; i++) {
doShade = boardList[i].equals(boardName);
}
}
if (doShade) {
boardClip.add(new Area(b.bounds()));
}
}
}
}
public void setLaunchButtonVisibility() {
launch.setVisible(!isAlwaysOn());
}
@Override
public void setup(boolean gameStarting) {
launch.setEnabled(gameStarting);
if (!gameStarting) {
boardClip = null;
}
}
@Override
public Command getRestoreCommand() {
return null;
}
public static class IconConfig implements ConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new IconConfigurer(key, name, ((MapShader) c).launch.getAttributeValueString(ICON));
}
}
protected void buildPatternAndTexture() {
textures.clear();
buildShadePattern();
buildTexture();
}
@Override
public void setAttribute(String key, Object value) {
if (NAME.equals(key)) {
setConfigureName((String) value);
if (launch.getAttributeValueString(TOOLTIP) == null) {
launch.setAttribute(TOOLTIP, value);
}
}
else if (ALWAYS_ON.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
alwaysOn = (Boolean) value;
setLaunchButtonVisibility();
reset();
}
else if (STARTS_ON.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
startsOn = (Boolean) value;
setLaunchButtonVisibility();
reset();
}
else if (BOARDS.equals(key)) {
boardSelection = (String) value;
}
else if (BOARD_LIST.equals(key)) {
if (value instanceof String) {
value = StringArrayConfigurer.stringToArray((String) value);
}
boardList = (String[]) value;
}
else if (TYPE.equals(key)) {
type = (String) value;
}
else if (DRAW_OVER.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
drawOver = (Boolean) value;
}
else if (PATTERN.equals(key)) {
pattern = (String) value;
buildPatternAndTexture();
}
else if (COLOR.equals(key)) {
if (value instanceof String) {
value = ColorConfigurer.stringToColor((String) value);
}
// Bug 9969. Color configurer returns null if cancelled, so ignore a null.
// and leave pattern and texture unchanged
if (value != null) {
color = (Color) value;
buildPatternAndTexture();
}
}
else if (IMAGE.equals(key)) {
if (value instanceof File) {
value = ((File) value).getName();
}
imageName = (String) value;
buildPatternAndTexture();
}
else if (SCALE_IMAGE.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String)value);
}
scaleImage = (Boolean) value;
}
else if (BORDER.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
border = (Boolean) value;
}
else if (BORDER_COLOR.equals(key)) {
if (value instanceof String) {
value = ColorConfigurer.stringToColor((String) value);
}
borderColor = (Color) value;
}
else if (BORDER_WIDTH.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
borderWidth = (Integer) value;
if (borderWidth < 0) {
borderWidth = 0;
}
stroke = null;
}
else if (OPACITY.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
opacity = (Integer) value;
if (opacity < 0 || opacity > 100) {
opacity = 100;
}
buildComposite();
}
else if (BORDER_OPACITY.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
borderOpacity = (Integer) value;
if (borderOpacity < 0 || borderOpacity > 100) {
borderOpacity = 100;
}
buildBorderComposite();
}
else {
launch.setAttribute(key, value);
}
}
@Override
public String getAttributeValueString(String key) {
if (NAME.equals(key)) {
return getConfigureName() + "";
}
else if (ALWAYS_ON.equals(key)) {
return String.valueOf(isAlwaysOn());
}
else if (STARTS_ON.equals(key)) {
return String.valueOf(isStartsOn());
}
else if (BOARDS.equals(key)) {
return boardSelection + "";
}
else if (BOARD_LIST.equals(key)) {
return StringArrayConfigurer.arrayToString(boardList);
}
else if (TYPE.equals(key)) {
return type + "";
}
else if (DRAW_OVER.equals(key)) {
return String.valueOf(drawOver);
}
else if (PATTERN.equals(key)) {
return pattern + "";
}
else if (COLOR.equals(key)) {
return ColorConfigurer.colorToString(color);
}
else if (IMAGE.equals(key)) {
return imageName;
}
else if (SCALE_IMAGE.equals(key)) {
return String.valueOf(scaleImage);
}
else if (BORDER.equals(key)) {
return String.valueOf(border);
}
else if (BORDER_COLOR.equals(key)) {
return ColorConfigurer.colorToString(borderColor);
}
else if (BORDER_WIDTH.equals(key)) {
return borderWidth + "";
}
else if (OPACITY.equals(key)) {
return opacity + "";
}
else if (BORDER_OPACITY.equals(key)) {
return borderOpacity + "";
}
else {
return launch.getAttributeValueString(key);
}
}
@Override
public VisibilityCondition getAttributeVisibility(String name) {
if (List.of(ICON, HOT_KEY, BUTTON_TEXT, STARTS_ON, TOOLTIP).contains(name)) {
return () -> !isAlwaysOn();
}
else if (BOARD_LIST.equals(name)) {
return () -> !boardSelection.equals(ALL_BOARDS);
}
else if (COLOR.equals(name)) {
return () -> !pattern.equals(TYPE_IMAGE);
}
else if (IMAGE.equals(name)) {
return () -> pattern.equals(TYPE_IMAGE);
}
else if (SCALE_IMAGE.equals(name)) {
return () -> pattern.equals(TYPE_IMAGE);
}
else if (List.of(BORDER_COLOR, BORDER_WIDTH, BORDER_OPACITY).contains(name)) {
return () -> border;
}
else {
return super.getAttributeVisibility(name);
}
}
public static String getConfigureTypeName() {
return Resources.getString("Editor.MapShader.component_type"); //$NON-NLS-1$
}
@Override
public void removeFrom(Buildable parent) {
GameModule.getGameModule().getToolBar().remove(launch);
GameModule.getGameModule().getGameState().removeGameComponent(this);
map.removeDrawComponent(this);
idMgr.remove(this);
}
@Override
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("Map.htm", "MapShading");
}
@Override
public void addTo(Buildable parent) {
GameModule.getGameModule().getToolBar().add(launch);
launch.setAlignmentY(0.0F);
GameModule.getGameModule().getGameState().addGameComponent(this);
map = (Map) parent;
map.addDrawComponent(this);
idMgr.add(this);
validator = idMgr;
setAttributeTranslatable(NAME, false);
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
/**
* Pieces that contribute to shading must implement this interface
*/
public static interface ShadedPiece {
/**
* Returns the Area to add to (or subtract from) the area drawn by the MapShader's.
* Area is assumed to be at zoom factor 1.0
* @param shader
* @return the Area contributed by the piece
*/
public Area getArea(MapShader shader);
}
}
|
package railo.runtime.config;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import railo.commons.collection.LinkedHashMapMaxSize;
import railo.commons.collection.MapFactory;
import railo.commons.digest.Hash;
import railo.commons.io.SystemUtil;
import railo.commons.io.res.Resource;
import railo.commons.io.res.ResourcesImpl;
import railo.commons.lang.ClassUtil;
import railo.commons.lang.PCLCollection;
import railo.commons.lang.StringUtil;
import railo.commons.lang.SystemOut;
import railo.loader.TP;
import railo.loader.engine.CFMLEngine;
import railo.loader.engine.CFMLEngineFactory;
import railo.loader.util.ExtensionFilter;
import railo.runtime.CFMLFactory;
import railo.runtime.CFMLFactoryImpl;
import railo.runtime.Mapping;
import railo.runtime.MappingImpl;
import railo.runtime.engine.CFMLEngineImpl;
import railo.runtime.engine.ThreadQueueImpl;
import railo.runtime.exp.ApplicationException;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.monitor.ActionMonitorCollector;
import railo.runtime.monitor.IntervallMonitor;
import railo.runtime.monitor.RequestMonitor;
import railo.runtime.net.http.ReqRspUtil;
import railo.runtime.op.Caster;
import railo.runtime.reflection.Reflector;
import railo.runtime.security.SecurityManager;
import railo.runtime.security.SecurityManagerImpl;
import railo.runtime.type.scope.Cluster;
import railo.runtime.type.scope.ClusterRemote;
import railo.runtime.type.scope.ClusterWrap;
import railo.runtime.type.util.ArrayUtil;
/**
* config server impl
*/
public final class ConfigServerImpl extends ConfigImpl implements ConfigServer {
private static final long FIVE_SECONDS = 5000;
private final CFMLEngineImpl engine;
private Map<String,CFMLFactory> initContextes;
//private Map contextes;
private SecurityManager defaultSecurityManager;
private Map<String,SecurityManager> managers=MapFactory.<String,SecurityManager>getConcurrentMap();
private String defaultPassword;
private Resource rootDir;
private URL updateLocation;
private String updateType="";
private ConfigListener configListener;
private Map<String, String> labels;
private RequestMonitor[] requestMonitors;
private IntervallMonitor[] intervallMonitors;
private ActionMonitorCollector actionMonitorCollector;
private boolean monitoringEnabled=false;
private int delay=1;
private boolean captcha=false;
private static ConfigServerImpl instance;
private String[] authKeys;
private String idPro;
private LinkedHashMapMaxSize<Long,String> previousNonces=new LinkedHashMapMaxSize<Long,String>(100);
/**
* @param engine
* @param initContextes
* @param contextes
* @param configDir
* @param configFile
*/
protected ConfigServerImpl(CFMLEngineImpl engine,Map<String,CFMLFactory> initContextes, Map<String,CFMLFactory> contextes, Resource configDir, Resource configFile) {
super(null,configDir, configFile);
this.engine=engine;
this.initContextes=initContextes;
//this.contextes=contextes;
this.rootDir=configDir;
instance=this;
}
/**
* @return the configListener
*/
public ConfigListener getConfigListener() {
return configListener;
}
/**
* @param configListener the configListener to set
*/
public void setConfigListener(ConfigListener configListener) {
this.configListener = configListener;
}
@Override
public ConfigServer getConfigServer(String password) {
return this;
}
@Override
public ConfigWeb[] getConfigWebs() {
Iterator<String> it = initContextes.keySet().iterator();
ConfigWeb[] webs=new ConfigWeb[initContextes.size()];
int index=0;
while(it.hasNext()) {
webs[index++]=((CFMLFactoryImpl)initContextes.get(it.next())).getConfig();
}
return webs;
}
@Override
public ConfigWeb getConfigWeb(String realpath) {
return getConfigWebImpl(realpath);
}
/**
* returns CongigWeb Implementtion
* @param realpath
* @return ConfigWebImpl
*/
protected ConfigWebImpl getConfigWebImpl(String realpath) {
Iterator<String> it = initContextes.keySet().iterator();
while(it.hasNext()) {
ConfigWebImpl cw=((CFMLFactoryImpl)initContextes.get(it.next())).getConfigWebImpl();
if(ReqRspUtil.getRootPath(cw.getServletContext()).equals(realpath))
return cw;
}
return null;
}
public ConfigWebImpl getConfigWebById(String id) {
Iterator<String> it = initContextes.keySet().iterator();
while(it.hasNext()) {
ConfigWebImpl cw=((CFMLFactoryImpl)initContextes.get(it.next())).getConfigWebImpl();
if(cw.getId().equals(id))
return cw;
}
return null;
}
public String getIdPro() {
if(idPro==null){
idPro = getId(getSecurityKey(),getSecurityToken(),true,null);
}
return idPro;
}
/**
* @return JspFactoryImpl array
*/
public CFMLFactoryImpl[] getJSPFactories() {
Iterator<String> it = initContextes.keySet().iterator();
CFMLFactoryImpl[] factories=new CFMLFactoryImpl[initContextes.size()];
int index=0;
while(it.hasNext()) {
factories[index++]=(CFMLFactoryImpl)initContextes.get(it.next());
}
return factories;
}
@Override
public Map<String,CFMLFactory> getJSPFactoriesAsMap() {
return initContextes;
}
@Override
public SecurityManager getSecurityManager(String id) {
Object o=managers.get(id);
if(o!=null) return (SecurityManager) o;
if(defaultSecurityManager==null) {
defaultSecurityManager = SecurityManagerImpl.getOpenSecurityManager();
}
return defaultSecurityManager.cloneSecurityManager();
}
@Override
public boolean hasIndividualSecurityManager(String id) {
return managers.containsKey(id);
}
/**
* @param defaultSecurityManager
*/
protected void setDefaultSecurityManager(SecurityManager defaultSecurityManager) {
this.defaultSecurityManager=defaultSecurityManager;
}
/**
* @param id
* @param securityManager
*/
protected void setSecurityManager(String id, SecurityManager securityManager) {
managers.put(id,securityManager);
}
/**
* @param id
*/
protected void removeSecurityManager(String id) {
managers.remove(id);
}
@Override
public SecurityManager getDefaultSecurityManager() {
return defaultSecurityManager;
}
/**
* @return Returns the defaultPassword.
*/
protected String getDefaultPassword() {
return defaultPassword;
}
/**
* @param defaultPassword The defaultPassword to set.
*/
protected void setDefaultPassword(String defaultPassword) {
this.defaultPassword = defaultPassword;
}
@Override
public CFMLEngine getCFMLEngine() {
return engine;
}
/**
* @return Returns the rootDir.
*/
public Resource getRootDirectory() {
return rootDir;
}
@Override
public String getUpdateType() {
return updateType;
}
@Override
public void setUpdateType(String updateType) {
if(!StringUtil.isEmpty(updateType))
this.updateType = updateType;
}
@Override
public URL getUpdateLocation() {
return updateLocation;
}
@Override
public void setUpdateLocation(URL updateLocation) {
this.updateLocation = updateLocation;
}
@Override
public void setUpdateLocation(String strUpdateLocation) throws MalformedURLException {
setUpdateLocation(new URL(strUpdateLocation));
}
@Override
public void setUpdateLocation(String strUpdateLocation, URL defaultValue) {
try {
setUpdateLocation(strUpdateLocation);
} catch (MalformedURLException e) {
setUpdateLocation(defaultValue);
}
}
@Override
public SecurityManager getSecurityManager() {
SecurityManagerImpl sm = (SecurityManagerImpl) getDefaultSecurityManager();//.cloneSecurityManager();
//sm.setAccess(SecurityManager.TYPE_ACCESS_READ,SecurityManager.ACCESS_PROTECTED);
//sm.setAccess(SecurityManager.TYPE_ACCESS_WRITE,SecurityManager.ACCESS_PROTECTED);
return sm;
}
/**
* @return the instance
*/
public static ConfigServerImpl getInstance() {
return instance;
}
public void setLabels(Map<String, String> labels) {
this.labels=labels;
}
public Map<String, String> getLabels() {
if(labels==null) labels=new HashMap<String, String>();
return labels;
}
private ThreadQueueImpl threadQueue;
protected void setThreadQueue(ThreadQueueImpl threadQueue) {
this.threadQueue=threadQueue;
}
public ThreadQueueImpl getThreadQueue() {
return threadQueue;
}
public RequestMonitor[] getRequestMonitors() {
return requestMonitors;
}
public RequestMonitor getRequestMonitor(String name) throws ApplicationException {
for(int i=0;i<requestMonitors.length;i++){
if(requestMonitors[i].getName().equalsIgnoreCase(name))
return requestMonitors[i];
}
throw new ApplicationException("there is no request monitor registered with name ["+name+"]");
}
protected void setRequestMonitors(RequestMonitor[] monitors) {
this.requestMonitors=monitors;;
}
public IntervallMonitor[] getIntervallMonitors() {
return intervallMonitors;
}
public IntervallMonitor getIntervallMonitor(String name) throws ApplicationException {
for(int i=0;i<intervallMonitors.length;i++){
if(intervallMonitors[i].getName().equalsIgnoreCase(name))
return intervallMonitors[i];
}
throw new ApplicationException("there is no intervall monitor registered with name ["+name+"]");
}
protected void setIntervallMonitors(IntervallMonitor[] monitors) {
this.intervallMonitors=monitors;;
}
public void setActionMonitorCollector(ActionMonitorCollector actionMonitorCollector) {
this.actionMonitorCollector=actionMonitorCollector;
}
public ActionMonitorCollector getActionMonitorCollector() {
return actionMonitorCollector;
}
public Object getActionMonitor(String name) { // FUTURE return ActionMonitor
return actionMonitorCollector.getActionMonitor(name);
}
@Override
public boolean isMonitoringEnabled() {
return monitoringEnabled;
}
protected void setMonitoringEnabled(boolean monitoringEnabled) {
this.monitoringEnabled=monitoringEnabled;;
}
protected void setLoginDelay(int delay) {
this.delay=delay;
}
protected void setLoginCaptcha(boolean captcha) {
this.captcha=captcha;
}
@Override
public int getLoginDelay() {
return delay;
}
@Override
public boolean getLoginCaptcha() {
return captcha;
}
public void reset() {
super.reset();
getThreadQueue().clear();
}
@Override
public Resource getSecurityDirectory(){
Resource cacerts=null;
// javax.net.ssl.trustStore
String trustStore = SystemUtil.getPropertyEL("javax.net.ssl.trustStore");
if(trustStore!=null){
cacerts = ResourcesImpl.getFileResourceProvider().getResource(trustStore);
}
// security/cacerts
if(cacerts==null || !cacerts.exists()) {
cacerts = getConfigDir().getRealResource("security/cacerts");
if(!cacerts.exists())cacerts.mkdirs();
}
return cacerts;
}
@Override
public void checkPermGenSpace(boolean check) {
//print.e(Runtime.getRuntime().freeMemory());
// Runtime.getRuntime().freeMemory()<200000 ||
// long pgs=SystemUtil.getFreePermGenSpaceSize();
int promille=SystemUtil.getFreePermGenSpacePromille();
// Pen Gen Space info not available
if(promille==-1) {//if(pgs==-1) {
if(countLoadedPages()>500)
shrink();
}
else if(!check || promille<50){//else if(!check || pgs<1024*1024){
SystemOut.printDate(getErrWriter(),"+Free Perm Gen Space is less than 1mb (free:"+((SystemUtil.getFreePermGenSpaceSize())/1024)+"kb), shrink all template classloaders");
// first just call GC and check if it help
System.gc();
//if(SystemUtil.getFreePermGenSpaceSize()>1024*1024)
if(SystemUtil.getFreePermGenSpacePromille()>50)
return;
shrink();
}
}
private void shrink() {
ConfigWeb[] webs = getConfigWebs();
int count=0;
for(int i=0;i<webs.length;i++){
count+=shrink((ConfigWebImpl) webs[i],false);
}
if(count==0) {
for(int i=0;i<webs.length;i++){
shrink((ConfigWebImpl) webs[i],true);
}
}
}
private static int shrink(ConfigWebImpl config, boolean force) {
int count=0;
count+=shrink(config.getMappings(),force);
count+=shrink(config.getCustomTagMappings(),force);
count+=shrink(config.getComponentMappings(),force);
count+=shrink(config.getFunctionMapping(),force);
count+=shrink(config.getServerFunctionMapping(),force);
count+=shrink(config.getTagMapping(),force);
count+=shrink(config.getServerTagMapping(),force);
//count+=shrink(config.getServerTagMapping(),force);
return count;
}
private static int shrink(Mapping[] mappings, boolean force) {
int count=0;
for(int i=0;i<mappings.length;i++){
count+=shrink(mappings[i],force);
}
return count;
}
private static int shrink(Mapping mapping, boolean force) {
try {
PCLCollection pcl = ((MappingImpl)mapping).getPCLCollection();
if(pcl!=null)return pcl.shrink(force);
}
catch (Throwable t) {
t.printStackTrace();
}
return 0;
}
public long countLoadedPages() {
long count=0;
ConfigWeb[] webs = getConfigWebs();
for(int i=0;i<webs.length;i++){
count+=_count((ConfigWebImpl) webs[i]);
}
return count;
}
private static long _count(ConfigWebImpl config) {
long count=0;
count+=_count(config.getMappings());
count+=_count(config.getCustomTagMappings());
count+=_count(config.getComponentMappings());
count+=_count(config.getFunctionMapping());
count+=_count(config.getServerFunctionMapping());
count+=_count(config.getTagMapping());
count+=_count(config.getServerTagMapping());
//count+=_count(((ConfigWebImpl)config).getServerTagMapping());
return count;
}
private static long _count(Mapping[] mappings) {
long count=0;
for(int i=0;i<mappings.length;i++){
count+=_count(mappings[i]);
}
return count;
}
private static long _count(Mapping mapping) {
PCLCollection pcl = ((MappingImpl)mapping).getPCLCollection();
return pcl==null?0:pcl.count();
}
@Override
public Cluster createClusterScope() throws PageException {
Cluster cluster=null;
try {
if(Reflector.isInstaneOf(getClusterClass(), Cluster.class)){
cluster=(Cluster) ClassUtil.loadInstance(
getClusterClass(),
ArrayUtil.OBJECT_EMPTY
);
cluster.init(this);
}
else if(Reflector.isInstaneOf(getClusterClass(), ClusterRemote.class)){
ClusterRemote cb=(ClusterRemote) ClassUtil.loadInstance(
getClusterClass(),
ArrayUtil.OBJECT_EMPTY
);
cluster=new ClusterWrap(this,cb);
//cluster.init(cs);
}
}
catch (Exception e) {
throw Caster.toPageException(e);
}
return cluster;
}
@Override
public boolean hasServerPassword() {
return hasPassword();
}
public String[] getInstalledPatches() throws PageException {
CFMLEngineFactory factory = getCFMLEngine().getCFMLEngineFactory();
try{
return factory.getInstalledPatches();
}
catch(Throwable t){
try {
return getInstalledPatchesOld(factory);
} catch (Exception e1) {
throw Caster.toPageException(e1);
}
}
}
private String[] getInstalledPatchesOld(CFMLEngineFactory factory) throws IOException {
File patchDir = new File(factory.getResourceRoot(),"patches");
if(!patchDir.exists())patchDir.mkdirs();
File[] patches=patchDir.listFiles(new ExtensionFilter(new String[]{"."+getCoreExtension()}));
List<String> list=new ArrayList<String>();
String name;
int extLen=getCoreExtension().length()+1;
for(int i=0;i<patches.length;i++) {
name=patches[i].getName();
name=name.substring(0, name.length()-extLen);
list.add(name);
}
String[] arr = list.toArray(new String[list.size()]);
Arrays.sort(arr);
return arr;
}
private String getCoreExtension() {
URL res = new TP().getClass().getResource("/core/core.rcs");
if(res!=null) return "rcs";
res = new TP().getClass().getResource("/core/core.rc");
if(res!=null) return "rc";
return "rc";
}
@Override
public boolean allowRequestTimeout() {
return engine.allowRequestTimeout();
}
private boolean fullNullSupport=false;
protected void setFullNullSupport(boolean fullNullSupport) {
this.fullNullSupport=fullNullSupport;
}
public boolean getFullNullSupport() {
return fullNullSupport;
}
public String[] getAuthenticationKeys() {
return authKeys==null?new String[0]:authKeys;
}
protected void setAuthenticationKeys(String[] authKeys) {
this.authKeys = authKeys;
}
public ConfigServer getConfigServer(String key,String nonce) {
return this;
}
public void checkAccess(String password) throws ExpressionException {
if(!hasPassword())
throw new ExpressionException("Cannot access, no password is defined");
if(!passwordEqual(password))
throw new ExpressionException("No access, password is invalid");
}
public void checkAccess(String key, long timeNonce) throws PageException {
if(previousNonces.containsKey(timeNonce)) {
long now = System.currentTimeMillis();
long diff=timeNonce>now?timeNonce-now:now-timeNonce;
if(diff>10)
throw new ApplicationException("nonce was already used, same nonce can only be used once");
}
long now = System.currentTimeMillis()+getTimeServerOffset();
if(timeNonce>(now+FIVE_SECONDS) || timeNonce<(now-FIVE_SECONDS))
throw new ApplicationException("nonce is outdated");
previousNonces.put(timeNonce,"");
String[] keys=getAuthenticationKeys();
// check if one of the keys matching
String hash;
for(int i=0;i<keys.length;i++){
try {
hash=Hash.hash(keys[i], Caster.toString(timeNonce), Hash.ALGORITHM_SHA_256, Hash.ENCODING_HEX);
if(hash.equals(key)) return;
}
catch (NoSuchAlgorithmException e) {
throw Caster.toPageException(e);
}
}
throw new ApplicationException("No access, no matching authentication key found");
}
}
|
package com.thaiopensource.relaxng.output.rnc;
import com.thaiopensource.relaxng.edit.*;
import com.thaiopensource.relaxng.output.OutputDirectory;
import com.thaiopensource.relaxng.output.common.ErrorReporter;
import com.thaiopensource.relaxng.parse.SchemaBuilder;
import com.thaiopensource.relaxng.parse.Context;
import com.thaiopensource.xml.util.WellKnownNamespaces;
import java.io.IOException;
import java.util.*;
/*
Use \x{} escapes for characters not in repertoire of selected encoding
*/
class Output {
private final Prettyprinter pp;
private final String sourceUri;
private final OutputDirectory od;
private final ErrorReporter er;
private final NamespaceManager.NamespaceBindings nsb;
private final Map datatypeLibraryMap = new HashMap();
private final ComplexityCache complexityCache = new ComplexityCache();
private final NameClassVisitor nameClassOutput = new NameClassOutput(true);
private final NameClassVisitor noParenNameClassOutput = new NameClassOutput(false);
private final PatternVisitor noParenPatternOutput = new PatternOutput(false);
private final PatternVisitor patternOutput = new PatternOutput(true);
private final ComponentVisitor componentOutput = new ComponentOutput();
private final AnnotationChildVisitor annotationChildOutput = new AnnotationChildOutput();
private final AnnotationChildVisitor followingAnnotationChildOutput = new FollowingAnnotationChildOutput();
private boolean isAttributeNameClass;
static private final String indent = " ";
static private final String[] keywords = {
"attribute", "default", "datatypes", "div", "element", "empty", "external",
"grammar", "include", "inherit", "list", "mixed", "namespace", "notAllowed",
"parent", "start", "string", "text", "token"
};
static private final Set keywordSet = new HashSet();
static {
for (int i = 0; i < keywords.length; i++)
keywordSet.add(keywords[i]);
}
static void output(Pattern p, String sourceUri, OutputDirectory od, ErrorReporter er) throws IOException {
try {
new Output(sourceUri, od, er, NamespaceVisitor.createBindings(p)).topLevel(p);
}
catch (Prettyprinter.WrappedException e) {
throw e.getIOException();
}
}
private Output(String sourceUri, OutputDirectory od, ErrorReporter er,
NamespaceManager.NamespaceBindings nsb) throws IOException {
this.sourceUri = sourceUri;
this.od = od;
this.er = er;
this.pp = new StreamingPrettyprinter(od.getLineLength(), od.getLineSeparator(), od.open(sourceUri));
this.nsb = nsb;
}
private void topLevel(Pattern p) {
p.accept(new TextAnnotationMerger());
boolean implicitGrammar = p instanceof GrammarPattern && p.getAttributeAnnotations().isEmpty();
if (implicitGrammar && !p.getLeadingComments().isEmpty()) {
leadingComments(p);
pp.hardNewline();
}
outputNamespaceDeclarations();
outputDatatypeLibraryDeclarations(p);
if (implicitGrammar) {
for (Iterator iter = p.getChildElementAnnotations().iterator(); iter.hasNext();) {
((AnnotationChild)iter.next()).accept(annotationChildOutput);
pp.hardNewline();
}
innerBody(((GrammarPattern)p).getComponents());
// This deals with trailing comments
for (Iterator iter = p.getFollowingElementAnnotations().iterator(); iter.hasNext();) {
pp.hardNewline();
((AnnotationChild)iter.next()).accept(annotationChildOutput);
}
}
else
p.accept(patternOutput);
// The pretty printer ensures that we have a terminating newline.
pp.close();
}
private void outputNamespaceDeclarations() {
List prefixes = new Vector();
prefixes.addAll(nsb.getPrefixes());
Collections.sort(prefixes);
boolean needNewline = false;
String defaultPrefix = null;
String defaultNamespace = nsb.getNamespaceUri("");
if (defaultNamespace != null && !defaultNamespace.equals(SchemaBuilder.INHERIT_NS))
defaultPrefix = nsb.getNonEmptyPrefix(defaultNamespace);
for (Iterator iter = prefixes.iterator(); iter.hasNext();) {
String prefix = (String)iter.next();
String ns = nsb.getNamespaceUri(prefix);
if (prefix.length() == 0) {
if (defaultPrefix == null && !ns.equals(SchemaBuilder.INHERIT_NS)) {
pp.startGroup();
pp.text("default namespace =");
pp.startNest(indent);
pp.softNewline(" ");
literal(ns);
pp.endNest();
pp.endGroup();
pp.hardNewline();
needNewline = true;
}
}
else if (!prefix.equals("xml")) {
pp.startGroup();
if (prefix.equals(defaultPrefix))
pp.text("default namespace ");
else
pp.text("namespace ");
pp.text(prefix);
pp.text(" =");
pp.startNest(indent);
pp.softNewline(" ");
if (ns.equals(SchemaBuilder.INHERIT_NS))
pp.text("inherit");
else
literal(ns);
pp.endNest();
pp.endGroup();
pp.hardNewline();
needNewline = true;
}
}
if (needNewline)
pp.hardNewline();
}
private void outputDatatypeLibraryDeclarations(Pattern p) {
datatypeLibraryMap.put(WellKnownNamespaces.XML_SCHEMA_DATATYPES, "xsd");
List datatypeLibraries = new Vector();
datatypeLibraries.addAll(DatatypeLibraryVisitor.findDatatypeLibraries(p));
if (datatypeLibraries.isEmpty())
return;
Collections.sort(datatypeLibraries);
for (int i = 0, len = datatypeLibraries.size(); i < len; i++) {
String prefix = "d";
if (len > 1)
prefix += Integer.toString(i + 1);
String uri = (String)datatypeLibraries.get(i);
datatypeLibraryMap.put(uri, prefix);
pp.startGroup();
pp.text("datatypes ");
pp.text(prefix);
pp.text(" =");
pp.startNest(indent);
pp.softNewline(" ");
literal(uri);
pp.endNest();
pp.endGroup();
pp.hardNewline();
}
pp.hardNewline();
}
static class TextAnnotationMerger extends NullVisitor {
public void nullVisitElement(ElementAnnotation ea) {
TextAnnotation prevText = null;
for (Iterator iter = ea.getChildren().iterator(); iter.hasNext();) {
AnnotationChild child = (AnnotationChild)iter.next();
if (child instanceof TextAnnotation) {
if (prevText == null)
prevText = (TextAnnotation)child;
else {
prevText.setValue(prevText.getValue() + ((TextAnnotation)child).getValue());
iter.remove();
}
}
else {
prevText = null;
child.accept(this);
}
}
}
}
static class DatatypeLibraryVisitor extends NullVisitor {
private Set datatypeLibraries = new HashSet();
public void nullVisitValue(ValuePattern p) {
noteDatatypeLibrary(p.getDatatypeLibrary());
super.nullVisitValue(p);
}
public void nullVisitData(DataPattern p) {
noteDatatypeLibrary(p.getDatatypeLibrary());
super.nullVisitData(p);
}
private void noteDatatypeLibrary(String uri) {
if (!uri.equals("") && !uri.equals(WellKnownNamespaces.XML_SCHEMA_DATATYPES))
datatypeLibraries.add(uri);
}
static Set findDatatypeLibraries(Pattern p) {
DatatypeLibraryVisitor dlv = new DatatypeLibraryVisitor();
p.accept(dlv);
return dlv.datatypeLibraries;
}
}
static class NamespaceVisitor extends NullVisitor {
private NamespaceManager nsm = new NamespaceManager();
private boolean isAttribute;
public void nullVisitInclude(IncludeComponent c) {
super.nullVisitInclude(c);
nsm.requireNamespace(c.getNs(), true);
}
public void nullVisitExternalRef(ExternalRefPattern p) {
super.nullVisitExternalRef(p);
nsm.requireNamespace(p.getNs(), true);
}
public void nullVisitElement(ElementPattern p) {
isAttribute = false;
super.nullVisitElement(p);
}
public void nullVisitAttribute(AttributePattern p) {
isAttribute = true;
super.nullVisitAttribute(p);
}
public void nullVisitName(NameNameClass nc) {
super.nullVisitName(nc);
if (!isAttribute || nc.getNamespaceUri().length() != 0)
nsm.requireNamespace(nc.getNamespaceUri(), !isAttribute);
if (nc.getPrefix() == null) {
if (!isAttribute)
nsm.preferBinding("", nc.getNamespaceUri());
}
else
nsm.preferBinding(nc.getPrefix(), nc.getNamespaceUri());
}
public void nullVisitNsName(NsNameNameClass nc) {
super.nullVisitNsName(nc);
nsm.requireNamespace(nc.getNs(), false);
}
public void nullVisitValue(ValuePattern p) {
super.nullVisitValue(p);
for (Iterator iter = p.getPrefixMap().entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
nsm.requireBinding((String)entry.getKey(), (String)entry.getValue());
}
}
public void nullVisitElement(ElementAnnotation ea) {
super.nullVisitElement(ea);
noteAnnotationBinding(ea.getPrefix(), ea.getNamespaceUri());
noteContext(ea.getContext(), true);
}
private void noteContext(Context context, boolean required) {
if (context == null)
return;
for (Enumeration e = context.prefixes(); e.hasMoreElements();) {
String prefix = (String)e.nextElement();
// Default namespace is not relevant to annotations
if (!prefix.equals("")) {
String ns = context.resolveNamespacePrefix(prefix);
if (ns != null && !ns.equals(SchemaBuilder.INHERIT_NS)) {
if (required)
nsm.requireBinding(prefix, ns);
else
nsm.preferBinding(prefix, ns);
}
}
}
}
public void nullVisitAttribute(AttributeAnnotation a) {
super.nullVisitAttribute(a);
noteAnnotationBinding(a.getPrefix(), a.getNamespaceUri());
}
private void noteAnnotationBinding(String prefix, String ns) {
if (ns.length() != 0)
nsm.requireNamespace(ns, false);
if (prefix != null)
nsm.preferBinding(prefix, ns);
}
public void nullVisitAnnotated(Annotated p) {
p.leadingCommentsAccept(this);
noteContext(p.getContext(), !p.getAttributeAnnotations().isEmpty());
p.attributeAnnotationsAccept(this);
List before = (p.mayContainText()
? p.getFollowingElementAnnotations()
: p.getChildElementAnnotations());
// Avoid unnecessary prefix for documentation
int state = 0;
for (Iterator iter = before.iterator(); iter.hasNext();) {
AnnotationChild child = (AnnotationChild)iter.next();
if (state < 2 && documentationString(child) != null)
state = 1;
else if (state != 1 || !(child instanceof Comment))
state = 2;
if (state == 2)
child.accept(this);
}
if (!p.mayContainText())
p.followingElementAnnotationsAccept(this);
}
static NamespaceManager.NamespaceBindings createBindings(Pattern p) {
NamespaceVisitor nsv = new NamespaceVisitor();
p.accept(nsv);
return nsv.nsm.createBindings();
}
}
class ComponentOutput implements ComponentVisitor {
public Object visitDefine(DefineComponent c) {
startAnnotations(c);
pp.startGroup();
String name = c.getName();
if (name == DefineComponent.START)
pp.text("start");
else
identifier(name);
Combine combine = c.getCombine();
String op;
if (combine == null)
op = " =";
else if (combine == Combine.CHOICE)
op = " |=";
else
op = " &=";
pp.text(op);
pp.startNest(indent);
pp.softNewline(" ");
c.getBody().accept(noParenPatternOutput);
pp.endNest();
pp.endGroup();
endAnnotations(c);
return null;
}
public Object visitDiv(DivComponent c) {
startAnnotations(c);
pp.text("div");
body(c);
endAnnotations(c);
return null;
}
public Object visitInclude(IncludeComponent c) {
startAnnotations(c);
pp.startGroup();
pp.text("include ");
pp.startNest("include ");
literal(od.reference(sourceUri, c.getHref()));
inherit(c.getNs());
pp.endNest();
pp.endGroup();
List components = c.getComponents();
if (!components.isEmpty())
body(components);
endAnnotations(c);
return null;
}
}
class PatternOutput implements PatternVisitor {
private final boolean alwaysUseParens;
PatternOutput(boolean alwaysUseParens) {
this.alwaysUseParens = alwaysUseParens;
}
public Object visitGrammar(GrammarPattern p) {
startAnnotations(p);
pp.text("grammar");
body(p);
endAnnotations(p);
return null;
}
public Object visitElement(ElementPattern p) {
isAttributeNameClass = false;
nameClassed(p, "element ");
return null;
}
public Object visitAttribute(AttributePattern p) {
isAttributeNameClass = true;
nameClassed(p, "attribute ");
return null;
}
private void nameClassed(NameClassedPattern p, String key) {
startAnnotations(p);
pp.text(key);
pp.startNest(key);
p.getNameClass().accept(noParenNameClassOutput);
pp.endNest();
braceChild(p);
endAnnotations(p);
}
private void braceChild(UnaryPattern p) {
Pattern child = p.getChild();
boolean isSimple = !complexityCache.isComplex(child);
if (isSimple)
pp.startGroup();
pp.text(" {");
pp.startNest(indent);
if (isSimple)
pp.softNewline(" ");
else
pp.hardNewline();
child.accept(noParenPatternOutput);
pp.endNest();
if (isSimple)
pp.softNewline(" ");
else
pp.hardNewline();
pp.text("}");
if (isSimple)
pp.endGroup();
}
public Object visitOneOrMore(OneOrMorePattern p) {
postfix(p, "+");
return null;
}
public Object visitZeroOrMore(ZeroOrMorePattern p) {
postfix(p, "*");
return null;
}
public Object visitOptional(OptionalPattern p) {
postfix(p, "?");
return null;
}
private void postfix(UnaryPattern p, String op) {
if (!startAnnotations(p)) {
p.getChild().accept(patternOutput);
pp.text(op);
}
else {
pp.text("(");
pp.startNest("(");
p.getChild().accept(patternOutput);
pp.endNest();
pp.text(op);
pp.text(")");
}
endAnnotations(p);
}
public Object visitRef(RefPattern p) {
startAnnotations(p);
identifier(p.getName());
endAnnotations(p);
return null;
}
public Object visitParentRef(ParentRefPattern p) {
startAnnotations(p);
pp.text("parent ");
identifier(p.getName());
endAnnotations(p);
return null;
}
public Object visitExternalRef(ExternalRefPattern p) {
startAnnotations(p);
pp.startGroup();
pp.text("external ");
pp.startNest("external ");
literal(od.reference(sourceUri, p.getHref()));
inherit(p.getNs());
pp.endNest();
pp.endGroup();
endAnnotations(p);
return null;
}
public Object visitText(TextPattern p) {
startAnnotations(p);
pp.text("text");
endAnnotations(p);
return null;
}
public Object visitEmpty(EmptyPattern p) {
startAnnotations(p);
pp.text("empty");
endAnnotations(p);
return null;
}
public Object visitNotAllowed(NotAllowedPattern p) {
startAnnotations(p);
pp.text("notAllowed");
endAnnotations(p);
return null;
}
public Object visitList(ListPattern p) {
prefix(p, "list");
return null;
}
public Object visitMixed(MixedPattern p) {
prefix(p, "mixed");
return null;
}
private void prefix(UnaryPattern p, String key) {
startAnnotations(p);
pp.text(key);
braceChild(p);
endAnnotations(p);
}
public Object visitChoice(ChoicePattern p) {
composite(p, "| ", false);
return null;
}
public Object visitInterleave(InterleavePattern p) {
composite(p, "& ", false);
return null;
}
public Object visitGroup(GroupPattern p) {
composite(p, ",", true);
return null;
}
void composite(CompositePattern p, String sep, boolean sepBeforeNewline) {
boolean useParens = alwaysUseParens;
if (startAnnotations(p))
useParens = true;
boolean isSimple = !complexityCache.isComplex(p);
if (isSimple)
pp.startGroup();
if (useParens) {
pp.text("(");
pp.startNest("(");
}
boolean first = true;
for (Iterator iter = p.getChildren().iterator(); iter.hasNext();) {
if (!first) {
if (sepBeforeNewline)
pp.text(sep);
if (isSimple)
pp.softNewline(" ");
else
pp.hardNewline();
if (!sepBeforeNewline) {
pp.text(sep);
pp.startNest(sep);
}
}
((Pattern)iter.next()).accept(patternOutput);
if (first)
first = false;
else if (!sepBeforeNewline)
pp.endNest();
}
if (useParens) {
pp.endNest();
pp.text(")");
}
if (isSimple)
pp.endGroup();
endAnnotations(p);
}
public Object visitData(DataPattern p) {
startAnnotations(p);
String lib = p.getDatatypeLibrary();
String qn;
if (!lib.equals(""))
qn = (String)datatypeLibraryMap.get(lib) + ":" + p.getType();
else
qn = p.getType();
pp.text(qn);
List params = p.getParams();
if (params.size() > 0) {
pp.startGroup();
pp.text(" {");
pp.startNest(indent);
for (Iterator iter = params.iterator(); iter.hasNext();) {
pp.softNewline(" ");
Param param = (Param)iter.next();
startAnnotations(param);
pp.startGroup();
pp.text(param.getName());
pp.text(" =");
pp.startNest(indent);
pp.softNewline(" ");
literal(param.getValue());
pp.endNest();
pp.endGroup();
endAnnotations(param);
}
pp.endNest();
pp.softNewline(" ");
pp.text("}");
pp.endGroup();
}
Pattern e = p.getExcept();
if (e != null) {
boolean useParen = (!e.mayContainText()
&& !e.getFollowingElementAnnotations().isEmpty());
String s;
if (params.isEmpty())
s = " - ";
else {
pp.startGroup();
pp.softNewline(" ");
s = "- ";
}
if (useParen)
s += "(";
pp.text(s);
pp.startNest(params.isEmpty() ? qn + s : s);
e.accept(useParen ? noParenPatternOutput : patternOutput);
pp.endNest();
if (useParen)
pp.text(")");
if (!params.isEmpty())
pp.endGroup();
}
endAnnotations(p);
return null;
}
public Object visitValue(ValuePattern p) {
for (Iterator iter = p.getPrefixMap().entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
String prefix = (String)entry.getKey();
String uri = (String)entry.getValue();
if (!uri.equals(nsb.getNamespaceUri(prefix))) {
if (prefix.equals(""))
er.error("value_inconsistent_default_binding", uri, p.getSourceLocation());
else
er.error("value_inconsistent_binding", prefix, uri, p.getSourceLocation());
}
}
startAnnotations(p);
String lib = p.getDatatypeLibrary();
pp.startGroup();
String str = null;
if (lib.equals("")) {
if (!p.getType().equals("token"))
str = p.getType() + " ";
}
else
str = (String)datatypeLibraryMap.get(lib) + ":" + p.getType() + " ";
if (str != null) {
literal(str);
pp.startNest(str);
}
literal(p.getValue());
if (str != null)
pp.endNest();
pp.endGroup();
endAnnotations(p);
return null;
}
}
class NameClassOutput implements NameClassVisitor {
private final boolean alwaysUseParens;
NameClassOutput(boolean alwaysUseParens) {
this.alwaysUseParens = alwaysUseParens;
}
public Object visitAnyName(AnyNameNameClass nc) {
NameClass e = nc.getExcept();
if (e == null) {
startAnnotations(nc);
pp.text("*");
}
else {
boolean useParens = startAnnotations(nc) || alwaysUseParens;
String s = useParens ? "(* - " : "* - ";
pp.text(s);
pp.startNest(s);
e.accept(nameClassOutput);
if (useParens)
pp.text(")");
pp.endNest();
}
endAnnotations(nc);
return null;
}
public Object visitNsName(NsNameNameClass nc) {
NameClass e = nc.getExcept();
String prefix = nsb.getNonEmptyPrefix(nc.getNs());
if (e == null) {
startAnnotations(nc);
pp.text(prefix);
pp.text(":*");
}
else {
boolean useParens = startAnnotations(nc) || alwaysUseParens;
String s = useParens ? "(" : "";
s += prefix;
s += ":* - ";
pp.text(s);
pp.startNest(s);
e.accept(nameClassOutput);
pp.endNest();
if (useParens)
pp.text(")");
}
endAnnotations(nc);
return null;
}
public Object visitName(NameNameClass nc) {
startAnnotations(nc);
pp.text(qualifyName(nc.getNamespaceUri(), nc.getPrefix(), nc.getLocalName(), isAttributeNameClass));
endAnnotations(nc);
return null;
}
public Object visitChoice(ChoiceNameClass nc) {
boolean useParens = alwaysUseParens;
if (startAnnotations(nc))
useParens = true;
else if (nc.getChildren().size() == 1)
useParens = false;
if (useParens) {
pp.text("(");
pp.startNest("(");
}
pp.startGroup();
boolean first = true;
for (Iterator iter = nc.getChildren().iterator(); iter.hasNext();) {
if (first)
first = false;
else {
pp.softNewline(" ");
pp.text("| ");
}
((NameClass)iter.next()).accept(nameClassOutput);
}
pp.endGroup();
if (useParens) {
pp.endNest();
pp.text(")");
}
endAnnotations(nc);
return null;
}
}
class AnnotationChildOutput implements AnnotationChildVisitor {
public Object visitText(TextAnnotation ta) {
literal(ta.getValue());
return null;
}
public Object visitComment(Comment c) {
comment("#", c.getValue());
return null;
}
public Object visitElement(ElementAnnotation elem) {
checkContext(elem.getContext(), elem.getSourceLocation());
pp.text(qualifyName(elem.getNamespaceUri(), elem.getPrefix(), elem.getLocalName(),
// unqualified annotation element names have "" namespace
true));
pp.text(" ");
annotationBody(elem.getAttributes(), elem.getChildren());
return null;
}
}
class FollowingAnnotationChildOutput extends AnnotationChildOutput {
public Object visitElement(ElementAnnotation elem) {
pp.text(">> ");
pp.startNest(">> ");
super.visitElement(elem);
pp.endNest();
return null;
}
}
private static boolean hasAnnotations(Annotated annotated) {
return (!annotated.getChildElementAnnotations().isEmpty()
|| !annotated.getAttributeAnnotations().isEmpty()
|| !annotated.getFollowingElementAnnotations().isEmpty());
}
private boolean startAnnotations(Annotated annotated) {
if (!annotated.getLeadingComments().isEmpty()) {
leadingComments(annotated);
if (!hasAnnotations(annotated))
return false;
}
else if (!hasAnnotations(annotated))
return false;
List before = (annotated.mayContainText()
? annotated.getFollowingElementAnnotations()
: annotated.getChildElementAnnotations());
int i = 0;
int len = before.size();
for (; i < len; i++) {
int j = i;
if (i != 0) {
do {
if (!(before.get(j) instanceof Comment))
break;
} while (++j < len);
if (j >= len)
break;
}
String doc = documentationString((AnnotationChild)before.get(j));
if (doc == null)
break;
if (j == i)
pp.hardNewline();
else {
for (;;) {
((Comment)before.get(i)).accept(annotationChildOutput);
if (++i == j)
break;
pp.hardNewline();
}
}
comment("##", doc);
}
if (i > 0)
before = before.subList(i, len);
pp.startGroup();
if (!annotated.getAttributeAnnotations().isEmpty()
|| !before.isEmpty()) {
if (!annotated.getAttributeAnnotations().isEmpty())
checkContext(annotated.getContext(), annotated.getSourceLocation());
annotationBody(annotated.getAttributeAnnotations(), before);
pp.softNewline(" ");
}
return true;
}
private static String documentationString(AnnotationChild child) {
if (!(child instanceof ElementAnnotation))
return null;
ElementAnnotation elem = (ElementAnnotation)child;
if (!elem.getLocalName().equals("documentation"))
return null;
if (!elem.getNamespaceUri().equals(WellKnownNamespaces.RELAX_NG_COMPATIBILITY_ANNOTATIONS))
return null;
if (!elem.getAttributes().isEmpty())
return null;
StringBuffer buf = new StringBuffer();
for (Iterator iter = elem.getChildren().iterator(); iter.hasNext();) {
Object obj = iter.next();
if (!(obj instanceof TextAnnotation))
return null;
buf.append(((TextAnnotation)obj).getValue());
}
return buf.toString();
}
private void endAnnotations(Annotated annotated) {
if (!annotated.mayContainText()) {
for (Iterator iter = annotated.getFollowingElementAnnotations().iterator(); iter.hasNext();) {
if (annotated instanceof Component)
pp.hardNewline();
else
pp.softNewline(" ");
AnnotationChildVisitor output = (annotated instanceof Component
? annotationChildOutput
: followingAnnotationChildOutput);
((AnnotationChild)iter.next()).accept(output);
}
}
if (hasAnnotations(annotated))
pp.endGroup();
}
private void leadingComments(Annotated annotated) {
boolean first = true;
for (Iterator iter = annotated.getLeadingComments().iterator(); iter.hasNext();) {
if (!first)
pp.hardNewline();
else
first = false;
((Comment)iter.next()).accept(annotationChildOutput);
}
}
private void annotationBody(List attributes, List children) {
pp.startGroup();
pp.text("[");
pp.startNest(indent);
for (Iterator iter = attributes.iterator(); iter.hasNext();) {
AttributeAnnotation att = (AttributeAnnotation)iter.next();
pp.softNewline(" ");
pp.startGroup();
pp.text(qualifyName(att.getNamespaceUri(), att.getPrefix(), att.getLocalName(), true));
pp.text(" =");
pp.startNest(indent);
pp.softNewline(" ");
literal(att.getValue());
pp.endNest();
pp.endGroup();
}
for (Iterator iter = children.iterator(); iter.hasNext();) {
pp.softNewline(" ");
((AnnotationChild)iter.next()).accept(annotationChildOutput);
}
pp.endNest();
pp.softNewline(" ");
pp.text("]");
pp.endGroup();
}
private void body(Container container) {
body(container.getComponents());
}
private void body(List components) {
if (components.size() == 0)
pp.text(" { }");
else {
pp.text(" {");
pp.startNest(indent);
pp.hardNewline();
innerBody(components);
pp.endNest();
pp.hardNewline();
pp.text("}");
}
}
private void innerBody(List components) {
boolean first = true;
for (Iterator iter = components.iterator(); iter.hasNext();) {
if (first)
first = false;
else
pp.hardNewline();
((Component)iter.next()).accept(componentOutput);
}
}
private void inherit(String ns) {
if (ns.equals(nsb.getNamespaceUri("")))
return;
pp.softNewline(" ");
pp.text("inherit = ");
pp.text(nsb.getNonEmptyPrefix(ns));
}
private void identifier(String name) {
if (keywordSet.contains(name))
pp.text("\\");
pp.text(name);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.