gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
package org.newdawn.slick;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.newdawn.slick.opengl.GLUtils;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.renderer.Renderer;
import org.newdawn.slick.opengl.renderer.SGL;
import org.newdawn.slick.util.BufferedImageUtil;
/**
* A TrueType font implementation for Slick
*
* @author James Chambers (Jimmy)
* @author Jeremy Adams (elias4444)
* @author Kevin Glass (kevglass)
* @author Peter Korzuszek (genail)
*/
public class TrueTypeFont implements org.newdawn.slick.Font {
/** The renderer to use for all GL operations */
private static final SGL GL = Renderer.get();
/** Array that holds necessary information about the font characters */
private IntObject[] charArray = new IntObject[256];
/** Map of user defined font characters (Character <-> IntObject) */
private Map customChars = new HashMap();
/** Boolean flag on whether AntiAliasing is enabled or not */
private boolean antiAlias;
/** Font's size */
private int fontSize = 0;
/** Font's height */
private int fontHeight = 0;
/** Texture used to cache the font 0-255 characters */
private Texture fontTexture;
/** Default font texture width */
private int textureWidth = 512;
/** Default font texture height */
private int textureHeight = 512;
/** A reference to Java's AWT Font that we create our font texture from */
private java.awt.Font font;
/** The font metrics for our Java AWT font */
private FontMetrics fontMetrics;
/**
* This is a special internal class that holds our necessary information for
* the font characters. This includes width, height, and where the character
* is stored on the font texture.
*/
private class IntObject {
/** Character's width */
public int width;
/** Character's height */
public int height;
/** Character's stored x position */
public int storedX;
/** Character's stored y position */
public int storedY;
}
/**
* Constructor for the TrueTypeFont class Pass in the preloaded standard
* Java TrueType font, and whether you want it to be cached with
* AntiAliasing applied.
*
* @param font
* Standard Java AWT font
* @param antiAlias
* Whether or not to apply AntiAliasing to the cached font
* @param additionalChars
* Characters of font that will be used in addition of first 256 (by unicode).
*/
public TrueTypeFont(java.awt.Font font, boolean antiAlias, char[] additionalChars) {
GLUtils.checkGLContext();
this.font = font;
this.fontSize = font.getSize();
this.antiAlias = antiAlias;
createSet( additionalChars );
}
/**
* Constructor for the TrueTypeFont class Pass in the preloaded standard
* Java TrueType font, and whether you want it to be cached with
* AntiAliasing applied.
*
* @param font
* Standard Java AWT font
* @param antiAlias
* Whether or not to apply AntiAliasing to the cached font
*/
public TrueTypeFont(java.awt.Font font, boolean antiAlias) {
this( font, antiAlias, null );
}
/**
* Create a standard Java2D BufferedImage of the given character
*
* @param ch
* The character to create a BufferedImage for
*
* @return A BufferedImage containing the character
*/
private BufferedImage getFontImage(char ch) {
// Create a temporary image to extract the character's size
BufferedImage tempfontImage = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) tempfontImage.getGraphics();
if (antiAlias == true) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
g.setFont(font);
fontMetrics = g.getFontMetrics();
int charwidth = fontMetrics.charWidth(ch);
if (charwidth <= 0) {
charwidth = 1;
}
int charheight = fontMetrics.getHeight();
if (charheight <= 0) {
charheight = fontSize;
}
// Create another image holding the character we are creating
BufferedImage fontImage;
fontImage = new BufferedImage(charwidth, charheight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D gt = (Graphics2D) fontImage.getGraphics();
if (antiAlias == true) {
gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
gt.setFont(font);
gt.setColor(Color.WHITE);
int charx = 0;
int chary = 0;
gt.drawString(String.valueOf(ch), (charx), (chary)
+ fontMetrics.getAscent());
return fontImage;
}
/**
* Create and store the font
*
* @param customCharsArray Characters that should be also added to the cache.
*/
private void createSet( char[] customCharsArray ) {
// If there are custom chars then I expand the font texture twice
if (customCharsArray != null && customCharsArray.length > 0) {
textureWidth *= 2;
}
// In any case this should be done in other way. Texture with size 512x512
// can maintain only 256 characters with resolution of 32x32. The texture
// size should be calculated dynamicaly by looking at character sizes.
try {
BufferedImage imgTemp = new BufferedImage(textureWidth, textureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) imgTemp.getGraphics();
g.setColor(new Color(255,255,255,1));
g.fillRect(0,0,textureWidth,textureHeight);
int rowHeight = 0;
int positionX = 0;
int positionY = 0;
int customCharsLength = ( customCharsArray != null ) ? customCharsArray.length : 0;
for (int i = 0; i < 256 + customCharsLength; i++) {
// get 0-255 characters and then custom characters
char ch = ( i < 256 ) ? (char) i : customCharsArray[i-256];
BufferedImage fontImage = getFontImage(ch);
IntObject newIntObject = new IntObject();
newIntObject.width = fontImage.getWidth();
newIntObject.height = fontImage.getHeight();
if (positionX + newIntObject.width >= textureWidth) {
positionX = 0;
positionY += rowHeight;
rowHeight = 0;
}
newIntObject.storedX = positionX;
newIntObject.storedY = positionY;
if (newIntObject.height > fontHeight) {
fontHeight = newIntObject.height;
}
if (newIntObject.height > rowHeight) {
rowHeight = newIntObject.height;
}
// Draw it here
g.drawImage(fontImage, positionX, positionY, null);
positionX += newIntObject.width;
if( i < 256 ) { // standard characters
charArray[i] = newIntObject;
} else { // custom characters
customChars.put( new Character( ch ), newIntObject );
}
fontImage = null;
}
fontTexture = BufferedImageUtil
.getTexture(font.toString(), imgTemp);
} catch (IOException e) {
System.err.println("Failed to create font.");
e.printStackTrace();
}
}
/**
* Draw a textured quad
*
* @param drawX
* The left x position to draw to
* @param drawY
* The top y position to draw to
* @param drawX2
* The right x position to draw to
* @param drawY2
* The bottom y position to draw to
* @param srcX
* The left source x position to draw from
* @param srcY
* The top source y position to draw from
* @param srcX2
* The right source x position to draw from
* @param srcY2
* The bottom source y position to draw from
*/
private void drawQuad(float drawX, float drawY, float drawX2, float drawY2,
float srcX, float srcY, float srcX2, float srcY2) {
float DrawWidth = drawX2 - drawX;
float DrawHeight = drawY2 - drawY;
float TextureSrcX = srcX / textureWidth;
float TextureSrcY = srcY / textureHeight;
float SrcWidth = srcX2 - srcX;
float SrcHeight = srcY2 - srcY;
float RenderWidth = (SrcWidth / textureWidth);
float RenderHeight = (SrcHeight / textureHeight);
GL.glTexCoord2f(TextureSrcX, TextureSrcY);
GL.glVertex2f(drawX, drawY);
GL.glTexCoord2f(TextureSrcX, TextureSrcY + RenderHeight);
GL.glVertex2f(drawX, drawY + DrawHeight);
GL.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY + RenderHeight);
GL.glVertex2f(drawX + DrawWidth, drawY + DrawHeight);
GL.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY);
GL.glVertex2f(drawX + DrawWidth, drawY);
}
/**
* Get the width of a given String
*
* @param whatchars
* The characters to get the width of
*
* @return The width of the characters
*/
public int getWidth(String whatchars) {
int totalwidth = 0;
IntObject intObject = null;
int currentChar = 0;
for (int i = 0; i < whatchars.length(); i++) {
currentChar = whatchars.charAt(i);
if (currentChar < 256) {
intObject = charArray[currentChar];
} else {
intObject = (IntObject)customChars.get( new Character( (char) currentChar ) );
}
if( intObject != null )
totalwidth += intObject.width;
}
return totalwidth;
}
/**
* Get the font's height
*
* @return The height of the font
*/
public int getHeight() {
return fontHeight;
}
/**
* Get the height of a String
*
* @return The height of a given string
*/
public int getHeight(String HeightString) {
return fontHeight;
}
/**
* Get the font's line height
*
* @return The line height of the font
*/
public int getLineHeight() {
return fontHeight;
}
/**
* Draw a string
*
* @param x
* The x position to draw the string
* @param y
* The y position to draw the string
* @param whatchars
* The string to draw
* @param color
* The color to draw the text
*/
public void drawString(float x, float y, String whatchars,
org.newdawn.slick.Color color) {
drawString(x,y,whatchars,color,0,whatchars.length()-1);
}
/**
* @see Font#drawString(float, float, String, org.newdawn.slick.Color, int, int)
*/
public void drawString(float x, float y, String whatchars,
org.newdawn.slick.Color color, int startIndex, int endIndex) {
color.bind();
fontTexture.bind();
IntObject intObject = null;
int charCurrent;
GL.glBegin(SGL.GL_QUADS);
int totalwidth = 0;
for (int i = 0; i < whatchars.length(); i++) {
charCurrent = whatchars.charAt(i);
if (charCurrent < 256) {
intObject = charArray[charCurrent];
} else {
intObject = (IntObject)customChars.get( new Character( (char) charCurrent ) );
}
if( intObject != null ) {
if ((i >= startIndex) || (i <= endIndex)) {
drawQuad((x + totalwidth), y,
(x + totalwidth + intObject.width),
(y + intObject.height), intObject.storedX,
intObject.storedY, intObject.storedX + intObject.width,
intObject.storedY + intObject.height);
}
totalwidth += intObject.width;
}
}
GL.glEnd();
}
/**
* Draw a string
*
* @param x
* The x position to draw the string
* @param y
* The y position to draw the string
* @param whatchars
* The string to draw
*/
public void drawString(float x, float y, String whatchars) {
drawString(x, y, whatchars, org.newdawn.slick.Color.white);
}
}
| |
/**
* Copyright (c) 2012 Santoso Wijaya
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.swijaya.galaxytorch;
import java.io.IOException;
import java.util.List;
import android.hardware.Camera;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
public class CameraDevice {
public interface Torch {
public boolean toggleTorch(Camera camera, boolean on);
}
private static final String TAG = CameraDevice.class.getSimpleName();
private Camera mCamera;
private CameraDevice.Torch mTorch;
private boolean mIsFlashlightOn;
private boolean mIsPreviewStarted;
private Handler mHandler = new Handler();
private boolean mStateOn; // only used for strobing effect
private final Runnable mStrober = new Runnable() {
@Override
public void run() {
if (mIsFlashlightOn) {
if (mStateOn) {
// turn state on
mTorch.toggleTorch(mCamera, true);
mStateOn = false;
mHandler.postDelayed(this, 20);
} else {
// turn state off
mTorch.toggleTorch(mCamera, false);
mStateOn = true;
mHandler.postDelayed(this, 100);
}
} else {
mTorch.toggleTorch(mCamera, false);
}
}
};
public boolean isFlashlightOn() {
return mIsFlashlightOn;
}
private void postFlashlightState(boolean on) {
mIsFlashlightOn = on;
}
/* not currently used
protected Camera getCamera() {
return mCamera;
}
*/
/**
* Acquire the default camera object (it should support a flashlight).
* Subclasses can override this method for a more specialized usage of
* its camera hardware, if necessary.
*
* @return whether the method was successful
*/
public boolean acquireCamera() {
Log.v(TAG, "Acquiring camera...");
assert (mCamera == null);
try {
mCamera = Camera.open();
}
catch (RuntimeException e) {
Log.e(TAG, "Failed to open camera: " + e.getLocalizedMessage());
}
return (mCamera != null);
}
public void releaseCamera() {
if (mCamera != null) {
Log.v(TAG, "Releasing camera...");
if (mIsFlashlightOn) {
// attempt to cleanly turn off the torch (in case keeping a
// "torch" on is a hackery) prior to release
mTorch.toggleTorch(mCamera, false);
postFlashlightState(false);
}
stopPreview();
mCamera.release();
mCamera = null;
}
}
public void stopPreview() {
if (mIsPreviewStarted && mCamera != null) {
Log.v(TAG, "Stopping preview...");
mCamera.stopPreview();
mIsPreviewStarted = false;
}
}
public void startPreview() {
if (!mIsPreviewStarted && mCamera != null) {
Log.v(TAG, "Starting preview...");
mCamera.startPreview();
mIsPreviewStarted = true;
}
}
/**
* Supply the underlying camera device with a SurfaceHolder.
* Assume that the latter has been fully instantiated. That means,
* this method should be called within a SurfaceHolder.Callback.surfaceCreated
* callback. This method won't actually tell the camera device
* to Camera.startPreview(); do so by calling this wrapper object's
* startPreview().
*
* @param holder a fully instantiated SurfaceHolder
*/
public void setPreviewDisplay(SurfaceHolder holder) {
assert (mCamera != null);
if (mCamera == null) {
Log.wtf(TAG, "surfaceCreated called with NULL camera!");
return;
}
Log.v(TAG, "Setting preview display with a surface holder...");
try {
mCamera.setPreviewDisplay(holder);
}
catch (IOException e) {
Log.e(TAG, "Error setting camera preview: " + e.getLocalizedMessage());
}
}
public void setPreviewDisplayAndStartPreview(SurfaceHolder holder) {
setPreviewDisplay(holder);
startPreview();
}
private boolean supportsTorchMode() {
if (mCamera == null)
return false;
Camera.Parameters params = mCamera.getParameters();
List<String> flashModes = params.getSupportedFlashModes();
return (flashModes != null) &&
(flashModes.contains(Camera.Parameters.FLASH_MODE_TORCH));
}
/**
* Toggle the camera device's flashlight LED in a continuous or strobing manner.
* Pre-condition: the camera device, and its associated resources, has
* been acquired and set up
*
* @param on whether to toggle the flashlight LED on (true) or off (false)
* @param strobe whether to strobe the flashlight LED or not
* @return operation success
*/
public boolean toggleCameraLED(boolean on, boolean strobe) {
assert (mCamera != null);
if (mCamera == null) {
Log.wtf(TAG, "toggling with NULL camera!");
return false;
}
// check if the camera's flashlight supports torch mode
if (!supportsTorchMode()) {
// for now, bail early
// XXX: there might be workarounds; use specialized ITorch classes in such cases
Log.d(TAG, "This device does not support 'torch' mode");
return false;
}
// we've got a working torch-supported camera device now
mTorch = new DefaultTorch();
boolean success = false;
if (!strobe) {
Log.v(TAG, "Turning " + (on ? "on" : "off") + " camera LED...");
success = mTorch.toggleTorch(mCamera, on);
if (success) {
postFlashlightState(on);
}
} else {
Log.v(TAG, "Turning " + (on ? "on" : "off") + " camera LED in strobing mode...");
// strobing mode: must spawn and track a separate thread to do the strobing
postFlashlightState(on);
if (on) {
mHandler.post(mStrober);
}
success = true;
}
return success;
}
}
| |
// ========================================================================
// Copyright (c) 2003-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;
import org.eclipse.jetty.http.HttpException;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ConnectedEndPoint;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.io.nio.ChannelEndPoint;
import org.eclipse.jetty.server.BlockingHttpConnection;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.ConcurrentHashSet;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/* ------------------------------------------------------------------------------- */
/** Blocking NIO connector.
* This connector uses efficient NIO buffers with a traditional blocking thread model.
* Direct NIO buffers are used and a thread is allocated per connections.
*
* This connector is best used when there are a few very active connections.
*
* @org.apache.xbean.XBean element="blockingNioConnector" description="Creates a blocking NIO based socket connector"
*
*
*
*/
public class BlockingChannelConnector extends AbstractNIOConnector
{
private static final Logger LOG = Log.getLogger(BlockingChannelConnector.class);
private transient ServerSocketChannel _acceptChannel;
private final Set<BlockingChannelEndPoint> _endpoints = new ConcurrentHashSet<BlockingChannelEndPoint>();
/* ------------------------------------------------------------ */
/** Constructor.
*
*/
public BlockingChannelConnector()
{
}
/* ------------------------------------------------------------ */
public Object getConnection()
{
return _acceptChannel;
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.server.AbstractConnector#doStart()
*/
@Override
protected void doStart() throws Exception
{
super.doStart();
getThreadPool().dispatch(new Runnable()
{
public void run()
{
while (isRunning())
{
try
{
Thread.sleep(400);
long now=System.currentTimeMillis();
for (BlockingChannelEndPoint endp : _endpoints)
{
endp.checkIdleTimestamp(now);
}
}
catch(InterruptedException e)
{
LOG.ignore(e);
}
catch(Exception e)
{
LOG.warn(e);
}
}
}
});
}
/* ------------------------------------------------------------ */
public void open() throws IOException
{
// Create a new server socket and set to non blocking mode
_acceptChannel= ServerSocketChannel.open();
_acceptChannel.configureBlocking(true);
// Bind the server socket to the local host and port
InetSocketAddress addr = getHost()==null?new InetSocketAddress(getPort()):new InetSocketAddress(getHost(),getPort());
_acceptChannel.socket().bind(addr,getAcceptQueueSize());
}
/* ------------------------------------------------------------ */
public void close() throws IOException
{
if (_acceptChannel != null)
_acceptChannel.close();
_acceptChannel=null;
}
/* ------------------------------------------------------------ */
@Override
public void accept(int acceptorID)
throws IOException, InterruptedException
{
SocketChannel channel = _acceptChannel.accept();
channel.configureBlocking(true);
Socket socket=channel.socket();
configure(socket);
BlockingChannelEndPoint connection=new BlockingChannelEndPoint(channel);
connection.dispatch();
}
/* ------------------------------------------------------------------------------- */
@Override
public void customize(EndPoint endpoint, Request request)
throws IOException
{
super.customize(endpoint, request);
endpoint.setMaxIdleTime(_maxIdleTime);
configure(((SocketChannel)endpoint.getTransport()).socket());
}
/* ------------------------------------------------------------------------------- */
public int getLocalPort()
{
if (_acceptChannel==null || !_acceptChannel.isOpen())
return -1;
return _acceptChannel.socket().getLocalPort();
}
/* ------------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------------- */
private class BlockingChannelEndPoint extends ChannelEndPoint implements Runnable, ConnectedEndPoint
{
private Connection _connection;
private int _timeout;
private volatile long _idleTimestamp;
BlockingChannelEndPoint(ByteChannel channel)
throws IOException
{
super(channel,BlockingChannelConnector.this._maxIdleTime);
_connection = new BlockingHttpConnection(BlockingChannelConnector.this,this,getServer());
}
/* ------------------------------------------------------------ */
/** Get the connection.
* @return the connection
*/
public Connection getConnection()
{
return _connection;
}
/* ------------------------------------------------------------ */
public void setConnection(Connection connection)
{
_connection=connection;
}
/* ------------------------------------------------------------ */
public void checkIdleTimestamp(long now)
{
if (_idleTimestamp!=0 && _timeout>0 && now>(_idleTimestamp+_timeout))
{
idleExpired();
}
}
/* ------------------------------------------------------------ */
protected void idleExpired()
{
try
{
super.close();
}
catch (IOException e)
{
LOG.ignore(e);
}
}
/* ------------------------------------------------------------ */
void dispatch() throws IOException
{
if (!getThreadPool().dispatch(this))
{
LOG.warn("dispatch failed for {}",_connection);
super.close();
}
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.io.nio.ChannelEndPoint#fill(org.eclipse.jetty.io.Buffer)
*/
@Override
public int fill(Buffer buffer) throws IOException
{
_idleTimestamp=System.currentTimeMillis();
return super.fill(buffer);
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.io.nio.ChannelEndPoint#flush(org.eclipse.jetty.io.Buffer)
*/
@Override
public int flush(Buffer buffer) throws IOException
{
_idleTimestamp=System.currentTimeMillis();
return super.flush(buffer);
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.io.nio.ChannelEndPoint#flush(org.eclipse.jetty.io.Buffer, org.eclipse.jetty.io.Buffer, org.eclipse.jetty.io.Buffer)
*/
@Override
public int flush(Buffer header, Buffer buffer, Buffer trailer) throws IOException
{
_idleTimestamp=System.currentTimeMillis();
return super.flush(header,buffer,trailer);
}
/* ------------------------------------------------------------ */
public void run()
{
try
{
_timeout=getMaxIdleTime();
connectionOpened(_connection);
_endpoints.add(this);
while (isOpen())
{
_idleTimestamp=System.currentTimeMillis();
if (_connection.isIdle())
{
if (getServer().getThreadPool().isLowOnThreads())
{
int lrmit = getLowResourcesMaxIdleTime();
if (lrmit>=0 && _timeout!= lrmit)
{
_timeout=lrmit;
}
}
}
else
{
if (_timeout!=getMaxIdleTime())
{
_timeout=getMaxIdleTime();
}
}
_connection = _connection.handle();
}
}
catch (EofException e)
{
LOG.debug("EOF", e);
try{BlockingChannelEndPoint.this.close();}
catch(IOException e2){LOG.ignore(e2);}
}
catch (HttpException e)
{
LOG.debug("BAD", e);
try{super.close();}
catch(IOException e2){LOG.ignore(e2);}
}
catch(Throwable e)
{
LOG.warn("handle failed",e);
try{super.close();}
catch(IOException e2){LOG.ignore(e2);}
}
finally
{
connectionClosed(_connection);
_endpoints.remove(this);
// wait for client to close, but if not, close ourselves.
try
{
if (!_socket.isClosed())
{
long timestamp=System.currentTimeMillis();
int max_idle=getMaxIdleTime();
_socket.setSoTimeout(getMaxIdleTime());
int c=0;
do
{
c = _socket.getInputStream().read();
}
while (c>=0 && (System.currentTimeMillis()-timestamp)<max_idle);
if (!_socket.isClosed())
_socket.close();
}
}
catch(IOException e)
{
LOG.ignore(e);
}
}
}
/* ------------------------------------------------------------ */
@Override
public String toString()
{
return String.format("BCEP@%x{l(%s)<->r(%s),open=%b,ishut=%b,oshut=%b}-{%s}",
hashCode(),
_socket.getRemoteSocketAddress(),
_socket.getLocalSocketAddress(),
isOpen(),
isInputShutdown(),
isOutputShutdown(),
_connection);
}
}
}
| |
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.java.swing.plaf.windows;
import javax.swing.plaf.basic.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.*;
import java.awt.*;
import static com.sun.java.swing.plaf.windows.TMSchema.*;
import static com.sun.java.swing.plaf.windows.TMSchema.Part.*;
import static com.sun.java.swing.plaf.windows.XPStyle.Skin;
import sun.awt.AppContext;
/**
* Windows button.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is appropriate
* for short term storage or RMI between applications running the same
* version of Swing. A future release of Swing will provide support for
* long term persistence.
*
* @author Jeff Dinkins
*
*/
public class WindowsButtonUI extends BasicButtonUI
{
protected int dashedRectGapX;
protected int dashedRectGapY;
protected int dashedRectGapWidth;
protected int dashedRectGapHeight;
protected Color focusColor;
private boolean defaults_initialized = false;
private static final Object WINDOWS_BUTTON_UI_KEY = new Object();
// ********************************
// Create PLAF
// ********************************
public static ComponentUI createUI(JComponent c) {
AppContext appContext = AppContext.getAppContext();
WindowsButtonUI windowsButtonUI =
(WindowsButtonUI) appContext.get(WINDOWS_BUTTON_UI_KEY);
if (windowsButtonUI == null) {
windowsButtonUI = new WindowsButtonUI();
appContext.put(WINDOWS_BUTTON_UI_KEY, windowsButtonUI);
}
return windowsButtonUI;
}
// ********************************
// Defaults
// ********************************
protected void installDefaults(AbstractButton b) {
super.installDefaults(b);
if(!defaults_initialized) {
String pp = getPropertyPrefix();
dashedRectGapX = UIManager.getInt(pp + "dashedRectGapX");
dashedRectGapY = UIManager.getInt(pp + "dashedRectGapY");
dashedRectGapWidth = UIManager.getInt(pp + "dashedRectGapWidth");
dashedRectGapHeight = UIManager.getInt(pp + "dashedRectGapHeight");
focusColor = UIManager.getColor(pp + "focus");
defaults_initialized = true;
}
XPStyle xp = XPStyle.getXP();
if (xp != null) {
b.setBorder(xp.getBorder(b, getXPButtonType(b)));
LookAndFeel.installProperty(b, "rolloverEnabled", Boolean.TRUE);
}
}
protected void uninstallDefaults(AbstractButton b) {
super.uninstallDefaults(b);
defaults_initialized = false;
}
protected Color getFocusColor() {
return focusColor;
}
// ********************************
// Paint Methods
// ********************************
/**
* Overridden method to render the text without the mnemonic
*/
protected void paintText(Graphics g, AbstractButton b, Rectangle textRect, String text) {
WindowsGraphicsUtils.paintText(g, b, textRect, text, getTextShiftOffset());
}
protected void paintFocus(Graphics g, AbstractButton b, Rectangle viewRect, Rectangle textRect, Rectangle iconRect){
// focus painted same color as text on Basic??
int width = b.getWidth();
int height = b.getHeight();
g.setColor(getFocusColor());
BasicGraphicsUtils.drawDashedRect(g, dashedRectGapX, dashedRectGapY,
width - dashedRectGapWidth, height - dashedRectGapHeight);
}
protected void paintButtonPressed(Graphics g, AbstractButton b){
setTextShiftOffset();
}
// ********************************
// Layout Methods
// ********************************
public Dimension getPreferredSize(JComponent c) {
Dimension d = super.getPreferredSize(c);
/* Ensure that the width and height of the button is odd,
* to allow for the focus line if focus is painted
*/
AbstractButton b = (AbstractButton)c;
if (d != null && b.isFocusPainted()) {
if(d.width % 2 == 0) { d.width += 1; }
if(d.height % 2 == 0) { d.height += 1; }
}
return d;
}
/* These rectangles/insets are allocated once for all
* ButtonUI.paint() calls. Re-using rectangles rather than
* allocating them in each paint call substantially reduced the time
* it took paint to run. Obviously, this method can't be re-entered.
*/
private Rectangle viewRect = new Rectangle();
public void paint(Graphics g, JComponent c) {
if (XPStyle.getXP() != null) {
WindowsButtonUI.paintXPButtonBackground(g, c);
}
super.paint(g, c);
}
static Part getXPButtonType(AbstractButton b) {
if(b instanceof JCheckBox) {
return Part.BP_CHECKBOX;
}
if(b instanceof JRadioButton) {
return Part.BP_RADIOBUTTON;
}
boolean toolbar = (b.getParent() instanceof JToolBar);
return toolbar ? Part.TP_BUTTON : Part.BP_PUSHBUTTON;
}
static State getXPButtonState(AbstractButton b) {
Part part = getXPButtonType(b);
ButtonModel model = b.getModel();
State state = State.NORMAL;
switch (part) {
case BP_RADIOBUTTON:
/* falls through */
case BP_CHECKBOX:
if (! model.isEnabled()) {
state = (model.isSelected()) ? State.CHECKEDDISABLED
: State.UNCHECKEDDISABLED;
} else if (model.isPressed() && model.isArmed()) {
state = (model.isSelected()) ? State.CHECKEDPRESSED
: State.UNCHECKEDPRESSED;
} else if (model.isRollover()) {
state = (model.isSelected()) ? State.CHECKEDHOT
: State.UNCHECKEDHOT;
} else {
state = (model.isSelected()) ? State.CHECKEDNORMAL
: State.UNCHECKEDNORMAL;
}
break;
case BP_PUSHBUTTON:
/* falls through */
case TP_BUTTON:
boolean toolbar = (b.getParent() instanceof JToolBar);
if (toolbar) {
if (model.isArmed() && model.isPressed()) {
state = State.PRESSED;
} else if (!model.isEnabled()) {
state = State.DISABLED;
} else if (model.isSelected() && model.isRollover()) {
state = State.HOTCHECKED;
} else if (model.isSelected()) {
state = State.CHECKED;
} else if (model.isRollover()) {
state = State.HOT;
} else if (b.hasFocus()) {
state = State.HOT;
}
} else {
if ((model.isArmed() && model.isPressed())
|| model.isSelected()) {
state = State.PRESSED;
} else if (!model.isEnabled()) {
state = State.DISABLED;
} else if (model.isRollover() || model.isPressed()) {
state = State.HOT;
} else if (b instanceof JButton
&& ((JButton)b).isDefaultButton()) {
state = State.DEFAULTED;
} else if (b.hasFocus()) {
state = State.HOT;
}
}
break;
default :
state = State.NORMAL;
}
return state;
}
static void paintXPButtonBackground(Graphics g, JComponent c) {
AbstractButton b = (AbstractButton)c;
XPStyle xp = XPStyle.getXP();
Part part = getXPButtonType(b);
if (b.isContentAreaFilled() && xp != null) {
Skin skin = xp.getSkin(b, part);
State state = getXPButtonState(b);
Dimension d = c.getSize();
int dx = 0;
int dy = 0;
int dw = d.width;
int dh = d.height;
Border border = c.getBorder();
Insets insets;
if (border != null) {
// Note: The border may be compound, containing an outer
// opaque border (supplied by the application), plus an
// inner transparent margin border. We want to size the
// background to fill the transparent part, but stay
// inside the opaque part.
insets = WindowsButtonUI.getOpaqueInsets(border, c);
} else {
insets = c.getInsets();
}
if (insets != null) {
dx += insets.left;
dy += insets.top;
dw -= (insets.left + insets.right);
dh -= (insets.top + insets.bottom);
}
skin.paintSkin(g, dx, dy, dw, dh, state);
}
}
/**
* returns - b.getBorderInsets(c) if border is opaque
* - null if border is completely non-opaque
* - somewhere inbetween if border is compound and
* outside border is opaque and inside isn't
*/
private static Insets getOpaqueInsets(Border b, Component c) {
if (b == null) {
return null;
}
if (b.isBorderOpaque()) {
return b.getBorderInsets(c);
} else if (b instanceof CompoundBorder) {
CompoundBorder cb = (CompoundBorder)b;
Insets iOut = getOpaqueInsets(cb.getOutsideBorder(), c);
if (iOut != null && iOut.equals(cb.getOutsideBorder().getBorderInsets(c))) {
// Outside border is opaque, keep looking
Insets iIn = getOpaqueInsets(cb.getInsideBorder(), c);
if (iIn == null) {
// Inside is non-opaque, use outside insets
return iOut;
} else {
// Found non-opaque somewhere in the inside (which is
// also compound).
return new Insets(iOut.top + iIn.top, iOut.left + iIn.left,
iOut.bottom + iIn.bottom, iOut.right + iIn.right);
}
} else {
// Outside is either all non-opaque or has non-opaque
// border inside another compound border
return iOut;
}
} else {
return null;
}
}
}
| |
package com.suscipio_solutions.consecro_mud.core.smtp;
import java.util.Calendar;
import java.util.HashSet;
import java.util.LinkedList;
import com.suscipio_solutions.consecro_mud.Common.interfaces.PlayerAccount;
import com.suscipio_solutions.consecro_mud.Libraries.interfaces.JournalsLibrary;
import com.suscipio_solutions.consecro_mud.Libraries.interfaces.SMTPLibrary;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMProps;
import com.suscipio_solutions.consecro_mud.core.CMath;
import com.suscipio_solutions.consecro_mud.core.Log;
import com.suscipio_solutions.consecro_mud.core.exceptions.BadEmailAddressException;
public class MassMailer implements Runnable
{
private final LinkedList<MassMailerEntry> entries=new LinkedList<MassMailerEntry>();
private final CMProps page;
private final String domain;
private final HashSet<String> oldEmailComplaints;
private static class MassMailerEntry
{
public final JournalsLibrary.JournalEntry mail;
public final String journalName;
public final String overrideReplyTo;
public final boolean usePrivateRules;
public MassMailerEntry(JournalsLibrary.JournalEntry mail, String journalName, String overrideReplyTo, boolean usePrivateRules)
{
this.mail=mail;
this.journalName=journalName;
this.overrideReplyTo=overrideReplyTo;
this.usePrivateRules=usePrivateRules;
}
}
public MassMailer(CMProps page, String domain, HashSet<String> oldEmailComplaints)
{
this.page=page;
this.domain=domain;
this.oldEmailComplaints=oldEmailComplaints;
}
public String domainName() { return domain;}
public int getFailureDays()
{
final String s=page.getStr("FAILUREDAYS");
if(s==null) return (365*20);
final int x=CMath.s_int(s);
if(x==0) return (365*20);
return x;
}
public int getEmailDays()
{
final String s=page.getStr("EMAILDAYS");
if(s==null) return (365*20);
final int x=CMath.s_int(s);
if(x==0) return (365*20);
return x;
}
public boolean deleteEmailIfOld(String journalName, String key, long date, int days)
{
final Calendar IQE=Calendar.getInstance();
IQE.setTimeInMillis(date);
IQE.add(Calendar.DATE,days);
if(IQE.getTimeInMillis()<System.currentTimeMillis())
{
// email is a goner
CMLib.database().DBDeleteJournal(journalName, key);
return true;
}
return false;
}
public void addMail(JournalsLibrary.JournalEntry mail, String journalName, String overrideReplyTo, boolean usePrivateRules)
{
entries.add(new MassMailerEntry(mail,journalName,overrideReplyTo,usePrivateRules));
}
protected boolean rightTimeToSendEmail(long email)
{
final long curr=System.currentTimeMillis();
final Calendar IQE=Calendar.getInstance();
IQE.setTimeInMillis(email);
final Calendar IQC=Calendar.getInstance();
IQC.setTimeInMillis(curr);
if(CMath.absDiff(email,curr)<(30*60*1000)) return true;
while(IQE.before(IQC))
{
if(CMath.absDiff(IQE.getTimeInMillis(),IQC.getTimeInMillis())<(30*60*1000))
return true;
IQE.add(Calendar.DATE,1);
}
return false;
}
@Override
public void run()
{
for(final MassMailerEntry entry : entries)
{
final JournalsLibrary.JournalEntry mail=entry.mail;
final String journalName=entry.journalName;
final String overrideReplyTo=entry.overrideReplyTo;
final boolean usePrivateRules=entry.usePrivateRules;
final String key=mail.key;
final String from=mail.from;
final String to=mail.to;
final long date=mail.update;
final String subj=mail.subj;
final String msg=mail.msg.trim();
if(to.equalsIgnoreCase("ALL")||(to.toUpperCase().trim().startsWith("MASK="))) continue;
if(!rightTimeToSendEmail(date)) continue;
// check for valid recipient
final String toEmail;
final String toName;
if(CMLib.players().playerExists(to))
{
final MOB toM=CMLib.players().getLoadPlayer(to);
// check to see if the sender is ignored
if((toM.playerStats()!=null)
&&(toM.playerStats().getIgnored().contains(from)))
{
// email is ignored
CMLib.database().DBDeleteJournal(journalName,key);
continue;
}
if(toM.isAttribute(MOB.Attrib.AUTOFORWARD)) // forwarding OFF
continue;
if((toM.playerStats()==null)
||(toM.playerStats().getEmail().length()==0)) // no email addy to forward TO
continue;
toName=toM.Name();
toEmail=toM.playerStats().getEmail();
}
else
if(CMLib.players().accountExists(to))
{
final PlayerAccount P=CMLib.players().getLoadAccount(to);
if((P.getEmail().length()==0)) // no email addy to forward TO
continue;
toName=P.getAccountName();
toEmail=P.getEmail();
}
else
{
Log.errOut("SMTPServer","Invalid to address '"+to+"' in email: "+msg);
CMLib.database().DBDeleteJournal(journalName,key);
continue;
}
// check email age
if((usePrivateRules)
&&(!CMath.bset(mail.attributes, JournalsLibrary.JournalEntry.ATTRIBUTE_PROTECTED))
&&(deleteEmailIfOld(journalName, key, date, getEmailDays())))
continue;
SMTPLibrary.SMTPClient SC=null;
try
{
if(CMProps.getVar(CMProps.Str.SMTPSERVERNAME).length()>0)
SC=CMLib.smtp().getClient(CMProps.getVar(CMProps.Str.SMTPSERVERNAME),SMTPLibrary.DEFAULT_PORT);
else
SC=CMLib.smtp().getClient(toEmail);
}
catch(final BadEmailAddressException be)
{
if((!usePrivateRules)
&&(!CMath.bset(mail.attributes, JournalsLibrary.JournalEntry.ATTRIBUTE_PROTECTED)))
{
// email is a goner if its a list
CMLib.database().DBDeleteJournal(journalName,key);
continue;
}
// otherwise it has its n days
continue;
}
catch(final java.io.IOException ioe)
{
if(!oldEmailComplaints.contains(toName))
{
oldEmailComplaints.add(toName);
Log.errOut("SMTPServer","Unable to send '"+toEmail+"' for '"+toName+"': "+ioe.getMessage());
}
if(!CMath.bset(mail.attributes, JournalsLibrary.JournalEntry.ATTRIBUTE_PROTECTED))
deleteEmailIfOld(journalName, key, date,getFailureDays());
continue;
}
final String replyTo=(overrideReplyTo!=null)?(overrideReplyTo):from;
try
{
SC.sendMessage(from+"@"+domainName(),
replyTo+"@"+domainName(),
toEmail,
usePrivateRules?toEmail:replyTo+"@"+domainName(),
subj,
CMLib.coffeeFilter().simpleOutFilter(msg));
//this email is HISTORY!
CMLib.database().DBDeleteJournal(journalName, key);
}
catch(final java.io.IOException ioe)
{
// it has FAILUREDAYS days to get better.
if(deleteEmailIfOld(journalName, key, date,getFailureDays()))
Log.errOut("SMTPServer","Permanently unable to send to '"+toEmail+"' for user '"+toName+"': "+ioe.getMessage()+".");
else
Log.errOut("SMTPServer","Failure to send to '"+toEmail+"' for user '"+toName+"'.");
}
}
}
}
| |
/*
* Copyright 2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.thrift.io;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TField;
import org.apache.thrift.protocol.TList;
import org.apache.thrift.protocol.TMap;
import org.apache.thrift.protocol.TMessage;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TSet;
import org.apache.thrift.protocol.TStruct;
/**
* Replace list field protocol.
*
* @author jaehong.kim
*/
public class TReplaceListProtocol extends TProtocol {
private boolean writeFieldBegin = false;
private int writeListDepth = 0;
private Map<String, List<ByteArrayOutput>> replaceFields = new HashMap<String, List<ByteArrayOutput>>();
private TField currentField = null;
private TProtocol protocol;
public TReplaceListProtocol(final TProtocol protocol) {
super(protocol.getTransport());
this.protocol = protocol;
}
public void addReplaceField(final String fieldName, List<ByteArrayOutput> outputs) {
if (fieldName == null) {
throw new IllegalArgumentException("field name must not be null");
}
if (outputs == null || outputs.isEmpty()) {
throw new IllegalArgumentException("stream nodes must not be empty");
}
replaceFields.put(fieldName, outputs);
}
@Override
public void writeFieldBegin(TField field) throws TException {
if (!writeFieldBegin) {
protocol.writeFieldBegin(field);
if (replaceFields.containsKey(field.name)) {
writeFieldBegin = true;
currentField = field;
}
}
}
@Override
public void writeFieldEnd() throws TException {
if (!writeFieldBegin) {
protocol.writeFieldEnd();
} else if (writeListDepth == 0) {
writeFieldBegin = false;
currentField = null;
}
}
@Override
public void writeListBegin(TList list) throws TException {
if (!writeFieldBegin) {
protocol.writeListBegin(list);
return;
}
if (writeListDepth == 0 && currentField != null) {
List<ByteArrayOutput> outputs = replaceFields.get(currentField.name);
if (outputs == null) {
throw new TException("not found replace field - " + currentField.name);
}
final TList replaceList = new TList(list.elemType, outputs.size());
protocol.writeListBegin(replaceList);
for (ByteArrayOutput output : outputs) {
try {
final OutputStream out = ((ByteArrayOutputStreamTransport) getTransport()).getByteArrayOutputStream();
output.writeTo(out);
} catch (IOException e) {
throw new TException(e);
}
}
}
writeListDepth++;
}
@Override
public void writeListEnd() throws TException {
if (!writeFieldBegin) {
protocol.writeListEnd();
} else {
writeListDepth--;
}
}
@Override
public void reset() {
protocol.reset();
}
@Override
public void writeMessageBegin(TMessage message) throws TException {
if (!writeFieldBegin) {
protocol.writeMessageBegin(message);
}
}
@Override
public void writeMessageEnd() throws TException {
if (!writeFieldBegin) {
protocol.writeMessageEnd();
}
}
@Override
public void writeStructBegin(TStruct struct) throws TException {
if (!writeFieldBegin) {
protocol.writeStructBegin(struct);
}
}
@Override
public void writeStructEnd() throws TException {
if (!writeFieldBegin) {
protocol.writeStructEnd();
}
}
@Override
public void writeFieldStop() throws TException {
if (!writeFieldBegin) {
protocol.writeFieldStop();
}
}
@Override
public void writeMapBegin(TMap map) throws TException {
if (!writeFieldBegin) {
protocol.writeMapBegin(map);
}
}
@Override
public void writeMapEnd() throws TException {
if (!writeFieldBegin) {
protocol.writeMapEnd();
}
}
@Override
public void writeSetBegin(TSet set) throws TException {
if (!writeFieldBegin) {
protocol.writeSetBegin(set);
}
}
@Override
public void writeSetEnd() throws TException {
if (!writeFieldBegin) {
protocol.writeSetEnd();
}
}
@Override
public void writeBool(boolean b) throws TException {
if (!writeFieldBegin) {
protocol.writeBool(b);
}
}
@Override
public void writeByte(byte b) throws TException {
if (!writeFieldBegin) {
protocol.writeByte(b);
}
}
@Override
public void writeI16(short i16) throws TException {
if (!writeFieldBegin) {
protocol.writeI16(i16);
}
}
@Override
public void writeI32(int i32) throws TException {
if (!writeFieldBegin) {
protocol.writeI32(i32);
}
}
@Override
public void writeI64(long i64) throws TException {
if (!writeFieldBegin) {
protocol.writeI64(i64);
}
}
@Override
public void writeDouble(double dub) throws TException {
if (!writeFieldBegin) {
protocol.writeDouble(dub);
}
}
@Override
public void writeString(String str) throws TException {
if (!writeFieldBegin) {
protocol.writeString(str);
}
}
@Override
public void writeBinary(ByteBuffer bin) throws TException {
if (!writeFieldBegin) {
protocol.writeBinary(bin);
}
}
@Override
public ByteBuffer readBinary() throws TException {
throw new TException("unsupported operation");
}
@Override
public boolean readBool() throws TException {
throw new TException("unsupported operation");
}
@Override
public byte readByte() throws TException {
throw new TException("unsupported operation");
}
@Override
public double readDouble() throws TException {
throw new TException("unsupported operation");
}
@Override
public TField readFieldBegin() throws TException {
throw new TException("unsupported operation");
}
@Override
public void readFieldEnd() throws TException {
throw new TException("unsupported operation");
}
@Override
public short readI16() throws TException {
throw new TException("unsupported operation");
}
@Override
public int readI32() throws TException {
throw new TException("unsupported operation");
}
@Override
public long readI64() throws TException {
throw new TException("unsupported operation");
}
@Override
public TList readListBegin() throws TException {
throw new TException("unsupported operation");
}
@Override
public void readListEnd() throws TException {
throw new TException("unsupported operation");
}
@Override
public TMap readMapBegin() throws TException {
throw new TException("unsupported operation");
}
@Override
public void readMapEnd() throws TException {
throw new TException("unsupported operation");
}
@Override
public TMessage readMessageBegin() throws TException {
throw new TException("unsupported operation");
}
@Override
public void readMessageEnd() throws TException {
throw new TException("unsupported operation");
}
@Override
public TSet readSetBegin() throws TException {
throw new TException("unsupported operation");
}
@Override
public void readSetEnd() throws TException {
throw new TException("unsupported operation");
}
@Override
public String readString() throws TException {
throw new TException("unsupported operation");
}
@Override
public TStruct readStructBegin() throws TException {
throw new TException("unsupported operation");
}
@Override
public void readStructEnd() throws TException {
throw new TException("unsupported operation");
}
}
| |
package com.formulasearchengine.mathosphere.pomlp.xml;
import com.formulasearchengine.mathosphere.pomlp.GoldStandardLoader;
import com.formulasearchengine.mathosphere.pomlp.gouldi.JsonGouldiBean;
import com.formulasearchengine.mathosphere.pomlp.util.config.ConfigLoader;
import net.sf.saxon.expr.flwor.Tuple;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.xml.transform.Source;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Andre Greiner-Petter
*/
public class DLMFWebLoader {
public static final Logger LOG = LogManager.getLogger(DLMFWebLoader.class.getName());
public static final String EXIT_CODE = "--quit--";
private GoldStandardLoader gouldi;
private Path outputFile;
private HashSet<String> loadedSet;
private LinkedList<URI> websitesList;
private LinkedBlockingQueue<SimpleInfoHolder> rawLoadedWebsitesQueue;
private LinkedBlockingQueue<SimpleInfoHolder> postProcessedWebsitesQueue;
private RestTemplate restTemplate;
private static final int min = 101, max = 200;
public DLMFWebLoader(){
gouldi = GoldStandardLoader.getInstance();
}
public void init() throws IOException, URISyntaxException {
LOG.info("Init multithreaded loader process for DLMF.");
gouldi.initLocally();
String gouldiPath = ConfigLoader.CONFIG.getProperty( ConfigLoader.GOULDI_LOCAL_PATH );
outputFile = Paths
.get( gouldiPath )
.resolve("..")
.resolve("dlmfSource")
.resolve("dlmf.xml");
if ( !Files.exists(outputFile) ) Files.createFile(outputFile);
loadedSet = new HashSet<>();
websitesList = new LinkedList<>();
rawLoadedWebsitesQueue = new LinkedBlockingQueue<>();
postProcessedWebsitesQueue = new LinkedBlockingQueue<>();
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout( 2000 );
factory.setReadTimeout( 5000 );
restTemplate = new RestTemplate(factory);
JsonGouldiBean currBean;
URL url;
for ( int idx = min; idx <= max; idx++ ){
currBean = gouldi.getGouldiJson(idx);
url = new URL(currBean.getUri());
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), null);
if ( !loadedSet.contains( uri.toString() ) ){
loadedSet.add(uri.toString());
websitesList.add( uri );
} else {
LOG.debug("Skip ID " + idx + " to avoid duplicated page loading.");
}
}
}
private void startProcess() {
LOG.info("Fill thread pools in reverse order.");
LOG.info("Start writer process.");
new Thread(
new Writer( outputFile, postProcessedWebsitesQueue ),
"WriterProcess"
).start();
LOG.info("Init 2 post processors.");
ExecutorService postProcessorPool = Executors.newFixedThreadPool(2);
postProcessorPool.submit(new PostProcessor( rawLoadedWebsitesQueue, postProcessedWebsitesQueue ));
postProcessorPool.submit(new PostProcessor( rawLoadedWebsitesQueue, postProcessedWebsitesQueue ));
LOG.info("Load websites.");
ExecutorService pageLoaderPool = Executors.newFixedThreadPool(6);
while ( !websitesList.isEmpty() ){
pageLoaderPool.submit(
new WebsiteLoader(
restTemplate,
websitesList.removeFirst(),
rawLoadedWebsitesQueue
)
);
}
try {
LOG.info("Process running. Wait at most 10 minutes until send stop signal to all process.");
pageLoaderPool.shutdown();
postProcessorPool.shutdown();
pageLoaderPool.awaitTermination( 10, TimeUnit.MINUTES );
LOG.info("Loading process finished. Inform others about the end of the process.");
rawLoadedWebsitesQueue.add(new SimpleInfoHolder(null, EXIT_CODE));
postProcessorPool.awaitTermination( 2, TimeUnit.MINUTES );
postProcessedWebsitesQueue.add(new SimpleInfoHolder(null, EXIT_CODE));
} catch (InterruptedException e) {
LOG.error("Cannot wait until end of termination.", e);
}
}
public static void main(String[] args) throws Exception {
DLMFWebLoader loader = new DLMFWebLoader();
LOG.info("Init loader.");
loader.init();
LOG.info("Start loader...");
loader.startProcess();
}
private class SimpleInfoHolder {
private URI uri;
private String input;
public SimpleInfoHolder(URI uri, String input){
this.uri = uri;
this.input = input;
}
}
private class WebsiteLoader implements Runnable {
private final Logger LOG = LogManager.getLogger(WebsiteLoader.class.getName());
private LinkedBlockingQueue<SimpleInfoHolder> rawWebPageQueue;
private final URI uri;
private final RestTemplate rest;
public WebsiteLoader( RestTemplate rest, URI uri, LinkedBlockingQueue rawWebPageQueue){
this.rawWebPageQueue = rawWebPageQueue;
this.uri = uri;
this.rest = rest;
}
@Override
public void run() {
try {
LOG.info( "Wait for response: " + uri.toString() );
String webPage = rest.getForObject( uri, String.class );
rawWebPageQueue.put( new SimpleInfoHolder(uri, webPage) );
} catch ( Exception e ){
LOG.error("Cannot load websites.", e);
}
}
}
private class PostProcessor implements Runnable {
private final Logger LOG = LogManager.getLogger(PostProcessor.class.getName());
private LinkedBlockingQueue<SimpleInfoHolder> rawWebPageQueue;
private LinkedBlockingQueue<SimpleInfoHolder> processedPageQueue;
private static final int OPEN_BODY_IDX = 1;
private static final int CLOSE_BODY_IDX = 2;
private static final String TAGS = "<link.+?>\r?\n?|<script.+</script>\r?\n?|(<body)|(</body>)|<a((?!<math).)*</a>\r?\n?";
private Pattern pattern;
public PostProcessor( LinkedBlockingQueue rawWebPageQueue, LinkedBlockingQueue processedPageQueue ){
this.rawWebPageQueue = rawWebPageQueue;
this.processedPageQueue = processedPageQueue;
this.pattern = Pattern.compile( TAGS );
}
private String postProcess(String in){
StringBuffer buffer = new StringBuffer();
Matcher matcher = pattern.matcher( in );
while( matcher.find() ){
if ( matcher.group(OPEN_BODY_IDX) != null ){
// LOG.trace("Found body start, wrap it by text block. " + matcher.group(0));
matcher.appendReplacement( buffer, "<text><body" );
}
else if ( matcher.group(CLOSE_BODY_IDX) != null ){
// LOG.trace("Found body end, close text wrapping." + matcher.group(0));
matcher.appendReplacement( buffer, "</body></text>" );
}
else {
// LOG.trace("Found something else, delete: " + matcher.group(0));
matcher.appendReplacement( buffer, "" );
}
}
matcher.appendTail(buffer);
return buffer.toString();
}
@Override
public void run() {
LOG.info("Start post processor.");
try {
SimpleInfoHolder info;
while( !( info = rawWebPageQueue.take()).input.equals(EXIT_CODE) ){
LOG.info("Start post processing: " + info.uri.toString());
info.input = postProcess(info.input);
LOG.info("Finished post processing: " + info.uri.toString());
processedPageQueue.put( info );
}
// put EXIT code back to queue for other waiting services.
rawWebPageQueue.put( info );
LOG.info("Post processor received exit signal - done!");
} catch ( InterruptedException ie ){
LOG.error("Cannot post process, interrupted queue process.", ie);
}
}
}
private class Writer implements Runnable {
private final Logger LOG = LogManager.getLogger(Writer.class.getName());
private final String NL = System.lineSeparator();
private Path file;
private BufferedWriter writer;
private LinkedBlockingQueue<SimpleInfoHolder> processedQueue;
public Writer( Path file, LinkedBlockingQueue processedQueue ){
this.file = file;
this.processedQueue = processedQueue;
}
private void init() throws IOException {
writer = Files.newBufferedWriter( file );
LOG.info("Write mother root.");
writer.write("<root>");
}
private void end() throws IOException {
LOG.info("Write end root.");
writer.write("</root>");
writer.close();
}
private void write( String processedPage ) throws IOException {
LOG.info("Write next page.");
writer.write("<page>" + NL);
writer.write(processedPage);
writer.write("</page>" + NL);
LOG.info("Done writing single page.");
}
@Override
public void run() {
try {
LOG.info("Start writing process...");
init();
SimpleInfoHolder info;
while ( !(info = this.processedQueue.take()).input.equals(EXIT_CODE) ){
LOG.info("Write next page: " + info.uri);
write( info.input );
}
// put exit code back to queue for other waiting services
processedQueue.put(info);
LOG.info("Received exit code. Finish writing process.");
end();
} catch ( IOException ioe ){
LOG.error("Cannot write output file!", ioe);
} catch ( InterruptedException ie ){
LOG.error("Interrupted reading from processed queue.", ie);
}
}
}
}
| |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util.newProjectWizard;
import com.intellij.ide.highlighter.ModuleFileType;
import com.intellij.ide.highlighter.ProjectFileType;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.ProjectBuilder;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.ide.wizard.AbstractWizard;
import com.intellij.ide.wizard.CommitStepException;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.StorageScheme;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.IdeBorderFactory;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.awt.*;
import java.io.File;
/**
* @author Dmitry Avdeev
* Date: 19.09.13
*/
public abstract class AbstractProjectWizard extends AbstractWizard<ModuleWizardStep> {
protected final WizardContext myWizardContext;
public AbstractProjectWizard(String title, Project project, String defaultPath) {
super(title, project);
myWizardContext = initContext(project, defaultPath, getDisposable());
}
public AbstractProjectWizard(String title, Project project, Component dialogParent) {
super(title, dialogParent);
myWizardContext = initContext(project, null, getDisposable());
}
@Override
protected String addStepComponent(Component component) {
if (component instanceof JComponent) {
((JComponent)component).setBorder(IdeBorderFactory.createEmptyBorder(0, 0, 0, 0));
}
return super.addStepComponent(component);
}
public abstract StepSequence getSequence();
private static WizardContext initContext(@Nullable Project project, @Nullable String defaultPath, Disposable parentDisposable) {
WizardContext context = new WizardContext(project, parentDisposable);
if (defaultPath != null) {
context.setProjectFileDirectory(defaultPath);
context.setProjectName(defaultPath.substring(FileUtil.toSystemIndependentName(defaultPath).lastIndexOf("/") + 1));
}
return context;
}
@Nullable
public static Sdk getNewProjectJdk(WizardContext context) {
if (context.getProjectJdk() != null) {
return context.getProjectJdk();
}
return getProjectSdkByDefault(context);
}
public static Sdk getProjectSdkByDefault(WizardContext context) {
final Project project = context.getProject() == null ? ProjectManager.getInstance().getDefaultProject() : context.getProject();
final Sdk projectJdk = ProjectRootManager.getInstance(project).getProjectSdk();
if (projectJdk != null) {
return projectJdk;
}
return null;
}
@NotNull
public String getNewProjectFilePath() {
if (myWizardContext.getProjectStorageFormat() == StorageScheme.DEFAULT) {
return myWizardContext.getProjectFileDirectory() + File.separator + myWizardContext.getProjectName() + ProjectFileType.DOT_DEFAULT_EXTENSION;
}
else {
return myWizardContext.getProjectFileDirectory();
}
}
@NotNull
public StorageScheme getStorageScheme() {
return myWizardContext.getProjectStorageFormat();
}
public ProjectBuilder getProjectBuilder() {
return myWizardContext.getProjectBuilder();
}
public String getProjectName() {
return myWizardContext.getProjectName();
}
@Nullable
public Sdk getNewProjectJdk() {
return getNewProjectJdk(myWizardContext);
}
@NotNull
public String getNewCompileOutput() {
final String projectFilePath = myWizardContext.getProjectFileDirectory();
@NonNls String path = myWizardContext.getCompilerOutputDirectory();
if (path == null) {
path = StringUtil.endsWithChar(projectFilePath, '/') ? projectFilePath + "out" : projectFilePath + "/out";
}
return path;
}
@Override
protected void updateStep() {
if (!mySteps.isEmpty()) {
getCurrentStepObject().updateStep();
}
super.updateStep();
myIcon.setIcon(null);
}
@Override
protected void dispose() {
StepSequence sequence = getSequence();
if (sequence != null) {
for (ModuleWizardStep step : sequence.getAllSteps()) {
step.disposeUIResources();
}
}
super.dispose();
}
@Override
protected final void doOKAction() {
if (!doFinishAction()) return;
super.doOKAction();
}
public boolean doFinishAction() {
int idx = getCurrentStep();
try {
do {
final ModuleWizardStep step = mySteps.get(idx);
if (step != getCurrentStepObject()) {
step.updateStep();
}
if (!commitStepData(step)) {
return false;
}
step.onStepLeaving();
try {
step._commit(true);
}
catch (CommitStepException e) {
handleCommitException(e);
return false;
}
if (!isLastStep(idx)) {
idx = getNextStep(idx);
}
else {
for (ModuleWizardStep wizardStep : mySteps) {
try {
wizardStep.onWizardFinished();
}
catch (CommitStepException e) {
handleCommitException(e);
return false;
}
}
break;
}
} while (true);
}
finally {
myCurrentStep = idx;
updateStep();
}
return true;
}
private void handleCommitException(CommitStepException e) {
String message = e.getMessage();
if (message != null) {
Messages.showErrorDialog(getCurrentStepComponent(), message);
}
}
protected boolean commitStepData(final ModuleWizardStep step) {
try {
if (!step.validate()) {
return false;
}
}
catch (ConfigurationException e) {
Messages.showErrorDialog(myContentPanel, e.getMessage(), e.getTitle());
return false;
}
step.updateDataModel();
return true;
}
@Override
public void doNextAction() {
final ModuleWizardStep step = getCurrentStepObject();
if (!commitStepData(step)) {
return;
}
step.onStepLeaving();
super.doNextAction();
}
@Override
protected String getHelpID() {
ModuleWizardStep step = getCurrentStepObject();
if (step != null) {
return step.getHelpId();
}
return null;
}
@TestOnly
public boolean isLast() {
return isLastStep();
}
@NonNls
public String getModuleFilePath() {
return myWizardContext.getProjectFileDirectory() + File.separator + myWizardContext.getProjectName() + ModuleFileType.DOT_DEFAULT_EXTENSION;
}
@Override
protected void doPreviousAction() {
final ModuleWizardStep step = getCurrentStepObject();
step.onStepLeaving();
super.doPreviousAction();
}
@Override
public void doCancelAction() {
final ModuleWizardStep step = getCurrentStepObject();
step.onStepLeaving();
super.doCancelAction();
}
private boolean isLastStep(int step) {
return getNextStep(step) == step;
}
@Override
protected final int getNextStep(final int step) {
ModuleWizardStep nextStep = null;
final StepSequence stepSequence = getSequence();
if (stepSequence != null) {
ModuleWizardStep current = mySteps.get(step);
nextStep = stepSequence.getNextStep(current);
while (nextStep != null && !nextStep.isStepVisible()) {
nextStep = stepSequence.getNextStep(nextStep);
}
}
return nextStep == null ? step : mySteps.indexOf(nextStep);
}
@Override
protected final int getPreviousStep(final int step) {
ModuleWizardStep previousStep = null;
final StepSequence stepSequence = getSequence();
if (stepSequence != null) {
previousStep = stepSequence.getPreviousStep(mySteps.get(step));
while (previousStep != null && !previousStep.isStepVisible()) {
previousStep = stepSequence.getPreviousStep(previousStep);
}
}
return previousStep == null ? 0 : mySteps.indexOf(previousStep);
}
}
| |
package ca.uhn.fhir.jpa.provider.r4;
import ca.uhn.fhir.interceptor.api.HookParams;
import ca.uhn.fhir.interceptor.api.IAnonymousInterceptor;
import ca.uhn.fhir.interceptor.api.Pointcut;
import ca.uhn.fhir.jpa.api.config.DaoConfig;
import ca.uhn.fhir.jpa.binstore.IBinaryStorageSvc;
import ca.uhn.fhir.jpa.binstore.MemoryBinaryStorageSvcImpl;
import ca.uhn.fhir.jpa.interceptor.UserRequestRetryVersionConflictsInterceptor;
import ca.uhn.fhir.jpa.model.util.JpaConstants;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.exceptions.ResourceGoneException;
import ca.uhn.fhir.util.HapiExtensions;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.r4.model.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.in;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
public class BinaryAccessProviderR4Test extends BaseResourceProviderR4Test {
public static final byte[] SOME_BYTES = {1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};
public static final byte[] SOME_BYTES_2 = {5, 5, 5, 6};
private static final Logger ourLog = LoggerFactory.getLogger(BinaryAccessProviderR4Test.class);
@Autowired
private MemoryBinaryStorageSvcImpl myStorageSvc;
@Autowired
private IBinaryStorageSvc myBinaryStorageSvc;
@Override
@BeforeEach
public void before() throws Exception {
super.before();
myStorageSvc.setMinimumBinarySize(10);
myDaoConfig.setExpungeEnabled(true);
myInterceptorRegistry.registerInterceptor(myBinaryStorageInterceptor);
}
@Override
@AfterEach
public void after() throws Exception {
super.after();
myStorageSvc.setMinimumBinarySize(0);
myDaoConfig.setExpungeEnabled(new DaoConfig().isExpungeEnabled());
}
@Test
public void testRead() throws IOException {
IIdType id = createDocumentReference(true);
IAnonymousInterceptor interceptor = mock(IAnonymousInterceptor.class);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESHOW_RESOURCES, interceptor);
doAnswer(t -> {
Pointcut pointcut = t.getArgument(0, Pointcut.class);
HookParams params = t.getArgument(1, HookParams.class);
ourLog.info("Interceptor invoked with pointcut {} and params {}", pointcut, params);
return null;
}).when(interceptor).invoke(any(), any());
// Read it back using the operation
String path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_READ +
"?path=DocumentReference.content.attachment";
HttpGet get = new HttpGet(path);
try (CloseableHttpResponse resp = ourHttpClient.execute(get)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertEquals("image/png", resp.getEntity().getContentType().getValue());
assertEquals(SOME_BYTES.length, resp.getEntity().getContentLength());
byte[] actualBytes = IOUtils.toByteArray(resp.getEntity().getContent());
assertArrayEquals(SOME_BYTES, actualBytes);
}
verify(interceptor, times(1)).invoke(eq(Pointcut.STORAGE_PRESHOW_RESOURCES), any());
}
@Test
public void testReadSecondInstance() throws IOException {
IIdType id = createDocumentReference(true);
IAnonymousInterceptor interceptor = mock(IAnonymousInterceptor.class);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESHOW_RESOURCES, interceptor);
// Read it back using the operation
String path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_READ +
"?path=DocumentReference.content[1].attachment";
HttpGet get = new HttpGet(path);
try (CloseableHttpResponse resp = ourHttpClient.execute(get)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertEquals("image/gif", resp.getEntity().getContentType().getValue());
assertEquals(SOME_BYTES_2.length, resp.getEntity().getContentLength());
byte[] actualBytes = IOUtils.toByteArray(resp.getEntity().getContent());
assertArrayEquals(SOME_BYTES_2, actualBytes);
}
verify(interceptor, times(1)).invoke(eq(Pointcut.STORAGE_PRESHOW_RESOURCES), any());
}
@Test
public void testReadNoPath() throws IOException {
IIdType id = createDocumentReference(true);
String path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_READ;
HttpGet get = new HttpGet(path);
try (CloseableHttpResponse resp = ourHttpClient.execute(get)) {
assertEquals(400, resp.getStatusLine().getStatusCode());
String response = IOUtils.toString(resp.getEntity().getContent(), Charsets.UTF_8);
assertThat(response, containsString("No path specified"));
}
}
@Test
public void testReadNoData() throws IOException {
IIdType id = createDocumentReference(false);
String path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_READ +
"?path=DocumentReference.content.attachment";
HttpGet get = new HttpGet(path);
try (CloseableHttpResponse resp = ourHttpClient.execute(get)) {
assertEquals(400, resp.getStatusLine().getStatusCode());
String response = IOUtils.toString(resp.getEntity().getContent(), Charsets.UTF_8);
assertThat(response, matchesPattern(".*The resource with ID DocumentReference/[0-9]+ has no data at path.*"));
}
}
@Test
public void testReadUnknownBlobId() throws IOException {
IIdType id = createDocumentReference(false);
// Write a binary using the operation
String path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_WRITE +
"?path=DocumentReference.content.attachment";
HttpPost post = new HttpPost(path);
post.setEntity(new ByteArrayEntity(SOME_BYTES, ContentType.IMAGE_JPEG));
post.addHeader("Accept", "application/fhir+json; _pretty=true");
String attachmentId;
try (CloseableHttpResponse resp = ourHttpClient.execute(post)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertThat(resp.getEntity().getContentType().getValue(), containsString("application/fhir+json"));
String response = IOUtils.toString(resp.getEntity().getContent(), Constants.CHARSET_UTF8);
ourLog.info("Response: {}", response);
DocumentReference ref = myFhirCtx.newJsonParser().parseResource(DocumentReference.class, response);
Attachment attachment = ref.getContentFirstRep().getAttachment();
assertEquals(ContentType.IMAGE_JPEG.getMimeType(), attachment.getContentType());
assertEquals(15, attachment.getSize());
assertEquals(null, attachment.getData());
assertEquals("2", ref.getMeta().getVersionId());
attachmentId = attachment.getDataElement().getExtensionString(HapiExtensions.EXT_EXTERNALIZED_BINARY_ID);
assertThat(attachmentId, matchesPattern("[a-zA-Z0-9]{100}"));
}
myBinaryStorageSvc.expungeBlob(id, attachmentId);
path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_READ +
"?path=DocumentReference.content.attachment";
HttpGet get = new HttpGet(path);
try (CloseableHttpResponse resp = ourHttpClient.execute(get)) {
assertEquals(400, resp.getStatusLine().getStatusCode());
String response = IOUtils.toString(resp.getEntity().getContent(), Charsets.UTF_8);
assertThat(response, matchesPattern(".*Can not find the requested binary content. It may have been deleted.*"));
}
}
/**
* Stores a binary large enough that it should live in binary storage
*/
@Test
public void testWriteLargeAttachment() throws IOException {
IIdType id = createDocumentReference(false);
IAnonymousInterceptor interceptor = mock(IAnonymousInterceptor.class);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESHOW_RESOURCES, interceptor);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESTORAGE_RESOURCE_CREATED, interceptor);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED, interceptor);
// Write the binary using the operation
String path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_WRITE +
"?path=DocumentReference.content.attachment";
HttpPost post = new HttpPost(path);
post.setEntity(new ByteArrayEntity(SOME_BYTES, ContentType.IMAGE_JPEG));
post.addHeader("Accept", "application/fhir+json; _pretty=true");
String attachmentId;
try (CloseableHttpResponse resp = ourHttpClient.execute(post)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertThat(resp.getEntity().getContentType().getValue(), containsString("application/fhir+json"));
String response = IOUtils.toString(resp.getEntity().getContent(), Constants.CHARSET_UTF8);
ourLog.info("Response: {}", response);
DocumentReference ref = myFhirCtx.newJsonParser().parseResource(DocumentReference.class, response);
Attachment attachment = ref.getContentFirstRep().getAttachment();
assertEquals(ContentType.IMAGE_JPEG.getMimeType(), attachment.getContentType());
assertEquals(15, attachment.getSize());
assertEquals(null, attachment.getData());
assertEquals("2", ref.getMeta().getVersionId());
attachmentId = attachment.getDataElement().getExtensionString(HapiExtensions.EXT_EXTERNALIZED_BINARY_ID);
assertThat(attachmentId, matchesPattern("[a-zA-Z0-9]{100}"));
}
verify(interceptor, timeout(5000).times(1)).invoke(eq(Pointcut.STORAGE_PRESHOW_RESOURCES), any());
verify(interceptor, timeout(5000).times(1)).invoke(eq(Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED), any());
verifyNoMoreInteractions(interceptor);
// Read it back using the operation
path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_READ +
"?path=DocumentReference.content.attachment";
HttpGet get = new HttpGet(path);
try (CloseableHttpResponse resp = ourHttpClient.execute(get)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertEquals("image/jpeg", resp.getEntity().getContentType().getValue());
assertEquals(SOME_BYTES.length, resp.getEntity().getContentLength());
byte[] actualBytes = IOUtils.toByteArray(resp.getEntity().getContent());
assertArrayEquals(SOME_BYTES, actualBytes);
}
}
@Test
public void testDontAllowUpdateWithAttachmentId_NoneExists() {
DocumentReference dr = new DocumentReference();
dr.addContent()
.getAttachment()
.getDataElement()
.addExtension(HapiExtensions.EXT_EXTERNALIZED_BINARY_ID, new StringType("0000-1111") );
try {
myClient.create().resource(dr).execute();
fail();
} catch (InvalidRequestException e) {
assertThat(e.getMessage(), containsString("Can not find the requested binary content. It may have been deleted."));
}
}
/**
* Stores a binary small enough that it shouldn't live in binary storage
*/
@Test
public void testWriteSmallAttachment() throws IOException {
IIdType id = createDocumentReference(false);
IAnonymousInterceptor interceptor = mock(IAnonymousInterceptor.class);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESHOW_RESOURCES, interceptor);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESTORAGE_RESOURCE_CREATED, interceptor);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED, interceptor);
// Read it back using the operation
String path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_WRITE +
"?path=DocumentReference.content.attachment";
HttpPost post = new HttpPost(path);
post.setEntity(new ByteArrayEntity(SOME_BYTES_2, ContentType.IMAGE_JPEG));
post.addHeader("Accept", "application/fhir+json; _pretty=true");
String attachmentId;
try (CloseableHttpResponse resp = ourHttpClient.execute(post)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertThat(resp.getEntity().getContentType().getValue(), containsString("application/fhir+json"));
String response = IOUtils.toString(resp.getEntity().getContent(), Constants.CHARSET_UTF8);
ourLog.info("Response: {}", response);
DocumentReference ref = myFhirCtx.newJsonParser().parseResource(DocumentReference.class, response);
Attachment attachment = ref.getContentFirstRep().getAttachment();
assertEquals(ContentType.IMAGE_JPEG.getMimeType(), attachment.getContentType());
assertEquals(4, attachment.getSize());
assertArrayEquals(SOME_BYTES_2, attachment.getData());
assertEquals("2", ref.getMeta().getVersionId());
attachmentId = attachment.getExtensionString(HapiExtensions.EXT_EXTERNALIZED_BINARY_ID);
assertEquals(null, attachmentId);
}
verify(interceptor, timeout(5000).times(1)).invoke(eq(Pointcut.STORAGE_PRESHOW_RESOURCES), any());
verify(interceptor, timeout(5000).times(1)).invoke(eq(Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED), any());
verifyNoMoreInteractions(interceptor);
}
/**
* Stores a binary large enough that it should live in binary storage
*/
@Test
public void testWriteLargeBinaryUsingOperation() throws IOException {
Binary binary = new Binary();
binary.setContentType("image/png");
ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(binary));
IIdType id = myClient.create().resource(binary).execute().getId().toUnqualifiedVersionless();
IAnonymousInterceptor interceptor = mock(IAnonymousInterceptor.class);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESHOW_RESOURCES, interceptor);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESTORAGE_RESOURCE_CREATED, interceptor);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED, interceptor);
// Write using the operation
String path = ourServerBase +
"/Binary/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_WRITE +
"?path=Binary";
HttpPost post = new HttpPost(path);
post.setEntity(new ByteArrayEntity(SOME_BYTES, ContentType.IMAGE_JPEG));
post.addHeader("Accept", "application/fhir+json; _pretty=true");
String attachmentId;
try (CloseableHttpResponse resp = ourHttpClient.execute(post)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertThat(resp.getEntity().getContentType().getValue(), containsString("application/fhir+json"));
String response = IOUtils.toString(resp.getEntity().getContent(), Constants.CHARSET_UTF8);
ourLog.info("Response: {}", response);
Binary target = myFhirCtx.newJsonParser().parseResource(Binary.class, response);
assertEquals(ContentType.IMAGE_JPEG.getMimeType(), target.getContentType());
assertEquals(null, target.getData());
assertEquals("2", target.getMeta().getVersionId());
attachmentId = target.getDataElement().getExtensionString(HapiExtensions.EXT_EXTERNALIZED_BINARY_ID);
assertThat(attachmentId, matchesPattern("[a-zA-Z0-9]{100}"));
}
verify(interceptor, timeout(5000).times(1)).invoke(eq(Pointcut.STORAGE_PRESHOW_RESOURCES), any());
verify(interceptor, timeout(5000).times(1)).invoke(eq(Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED), any());
verifyNoMoreInteractions(interceptor);
// Read it back using the operation
path = ourServerBase +
"/Binary/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_READ +
"?path=Binary";
HttpGet get = new HttpGet(path);
try (CloseableHttpResponse resp = ourHttpClient.execute(get)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertEquals("image/jpeg", resp.getEntity().getContentType().getValue());
assertEquals(SOME_BYTES.length, resp.getEntity().getContentLength());
byte[] actualBytes = IOUtils.toByteArray(resp.getEntity().getContent());
assertArrayEquals(SOME_BYTES, actualBytes);
}
}
/**
* Stores a binary large enough that it should live in binary storage
*/
@Test
public void testWriteLargeBinaryWithoutExplicitPath() throws IOException {
Binary binary = new Binary();
binary.setContentType("image/png");
ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(binary));
IIdType id = myClient.create().resource(binary).execute().getId().toUnqualifiedVersionless();
// Write using the operation
String path = ourServerBase +
"/Binary/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_WRITE;
HttpPost post = new HttpPost(path);
post.setEntity(new ByteArrayEntity(SOME_BYTES, ContentType.IMAGE_JPEG));
post.addHeader("Accept", "application/fhir+json; _pretty=true");
String attachmentId;
try (CloseableHttpResponse resp = ourHttpClient.execute(post)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertThat(resp.getEntity().getContentType().getValue(), containsString("application/fhir+json"));
String response = IOUtils.toString(resp.getEntity().getContent(), Constants.CHARSET_UTF8);
ourLog.info("Response: {}", response);
Binary target = myFhirCtx.newJsonParser().parseResource(Binary.class, response);
assertEquals(ContentType.IMAGE_JPEG.getMimeType(), target.getContentType());
assertEquals(null, target.getData());
assertEquals("2", target.getMeta().getVersionId());
attachmentId = target.getDataElement().getExtensionString(HapiExtensions.EXT_EXTERNALIZED_BINARY_ID);
assertThat(attachmentId, matchesPattern("[a-zA-Z0-9]{100}"));
}
// Read it back using the operation
path = ourServerBase +
"/Binary/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_READ;
HttpGet get = new HttpGet(path);
try (CloseableHttpResponse resp = ourHttpClient.execute(get)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertEquals("image/jpeg", resp.getEntity().getContentType().getValue());
assertEquals(SOME_BYTES.length, resp.getEntity().getContentLength());
byte[] actualBytes = IOUtils.toByteArray(resp.getEntity().getContent());
assertArrayEquals(SOME_BYTES, actualBytes);
}
}
@Test
public void testWriteLargeBinaryToDocumentReference() throws IOException {
byte[] bytes = new byte[134696];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) (((float)Byte.MAX_VALUE) * Math.random());
}
DocumentReference dr = new DocumentReference();
dr.addContent().getAttachment()
.setContentType("application/pdf")
.setSize(12345)
.setTitle("hello")
.setCreationElement(new DateTimeType("2002"));
IIdType id = myClient.create().resource(dr).execute().getId().toUnqualifiedVersionless();
IAnonymousInterceptor interceptor = mock(IAnonymousInterceptor.class);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESHOW_RESOURCES, interceptor);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESTORAGE_RESOURCE_CREATED, interceptor);
myInterceptorRegistry.registerAnonymousInterceptor(Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED, interceptor);
// Write using the operation
String path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_WRITE +
"?path=DocumentReference.content.attachment";
HttpPost post = new HttpPost(path);
post.setEntity(new ByteArrayEntity(bytes, ContentType.IMAGE_JPEG));
post.addHeader("Accept", "application/fhir+json; _pretty=true");
String attachmentId;
try (CloseableHttpResponse resp = ourHttpClient.execute(post)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertThat(resp.getEntity().getContentType().getValue(), containsString("application/fhir+json"));
String response = IOUtils.toString(resp.getEntity().getContent(), Constants.CHARSET_UTF8);
ourLog.info("Response: {}", response);
DocumentReference target = myFhirCtx.newJsonParser().parseResource(DocumentReference.class, response);
assertEquals(null, target.getContentFirstRep().getAttachment().getData());
assertEquals("2", target.getMeta().getVersionId());
attachmentId = target.getContentFirstRep().getAttachment().getDataElement().getExtensionString(HapiExtensions.EXT_EXTERNALIZED_BINARY_ID);
assertThat(attachmentId, matchesPattern("[a-zA-Z0-9]{100}"));
}
verify(interceptor, timeout(5000).times(1)).invoke(eq(Pointcut.STORAGE_PRESHOW_RESOURCES), any());
verify(interceptor, timeout(5000).times(1)).invoke(eq(Pointcut.STORAGE_PRESTORAGE_RESOURCE_UPDATED), any());
verifyNoMoreInteractions(interceptor);
// Read it back using the operation
path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_READ +
"?path=DocumentReference.content.attachment";
HttpGet get = new HttpGet(path);
try (CloseableHttpResponse resp = ourHttpClient.execute(get)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertEquals("image/jpeg", resp.getEntity().getContentType().getValue());
assertEquals(bytes.length, resp.getEntity().getContentLength());
byte[] actualBytes = IOUtils.toByteArray(resp.getEntity().getContent());
assertArrayEquals(bytes, actualBytes);
}
}
private IIdType createDocumentReference(boolean theSetData) {
DocumentReference documentReference = new DocumentReference();
Attachment attachment = documentReference
.addContent()
.getAttachment()
.setContentType("image/png");
if (theSetData) {
attachment.setData(SOME_BYTES);
}
attachment = documentReference
.addContent()
.getAttachment()
.setContentType("image/gif");
if (theSetData) {
attachment.setData(SOME_BYTES_2);
}
ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(documentReference));
return myClient.create().resource(documentReference).execute().getId().toUnqualifiedVersionless();
}
@Test
public void testResourceExpungeAlsoExpungesBinaryData() throws IOException {
IIdType id = createDocumentReference(false);
String path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_WRITE +
"?path=DocumentReference.content.attachment";
HttpPost post = new HttpPost(path);
post.setEntity(new ByteArrayEntity(SOME_BYTES, ContentType.IMAGE_JPEG));
post.addHeader("Accept", "application/fhir+json; _pretty=true");
String attachmentId;
try (CloseableHttpResponse resp = ourHttpClient.execute(post)) {
assertEquals(200, resp.getStatusLine().getStatusCode());
assertThat(resp.getEntity().getContentType().getValue(), containsString("application/fhir+json"));
String response = IOUtils.toString(resp.getEntity().getContent(), Constants.CHARSET_UTF8);
DocumentReference ref = myFhirCtx.newJsonParser().parseResource(DocumentReference.class, response);
Attachment attachment = ref.getContentFirstRep().getAttachment();
attachmentId = attachment.getDataElement().getExtensionString(HapiExtensions.EXT_EXTERNALIZED_BINARY_ID);
assertThat(attachmentId, matchesPattern("[a-zA-Z0-9]{100}"));
}
ByteArrayOutputStream capture = new ByteArrayOutputStream();
myStorageSvc.writeBlob(id, attachmentId, capture);
assertEquals(15, capture.size());
// Now delete (logical delete- should not expunge the binary)
myClient.delete().resourceById(id).execute();
try {
myClient.read().resource("DocumentReference").withId(id).execute();
fail();
} catch (ResourceGoneException e) {
// good
}
capture = new ByteArrayOutputStream();
myStorageSvc.writeBlob(id, attachmentId, capture);
assertEquals(15, capture.size());
// Now expunge
Parameters parameters = new Parameters();
parameters.addParameter().setName(JpaConstants.OPERATION_EXPUNGE_PARAM_EXPUNGE_DELETED_RESOURCES).setValue(new BooleanType(true));
myClient
.operation()
.onInstance(id)
.named(JpaConstants.OPERATION_EXPUNGE)
.withParameters(parameters)
.execute();
capture = new ByteArrayOutputStream();
assertFalse(myStorageSvc.writeBlob(id, attachmentId, capture));
assertEquals(0, capture.size());
}
@Test
public void testWriteWithConflictInterceptor() throws IOException {
UserRequestRetryVersionConflictsInterceptor interceptor = new UserRequestRetryVersionConflictsInterceptor();
ourRestServer.registerInterceptor(interceptor);
try {
IIdType id = createDocumentReference(false);
String path = ourServerBase +
"/DocumentReference/" + id.getIdPart() + "/" +
JpaConstants.OPERATION_BINARY_ACCESS_WRITE +
"?path=DocumentReference.content.attachment";
HttpPost post = new HttpPost(path);
post.setEntity(new ByteArrayEntity(SOME_BYTES, ContentType.IMAGE_JPEG));
post.addHeader("Accept", "application/fhir+json; _pretty=true");
String attachmentId;
try (CloseableHttpResponse resp = ourHttpClient.execute(post)) {
String response = IOUtils.toString(resp.getEntity().getContent(), Constants.CHARSET_UTF8);
ourLog.info("Response: {}\n{}", resp, response);
assertEquals(200, resp.getStatusLine().getStatusCode());
assertThat(resp.getEntity().getContentType().getValue(), containsString("application/fhir+json"));
DocumentReference ref = myFhirCtx.newJsonParser().parseResource(DocumentReference.class, response);
Attachment attachment = ref.getContentFirstRep().getAttachment();
attachmentId = attachment.getDataElement().getExtensionString(HapiExtensions.EXT_EXTERNALIZED_BINARY_ID);
assertThat(attachmentId, matchesPattern("[a-zA-Z0-9]{100}"));
}
} finally {
ourRestServer.unregisterInterceptor(interceptor);
}
}
}
| |
/*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.widgets.client.datamodel;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.drools.workbench.models.datamodel.oracle.DataType;
import org.drools.workbench.models.datamodel.oracle.DropDownData;
import org.drools.workbench.models.datamodel.oracle.FieldAccessorsAndMutators;
import org.drools.workbench.models.datamodel.oracle.ModelField;
import org.drools.workbench.models.datamodel.oracle.PackageDataModelOracle;
import org.drools.workbench.models.datamodel.oracle.ProjectDataModelOracle;
import org.jboss.errai.common.client.api.Caller;
import org.junit.Test;
import org.kie.workbench.common.services.datamodel.backend.server.builder.packages.PackageDataModelOracleBuilder;
import org.kie.workbench.common.services.datamodel.backend.server.builder.projects.FactBuilder;
import org.kie.workbench.common.services.datamodel.backend.server.builder.projects.ProjectDataModelOracleBuilder;
import org.kie.workbench.common.services.datamodel.model.PackageDataModelOracleBaselinePayload;
import org.kie.workbench.common.services.datamodel.service.IncrementalDataModelService;
import org.kie.workbench.common.widgets.client.datamodel.testclasses.TestJavaEnum1;
import org.kie.workbench.common.widgets.client.datamodel.testclasses.TestJavaEnum2;
import org.uberfire.backend.vfs.Path;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* Tests for the ProjectDataModelOracle enums
*/
public class PackageDataModelOracleEnumTest {
@Test
public void testBasicEnums() {
final ProjectDataModelOracle projectLoader = ProjectDataModelOracleBuilder.newProjectOracleBuilder()
.addFact( "Person" )
.addField( new ModelField( "age",
Integer.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_NUMERIC_INTEGER ) )
.addField( new ModelField( "sex",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.end()
.addFact( "Driver" )
.addField( new ModelField( "sex",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.end()
.addEnum( "Person",
"age",
new String[]{ "42", "43" } )
.addEnum( "Person",
"sex",
new String[]{ "M", "F" } )
.addEnum( "Driver",
"sex",
new String[]{ "M", "F" } )
.build();
final PackageDataModelOracle packageLoader = PackageDataModelOracleBuilder.newPackageOracleBuilder().setProjectOracle( projectLoader ).build();
//Emulate server-to-client conversions
final MockAsyncPackageDataModelOracleImpl oracle = new MockAsyncPackageDataModelOracleImpl();
final Caller<IncrementalDataModelService> service = new MockIncrementalDataModelServiceCaller( packageLoader );
oracle.setService( service );
final PackageDataModelOracleBaselinePayload dataModel = new PackageDataModelOracleBaselinePayload();
dataModel.setPackageName( packageLoader.getPackageName() );
dataModel.setModelFields( packageLoader.getProjectModelFields() );
dataModel.setJavaEnumDefinitions( packageLoader.getProjectJavaEnumDefinitions() );
dataModel.setWorkbenchEnumDefinitions( packageLoader.getPackageWorkbenchDefinitions() );
PackageDataModelOracleTestUtils.populateDataModelOracle( mock( Path.class ),
new MockHasImports(),
oracle,
dataModel );
String[] personAgeEnum = oracle.getEnumValues( "Person",
"age" );
assertEquals( 2,
personAgeEnum.length );
assertEquals( "42",
personAgeEnum[ 0 ] );
assertEquals( "43",
personAgeEnum[ 1 ] );
String[] personSexEnum = oracle.getEnumValues( "Person",
"sex" );
assertEquals( 2,
personSexEnum.length );
assertEquals( "M",
personSexEnum[ 0 ] );
assertEquals( "F",
personSexEnum[ 1 ] );
String[] driverSexEnum = oracle.getEnumValues( "Driver",
"sex" );
assertEquals( 2,
driverSexEnum.length );
assertEquals( "M",
driverSexEnum[ 0 ] );
assertEquals( "F",
driverSexEnum[ 1 ] );
}
@Test
public void testBasicDependentEnums() {
final ProjectDataModelOracle projectLoader = ProjectDataModelOracleBuilder.newProjectOracleBuilder()
.addFact( "Fact" )
.addField( new ModelField( "field1",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "field2",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.end()
.addFact( "Driver" )
.addField( new ModelField( "sex",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.end()
.addEnum( "'Fact.field1' : ['val1', 'val2'], 'Fact.field2' : ['val3', 'val4'], 'Fact.field2[field1=val1]' : ['f1val1a', 'f1val1b'], 'Fact.field2[field1=val2]' : ['f1val2a', 'f1val2b']",
Thread.currentThread().getContextClassLoader() )
.build();
final PackageDataModelOracle packageLoader = PackageDataModelOracleBuilder.newPackageOracleBuilder().setProjectOracle( projectLoader ).build();
//Emulate server-to-client conversions
final MockAsyncPackageDataModelOracleImpl oracle = new MockAsyncPackageDataModelOracleImpl();
final Caller<IncrementalDataModelService> service = new MockIncrementalDataModelServiceCaller( packageLoader );
oracle.setService( service );
final PackageDataModelOracleBaselinePayload dataModel = new PackageDataModelOracleBaselinePayload();
dataModel.setPackageName( packageLoader.getPackageName() );
dataModel.setModelFields( packageLoader.getProjectModelFields() );
dataModel.setJavaEnumDefinitions( packageLoader.getProjectJavaEnumDefinitions() );
dataModel.setWorkbenchEnumDefinitions( packageLoader.getPackageWorkbenchDefinitions() );
PackageDataModelOracleTestUtils.populateDataModelOracle( mock( Path.class ),
new MockHasImports(),
oracle,
dataModel );
assertEquals( "String",
oracle.getFieldType( "Fact",
"field1" ) );
assertEquals( "String",
oracle.getFieldType( "Fact",
"field2" ) );
String[] field1Enums = oracle.getEnumValues( "Fact",
"field1" );
assertEquals( 2,
field1Enums.length );
assertEquals( "val1",
field1Enums[ 0 ] );
assertEquals( "val2",
field1Enums[ 1 ] );
String[] field2Enums = oracle.getEnumValues( "Fact",
"field2" );
assertEquals( 2,
field2Enums.length );
assertEquals( "val3",
field2Enums[ 0 ] );
assertEquals( "val4",
field2Enums[ 1 ] );
}
@Test
public void testSmartEnums1() {
final ProjectDataModelOracle projectLoader = ProjectDataModelOracleBuilder.newProjectOracleBuilder()
.addFact( "Fact" )
.addField( new ModelField( "type",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "value",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.end()
.addEnum( "Fact",
"type",
new String[]{ "sex", "colour" } )
.addEnum( "Fact",
"value[type=sex]",
new String[]{ "M", "F" } )
.addEnum( "Fact",
"value[type=colour]",
new String[]{ "RED", "WHITE", "BLUE" } )
.build();
final PackageDataModelOracle packageLoader = PackageDataModelOracleBuilder.newPackageOracleBuilder().setProjectOracle( projectLoader ).build();
//Emulate server-to-client conversions
final MockAsyncPackageDataModelOracleImpl oracle = new MockAsyncPackageDataModelOracleImpl();
final Caller<IncrementalDataModelService> service = new MockIncrementalDataModelServiceCaller( packageLoader );
oracle.setService( service );
final PackageDataModelOracleBaselinePayload dataModel = new PackageDataModelOracleBaselinePayload();
dataModel.setPackageName( packageLoader.getPackageName() );
dataModel.setModelFields( packageLoader.getProjectModelFields() );
dataModel.setJavaEnumDefinitions( packageLoader.getProjectJavaEnumDefinitions() );
dataModel.setWorkbenchEnumDefinitions( packageLoader.getPackageWorkbenchDefinitions() );
PackageDataModelOracleTestUtils.populateDataModelOracle( mock( Path.class ),
new MockHasImports(),
oracle,
dataModel );
String[] typeResult = oracle.getEnums( "Fact",
"type" ).getFixedList();
assertEquals( 2,
typeResult.length );
assertEquals( "sex",
typeResult[ 0 ] );
assertEquals( "colour",
typeResult[ 1 ] );
Map<String, String> currentValueMap = new HashMap<String, String>();
currentValueMap.put( "type",
"sex" );
String[] typeSexResult = oracle.getEnums( "Fact",
"value",
currentValueMap ).getFixedList();
assertEquals( 2,
typeSexResult.length );
assertEquals( "M",
typeSexResult[ 0 ] );
assertEquals( "F",
typeSexResult[ 1 ] );
currentValueMap.clear();
currentValueMap.put( "type",
"colour" );
String[] typeColourResult = oracle.getEnums( "Fact",
"value",
currentValueMap ).getFixedList();
assertEquals( 3,
typeColourResult.length );
assertEquals( "RED",
typeColourResult[ 0 ] );
assertEquals( "WHITE",
typeColourResult[ 1 ] );
assertEquals( "BLUE",
typeColourResult[ 2 ] );
}
@Test
public void testSmartEnumsDependingOnSeveralFields1() {
final ProjectDataModelOracle projectLoader = ProjectDataModelOracleBuilder.newProjectOracleBuilder()
.addFact( "Fact" )
.addField( new ModelField( "field1",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "field2",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "field3",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "field4",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.end()
.addEnum( "Fact",
"field1",
new String[]{ "a1", "a2" } )
.addEnum( "Fact",
"field2",
new String[]{ "b1", "b2" } )
.addEnum( "Fact",
"field3[field1=a1,field2=b1]",
new String[]{ "c1", "c2", "c3" } )
.addEnum( "Fact",
"field4[field1=a1]",
new String[]{ "d1", "d2" } )
.build();
final PackageDataModelOracle packageLoader = PackageDataModelOracleBuilder.newPackageOracleBuilder().setProjectOracle( projectLoader ).build();
//Emulate server-to-client conversions
final MockAsyncPackageDataModelOracleImpl oracle = new MockAsyncPackageDataModelOracleImpl();
final Caller<IncrementalDataModelService> service = new MockIncrementalDataModelServiceCaller( packageLoader );
oracle.setService( service );
final PackageDataModelOracleBaselinePayload dataModel = new PackageDataModelOracleBaselinePayload();
dataModel.setPackageName( packageLoader.getPackageName() );
dataModel.setModelFields( packageLoader.getProjectModelFields() );
dataModel.setJavaEnumDefinitions( packageLoader.getProjectJavaEnumDefinitions() );
dataModel.setWorkbenchEnumDefinitions( packageLoader.getPackageWorkbenchDefinitions() );
PackageDataModelOracleTestUtils.populateDataModelOracle( mock( Path.class ),
new MockHasImports(),
oracle,
dataModel );
Map<String, String> currentValueMap = new HashMap<String, String>();
currentValueMap.put( "field1",
"a1" );
currentValueMap.put( "field2",
"b1" );
String[] field3Result = oracle.getEnums( "Fact",
"field3",
currentValueMap ).getFixedList();
assertEquals( 3,
field3Result.length );
assertEquals( "c1",
field3Result[ 0 ] );
assertEquals( "c2",
field3Result[ 1 ] );
assertEquals( "c3",
field3Result[ 2 ] );
String[] field4Result = oracle.getEnums( "Fact",
"field4",
currentValueMap ).getFixedList();
assertEquals( 2,
field4Result.length );
assertEquals( "d1",
field4Result[ 0 ] );
assertEquals( "d2",
field4Result[ 1 ] );
}
@Test
public void testSmartLookupEnums() {
final ProjectDataModelOracle projectLoader = ProjectDataModelOracleBuilder.newProjectOracleBuilder()
.addFact( "Fact" )
.addField( new ModelField( "type",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "value",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.end()
.addEnum( "Fact",
"type",
new String[]{ "sex", "colour" } )
.addEnum( "Fact",
"value[f1, f2]",
new String[]{ "select something from database where x=@{f1} and y=@{f2}" } )
.build();
final PackageDataModelOracle packageLoader = PackageDataModelOracleBuilder.newPackageOracleBuilder().setProjectOracle( projectLoader ).build();
//Emulate server-to-client conversions
final MockAsyncPackageDataModelOracleImpl oracle = new MockAsyncPackageDataModelOracleImpl();
final Caller<IncrementalDataModelService> service = new MockIncrementalDataModelServiceCaller( packageLoader );
oracle.setService( service );
final PackageDataModelOracleBaselinePayload dataModel = new PackageDataModelOracleBaselinePayload();
dataModel.setPackageName( packageLoader.getPackageName() );
dataModel.setModelFields( packageLoader.getProjectModelFields() );
dataModel.setJavaEnumDefinitions( packageLoader.getProjectJavaEnumDefinitions() );
dataModel.setWorkbenchEnumDefinitions( packageLoader.getPackageWorkbenchDefinitions() );
PackageDataModelOracleTestUtils.populateDataModelOracle( mock( Path.class ),
new MockHasImports(),
oracle,
dataModel );
Map<String, String> currentValueMap = new HashMap<String, String>();
currentValueMap.put( "f1",
"f1val" );
currentValueMap.put( "f2",
"f2val" );
DropDownData dd = oracle.getEnums( "Fact",
"value",
currentValueMap );
assertNull( dd.getFixedList() );
assertNotNull( dd.getQueryExpression() );
assertNotNull( dd.getValuePairs() );
assertEquals( 2,
dd.getValuePairs().length );
assertEquals( "select something from database where x=@{f1} and y=@{f2}",
dd.getQueryExpression() );
assertEquals( "f1=f1val",
dd.getValuePairs()[ 0 ] );
assertEquals( "f2=f2val",
dd.getValuePairs()[ 1 ] );
}
@Test
public void testDataDropDown() {
assertNull( DropDownData.create( null ) );
assertNull( DropDownData.create( null,
null ) );
assertNotNull( DropDownData.create( new String[]{ "hey" } ) );
assertNotNull( DropDownData.create( "abc",
new String[]{ "hey" } ) );
}
@Test
public void testDataHasEnums() {
final ProjectDataModelOracle projectLoader = ProjectDataModelOracleBuilder.newProjectOracleBuilder()
.addFact( "Fact" )
.addField( new ModelField( "field1",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "field2",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.end()
.addEnum( "'Fact.field1' : ['val1', 'val2'], 'Fact.field2[field1=val1]' : ['f1val1a', 'f1val1b'], 'Fact.field2[field1=val2]' : ['f1val2a', 'f1val2b']",
Thread.currentThread().getContextClassLoader() )
.build();
final PackageDataModelOracle packageLoader = PackageDataModelOracleBuilder.newPackageOracleBuilder().setProjectOracle( projectLoader ).build();
//Emulate server-to-client conversions
final MockAsyncPackageDataModelOracleImpl oracle = new MockAsyncPackageDataModelOracleImpl();
final Caller<IncrementalDataModelService> service = new MockIncrementalDataModelServiceCaller( packageLoader );
oracle.setService( service );
final PackageDataModelOracleBaselinePayload dataModel = new PackageDataModelOracleBaselinePayload();
dataModel.setPackageName( packageLoader.getPackageName() );
dataModel.setModelFields( packageLoader.getProjectModelFields() );
dataModel.setJavaEnumDefinitions( packageLoader.getProjectJavaEnumDefinitions() );
dataModel.setWorkbenchEnumDefinitions( packageLoader.getPackageWorkbenchDefinitions() );
PackageDataModelOracleTestUtils.populateDataModelOracle( mock( Path.class ),
new MockHasImports(),
oracle,
dataModel );
//Fact.field1 has explicit enumerations
assertTrue( oracle.hasEnums( "Fact.field1" ) );
assertTrue( oracle.hasEnums( "Fact",
"field1" ) );
//Fact.field2 has explicit enumerations dependent upon Fact.field1
assertTrue( oracle.hasEnums( "Fact.field2" ) );
assertTrue( oracle.hasEnums( "Fact",
"field2" ) );
}
@Test
public void testDataHasEnumsFieldSuffixes() {
final ProjectDataModelOracle projectLoader = ProjectDataModelOracleBuilder.newProjectOracleBuilder()
.addFact( "Fact" )
.addField( new ModelField( "field1",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "field2",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "field2suffixed",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.end()
.addEnum( "'Fact.field1' : ['val1', 'val2'], 'Fact.field2[field1=val1]' : ['f1val1a', 'f1val1b']",
Thread.currentThread().getContextClassLoader() )
.build();
final PackageDataModelOracle packageLoader = PackageDataModelOracleBuilder.newPackageOracleBuilder().setProjectOracle( projectLoader ).build();
//Emulate server-to-client conversions
final MockAsyncPackageDataModelOracleImpl oracle = new MockAsyncPackageDataModelOracleImpl();
final Caller<IncrementalDataModelService> service = new MockIncrementalDataModelServiceCaller( packageLoader );
oracle.setService( service );
final PackageDataModelOracleBaselinePayload dataModel = new PackageDataModelOracleBaselinePayload();
dataModel.setPackageName( packageLoader.getPackageName() );
dataModel.setModelFields( packageLoader.getProjectModelFields() );
dataModel.setJavaEnumDefinitions( packageLoader.getProjectJavaEnumDefinitions() );
dataModel.setWorkbenchEnumDefinitions( packageLoader.getPackageWorkbenchDefinitions() );
PackageDataModelOracleTestUtils.populateDataModelOracle( mock( Path.class ),
new MockHasImports(),
oracle,
dataModel );
//Fact.field1 has explicit enumerations
assertTrue( oracle.hasEnums( "Fact.field1" ) );
assertTrue( oracle.hasEnums( "Fact",
"field1" ) );
//Fact.field2 has explicit enumerations dependent upon Fact.field1
assertTrue( oracle.hasEnums( "Fact.field2" ) );
assertTrue( oracle.hasEnums( "Fact",
"field2" ) );
//Fact.field2suffixed has no enums
assertFalse( oracle.hasEnums( "Fact.field2suffixed" ) );
assertFalse( oracle.hasEnums( "Fact",
"field2suffixed" ) );
}
@Test
public void testDependentEnums() {
final ProjectDataModelOracle projectLoader = ProjectDataModelOracleBuilder.newProjectOracleBuilder()
.addFact( "Fact" )
.addField( new ModelField( "field1",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "field2",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "field3",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.addField( new ModelField( "field4",
String.class.getName(),
ModelField.FIELD_CLASS_TYPE.REGULAR_CLASS,
ModelField.FIELD_ORIGIN.DECLARED,
FieldAccessorsAndMutators.BOTH,
DataType.TYPE_STRING ) )
.end()
.addEnum( "'Fact.field1' : ['val1', 'val2']",
Thread.currentThread().getContextClassLoader() )
.addEnum( "'Fact.field2[field1=val1]' : ['f1val1a', 'f1val1b']",
Thread.currentThread().getContextClassLoader() )
.addEnum( "'Fact.field2[field1=val2]' : ['f1val2a', 'f1val2b']",
Thread.currentThread().getContextClassLoader() )
.addEnum( "'Fact.field3[field2=f1val1a]' : ['f1val1a1a', 'f1val1a1b']",
Thread.currentThread().getContextClassLoader() )
.addEnum( "'Fact.field3[field2=f1val1b]' : ['f1val1b1a', 'f1val1b1b']",
Thread.currentThread().getContextClassLoader() )
.addEnum( "'Fact.field3[field2=f1val2a]' : ['f1val2a1a', 'f1val2a1b']",
Thread.currentThread().getContextClassLoader() )
.addEnum( "'Fact.field3[field2=f1val2b]' : ['f1val2a2a', 'f1val2b2b']",
Thread.currentThread().getContextClassLoader() )
.addEnum( "'Fact.field4' : ['f4val1', 'f4val2']",
Thread.currentThread().getContextClassLoader() )
.build();
final PackageDataModelOracle packageLoader = PackageDataModelOracleBuilder.newPackageOracleBuilder().setProjectOracle( projectLoader ).build();
//Emulate server-to-client conversions
final MockAsyncPackageDataModelOracleImpl oracle = new MockAsyncPackageDataModelOracleImpl();
final Caller<IncrementalDataModelService> service = new MockIncrementalDataModelServiceCaller( packageLoader );
oracle.setService( service );
final PackageDataModelOracleBaselinePayload dataModel = new PackageDataModelOracleBaselinePayload();
dataModel.setPackageName( packageLoader.getPackageName() );
dataModel.setModelFields( packageLoader.getProjectModelFields() );
dataModel.setJavaEnumDefinitions( packageLoader.getProjectJavaEnumDefinitions() );
dataModel.setWorkbenchEnumDefinitions( packageLoader.getPackageWorkbenchDefinitions() );
PackageDataModelOracleTestUtils.populateDataModelOracle( mock( Path.class ),
new MockHasImports(),
oracle,
dataModel );
assertTrue( oracle.isDependentEnum( "Fact",
"field1",
"field2" ) );
assertTrue( oracle.isDependentEnum( "Fact",
"field1",
"field3" ) );
assertTrue( oracle.isDependentEnum( "Fact",
"field2",
"field3" ) );
assertFalse( oracle.isDependentEnum( "Fact",
"field1",
"field4" ) );
}
@Test
public void testJavaEnum1() throws IOException {
final ProjectDataModelOracle projectLoader = ProjectDataModelOracleBuilder.newProjectOracleBuilder()
.addClass( TestJavaEnum1.class,
new HashMap<String, FactBuilder>() )
.build();
final PackageDataModelOracle packageLoader = PackageDataModelOracleBuilder.newPackageOracleBuilder( "org.kie.workbench.common.widgets.client.datamodel.testclasses" ).setProjectOracle( projectLoader ).build();
//Emulate server-to-client conversions
final MockAsyncPackageDataModelOracleImpl oracle = new MockAsyncPackageDataModelOracleImpl();
final Caller<IncrementalDataModelService> service = new MockIncrementalDataModelServiceCaller( packageLoader );
oracle.setService( service );
final PackageDataModelOracleBaselinePayload dataModel = new PackageDataModelOracleBaselinePayload();
dataModel.setPackageName( packageLoader.getPackageName() );
dataModel.setModelFields( packageLoader.getProjectModelFields() );
dataModel.setJavaEnumDefinitions( packageLoader.getProjectJavaEnumDefinitions() );
dataModel.setWorkbenchEnumDefinitions( packageLoader.getPackageWorkbenchDefinitions() );
PackageDataModelOracleTestUtils.populateDataModelOracle( mock( Path.class ),
new MockHasImports(),
oracle,
dataModel );
assertEquals( 2,
oracle.getFactTypes().length );
assertEquals( "TestJavaEnum1.TestEnum",
oracle.getFactTypes()[ 1 ] );
final DropDownData dd = oracle.getEnums( TestJavaEnum1.class.getSimpleName(),
"field1" );
assertNotNull( dd );
assertEquals( 3,
dd.getFixedList().length );
assertEquals( "TestJavaEnum1.TestEnum.ZERO=TestJavaEnum1.TestEnum.ZERO",
dd.getFixedList()[ 0 ] );
assertEquals( "TestJavaEnum1.TestEnum.ONE=TestJavaEnum1.TestEnum.ONE",
dd.getFixedList()[ 1 ] );
assertEquals( "TestJavaEnum1.TestEnum.TWO=TestJavaEnum1.TestEnum.TWO",
dd.getFixedList()[ 2 ] );
final String[] ddValues = oracle.getEnumValues( TestJavaEnum1.class.getSimpleName(),
"field1" );
assertNotNull( ddValues );
assertEquals( 3,
ddValues.length );
assertEquals( "TestJavaEnum1.TestEnum.ZERO=TestJavaEnum1.TestEnum.ZERO",
ddValues[ 0 ] );
assertEquals( "TestJavaEnum1.TestEnum.ONE=TestJavaEnum1.TestEnum.ONE",
ddValues[ 1 ] );
assertEquals( "TestJavaEnum1.TestEnum.TWO=TestJavaEnum1.TestEnum.TWO",
ddValues[ 2 ] );
}
@Test
public void testJavaEnum2() throws IOException {
final ProjectDataModelOracle projectLoader = ProjectDataModelOracleBuilder.newProjectOracleBuilder()
.addClass( TestJavaEnum2.class,
new HashMap<String, FactBuilder>() )
.build();
final PackageDataModelOracle packageLoader = PackageDataModelOracleBuilder.newPackageOracleBuilder( "org.kie.workbench.common.widgets.client.datamodel.testclasses" ).setProjectOracle( projectLoader ).build();
//Emulate server-to-client conversions
final MockAsyncPackageDataModelOracleImpl oracle = new MockAsyncPackageDataModelOracleImpl();
final Caller<IncrementalDataModelService> service = new MockIncrementalDataModelServiceCaller( packageLoader );
oracle.setService( service );
final PackageDataModelOracleBaselinePayload dataModel = new PackageDataModelOracleBaselinePayload();
dataModel.setPackageName( packageLoader.getPackageName() );
dataModel.setModelFields( packageLoader.getProjectModelFields() );
dataModel.setJavaEnumDefinitions( packageLoader.getProjectJavaEnumDefinitions() );
dataModel.setWorkbenchEnumDefinitions( packageLoader.getPackageWorkbenchDefinitions() );
PackageDataModelOracleTestUtils.populateDataModelOracle( mock( Path.class ),
new MockHasImports(),
oracle,
dataModel );
assertEquals( 2,
oracle.getFactTypes().length );
assertEquals( TestJavaEnum2.class.getSimpleName(),
oracle.getFactTypes()[ 1 ] );
final DropDownData dd = oracle.getEnums( TestJavaEnum2.class.getSimpleName(),
"field1" );
assertNotNull( dd );
assertEquals( 3,
dd.getFixedList().length );
assertEquals( "TestExternalEnum.ZERO=TestExternalEnum.ZERO",
dd.getFixedList()[ 0 ] );
assertEquals( "TestExternalEnum.ONE=TestExternalEnum.ONE",
dd.getFixedList()[ 1 ] );
assertEquals( "TestExternalEnum.TWO=TestExternalEnum.TWO",
dd.getFixedList()[ 2 ] );
final String[] ddValues = oracle.getEnumValues( TestJavaEnum2.class.getSimpleName(),
"field1" );
assertNotNull( ddValues );
assertEquals( 3,
ddValues.length );
assertEquals( "TestExternalEnum.ZERO=TestExternalEnum.ZERO",
ddValues[ 0 ] );
assertEquals( "TestExternalEnum.ONE=TestExternalEnum.ONE",
ddValues[ 1 ] );
assertEquals( "TestExternalEnum.TWO=TestExternalEnum.TWO",
ddValues[ 2 ] );
}
}
| |
/*
* Copyright 2012 GitHub Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.mobile.ui.issue;
import android.accounts.Account;
import android.content.Intent;
import android.os.Bundle;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.github.mobile.Intents.*;
import com.github.mobile.R.id;
import com.github.mobile.R.layout;
import com.github.mobile.R.string;
import com.github.mobile.accounts.AccountUtils;
import com.github.mobile.accounts.AuthenticatedUserTask;
import com.github.mobile.core.issue.IssueStore;
import com.github.mobile.core.issue.IssueUtils;
import com.github.mobile.core.repo.RefreshRepositoryTask;
import com.github.mobile.ui.FragmentProvider;
import com.github.mobile.ui.PagerActivity;
import com.github.mobile.ui.UrlLauncher;
import com.github.mobile.ui.ViewPager;
import com.github.mobile.ui.repo.RepositoryViewActivity;
import com.github.mobile.util.AvatarLoader;
import com.google.inject.Inject;
import org.eclipse.egit.github.core.*;
import org.eclipse.egit.github.core.service.CollaboratorService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import static com.github.mobile.Intents.*;
/**
* Activity to display a collection of issues or pull requests in a pager
*/
public class IssuesViewActivity extends PagerActivity {
private static final String EXTRA_PULL_REQUESTS = "pullRequests";
/**
* Create an intent to show a single issue
*
* @param issue
* @return intent
*/
public static Intent createIntent(final Issue issue) {
return createIntent(Collections.singletonList(issue), 0);
}
/**
* Create an intent to show issue
*
* @param issue
* @param repository
* @return intent
*/
public static Intent createIntent(final Issue issue,
final Repository repository) {
return createIntent(Collections.singletonList(issue), repository, 0);
}
/**
* Create an intent to show issues with an initial selected issue
*
* @param issues
* @param repository
* @param position
* @return intent
*/
public static Intent createIntent(final Collection<? extends Issue> issues,
final Repository repository, final int position) {
int[] numbers = new int[issues.size()];
boolean[] pullRequests = new boolean[issues.size()];
int index = 0;
for (Issue issue : issues) {
numbers[index] = issue.getNumber();
pullRequests[index] = IssueUtils.isPullRequest(issue);
index++;
}
return new Builder("issues.VIEW").add(EXTRA_ISSUE_NUMBERS, numbers)
.add(EXTRA_REPOSITORY, repository)
.add(EXTRA_POSITION, position)
.add(EXTRA_PULL_REQUESTS, pullRequests).toIntent();
}
/**
* Create an intent to show issues with an initial selected issue
*
* @param issues
* @param position
* @return intent
*/
public static Intent createIntent(Collection<? extends Issue> issues,
int position) {
final int count = issues.size();
int[] numbers = new int[count];
boolean[] pullRequests = new boolean[count];
ArrayList<RepositoryId> repos = new ArrayList<RepositoryId>(count);
int index = 0;
for (Issue issue : issues) {
numbers[index] = issue.getNumber();
pullRequests[index] = IssueUtils.isPullRequest(issue);
index++;
RepositoryId repoId = null;
if (issue instanceof RepositoryIssue) {
Repository issueRepo = ((RepositoryIssue) issue)
.getRepository();
if (issueRepo != null) {
User owner = issueRepo.getOwner();
if (owner != null)
repoId = RepositoryId.create(owner.getLogin(),
issueRepo.getName());
}
}
if (repoId == null)
repoId = RepositoryId.createFromUrl(issue.getHtmlUrl());
repos.add(repoId);
}
Builder builder = new Builder("issues.VIEW");
builder.add(EXTRA_ISSUE_NUMBERS, numbers);
builder.add(EXTRA_REPOSITORIES, repos);
builder.add(EXTRA_POSITION, position);
builder.add(EXTRA_PULL_REQUESTS, pullRequests);
return builder.toIntent();
}
private ViewPager pager;
private int[] issueNumbers;
private boolean[] pullRequests;
private ArrayList<RepositoryId> repoIds;
private Repository repo;
@Inject
private AvatarLoader avatars;
@Inject
private IssueStore store;
@Inject
private CollaboratorService collaboratorService;
private final AtomicReference<User> user = new AtomicReference<User>();
private boolean isCollaborator;
private IssuesPagerAdapter adapter;
private final UrlLauncher urlLauncher = new UrlLauncher(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
issueNumbers = getIntArrayExtra(EXTRA_ISSUE_NUMBERS);
pullRequests = getBooleanArrayExtra(EXTRA_PULL_REQUESTS);
repoIds = getSerializableExtra(EXTRA_REPOSITORIES);
repo = getSerializableExtra(EXTRA_REPOSITORY);
setContentView(layout.pager);
if (repo != null) {
ActionBar actionBar = getSupportActionBar();
actionBar.setSubtitle(repo.generateId());
user.set(repo.getOwner());
avatars.bind(actionBar, user);
}
// Load avatar if single issue and user is currently unset or missing
// avatar URL
if (issueNumbers.length == 1
&& (user.get() == null || user.get().getAvatarUrl() == null))
new RefreshRepositoryTask(this, repo != null ? repo : repoIds.get(0)) {
@Override
protected void onSuccess(Repository fullRepository)
throws Exception {
super.onSuccess(fullRepository);
avatars.bind(getSupportActionBar(),
fullRepository.getOwner());
}
}.execute();
isCollaborator = false;
checkCollaboratorStatus();
}
private void configurePager() {
int initialPosition = getIntExtra(EXTRA_POSITION);
pager = finder.find(id.vp_pages);
if (repo != null)
adapter = new IssuesPagerAdapter(this, repo, issueNumbers, isCollaborator);
else
adapter = new IssuesPagerAdapter(this, repoIds, issueNumbers, store, isCollaborator);
pager.setAdapter(adapter);
pager.setOnPageChangeListener(this);
pager.scheduleSetItem(initialPosition, this);
onPageSelected(initialPosition);
}
private void updateTitle(final int position) {
int number = issueNumbers[position];
boolean pullRequest = pullRequests[position];
if (pullRequest)
getSupportActionBar().setTitle(
getString(string.pull_request_title) + number);
else
getSupportActionBar().setTitle(
getString(string.issue_title) + number);
}
@Override
public void onPageSelected(final int position) {
super.onPageSelected(position);
if (repo != null) {
updateTitle(position);
return;
}
if (repoIds == null)
return;
ActionBar actionBar = getSupportActionBar();
RepositoryId repoId = repoIds.get(position);
if (repoId != null) {
updateTitle(position);
actionBar.setSubtitle(repoId.generateId());
RepositoryIssue issue = store.getIssue(repoId,
issueNumbers[position]);
if (issue != null) {
Repository fullRepo = issue.getRepository();
if (fullRepo != null && fullRepo.getOwner() != null) {
user.set(fullRepo.getOwner());
avatars.bind(actionBar, user);
} else
actionBar.setLogo(null);
} else
actionBar.setLogo(null);
} else {
actionBar.setSubtitle(null);
actionBar.setLogo(null);
}
}
@Override
public void onDialogResult(int requestCode, int resultCode, Bundle arguments) {
adapter.onDialogResult(pager.getCurrentItem(), requestCode, resultCode,
arguments);
}
@Override
public void startActivity(Intent intent) {
Intent converted = urlLauncher.convert(intent);
if (converted != null)
super.startActivity(converted);
else
super.startActivity(intent);
}
@Override
protected FragmentProvider getProvider() {
return adapter;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem editItem = menu.findItem(id.m_edit);
MenuItem stateItem = menu.findItem(id.m_state);
if (editItem != null && stateItem != null) {
editItem.setVisible(isCollaborator);
stateItem.setVisible(isCollaborator);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Repository repository = repo;
if (repository == null) {
int position = pager.getCurrentItem();
RepositoryId repoId = repoIds.get(position);
if (repoId != null) {
RepositoryIssue issue = store.getIssue(repoId,
issueNumbers[position]);
if (issue != null)
repository = issue.getRepository();
}
}
if (repository != null) {
Intent intent = RepositoryViewActivity.createIntent(repository);
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP
| FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void checkCollaboratorStatus() {
new AuthenticatedUserTask<Boolean>(this) {
@Override
protected Boolean run(Account account) throws Exception {
return collaboratorService.isCollaborator(repo != null ? repo : repoIds.get(0),
AccountUtils.getLogin(IssuesViewActivity.this));
}
@Override
protected void onSuccess(Boolean collaborator) throws Exception {
super.onSuccess(collaborator);
isCollaborator = collaborator;
invalidateOptionsMenu();
configurePager();
}
}.execute();
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.broad.igv.gs.dm;
import org.broad.igv.AbstractHeadlessTest;
import org.broad.igv.prefs.Constants;
import org.broad.igv.gs.GSTestAuthenticator;
import org.broad.igv.gs.GSUtils;
import org.broad.igv.prefs.PreferencesManager;
import org.broad.igv.track.Track;
import org.broad.igv.track.TrackLoader;
import org.broad.igv.util.HttpUtils;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.TestUtils;
import org.junit.*;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import java.io.File;
import java.io.IOException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static junit.framework.Assert.*;
/**
* @author Jim Robinson
* @date 1/16/12
*/
public class DMUtilsTest extends AbstractHeadlessTest{
@Rule
public TestRule testTimeout = new Timeout((int) 30e4);
private static final String IGV_TEST_DIR = "/Home/igvtest/";
private URL defaultURL;
private URL personaldirectoryURL;
private static URL fileURL;
private static String delDirName = "testdir_deleteme";
private static String fullPath = IGV_TEST_DIR + delDirName;
@Before
public void setUp() throws Exception{
super.setUp();
GSUtils.logout();
//This is pretty dumb. The reason is that initializing HttpUtils sets the authenticator,
//and we need to overwrite it in initAuth. It's not actually important which method we call,
//as long as HttpUtils is initialized so it doesn't get initialized later
HttpUtils.getInstance().resetAuthenticator();
Authenticator.setDefault(new GSTestAuthenticator());
try {
String defaultURLStr = PreferencesManager.getPreferences().get(Constants.GENOME_SPACE_DM_SERVER);
defaultURL = new URL(defaultURLStr);
personaldirectoryURL = new URL(defaultURLStr + DMUtils.PERSONAL_DIRECTORY);
fileURL = new URL(defaultURL + "file");
System.out.println("Genome space URL: " + defaultURL);
} catch (MalformedURLException e) {
e.printStackTrace();
Assume.assumeTrue(false);
}
//We test creating this directory later
// try{
// DMUtils.deleteFileOrDirectory(fileURL + fullPath);
// }catch(FileNotFoundException e){
// //totally fine, in fact expected
// }
}
@After
public void tearDown() {
GSUtils.logout();
HttpUtils.getInstance().resetAuthenticator();
}
@Test
public void noOpTest() {
assertTrue(true);
}
@Ignore
public void testGetDirectoryListing() throws Exception {
final String testFileName = "Broad.080528.subtypes.seg.gz";
boolean found = dirContainsFile(personaldirectoryURL, testFileName);
assertTrue("Test file not found: " + testFileName, found);
}
protected boolean dirContainsFile(URL dirURL, String testFileName) throws Exception{
GSDirectoryListing dirListing = DMUtils.getDirectoryListing(dirURL);
assertNotNull("Directory listing", dirListing);
List<GSFileMetadata> gsFiles = dirListing.getContents();
//Search for known test file
boolean found = false;
for (GSFileMetadata fileMetadata : gsFiles) {
if (fileMetadata.getName().equals(testFileName)) {
found = true;
String path = IGV_TEST_DIR + testFileName;
assertEquals("Test file path not expected", path, fileMetadata.getPath());
}
}
return found;
}
/**
* Upload a file, check it got uploaded, delete it, check it was deleted
* Not really ideal, but since we need to check that the file doesn't exist before
* uploading and delete it afterwards anyway, figured we might as well combine these.
* @throws Exception
*/
@Ignore
public void testUploadDeleteFile() throws Exception {
String locName = "test2.bed";
File localFile = new File(TestUtils.DATA_DIR + "bed", locName);
String remPath = IGV_TEST_DIR + locName;
// Delete, in case the file is there from a previous test run
try {
DMUtils.deleteFileOrDirectory(fileURL + remPath);
} catch (IOException e) {
// Ignore -- expected
}
assertFileStatus(locName, false);
DMUtils.uploadFile(localFile, remPath);
assertFileStatus(locName, true);
DMUtils.deleteFileOrDirectory(fileURL + remPath);
assertFileStatus(locName, false);
}
//@Test
public void testCreateDeleteDirectory() throws Exception {
assertFileStatus(delDirName, false);
DMUtils.createDirectory(fileURL + fullPath);
assertFileStatus(delDirName, true);
DMUtils.deleteFileOrDirectory(fileURL + fullPath);
assertFileStatus(delDirName, false);
}
protected void assertFileStatus(String objName, boolean expExists) throws Exception{
boolean found = dirContainsFile(personaldirectoryURL, objName);
if(expExists){
assertEquals("Object not found: " + objName, expExists, found);
}else{
assertEquals("Object exists, but it shouldn't: " + objName, expExists, found);
}
}
/**
* Test that we can actually load files. More of an functional test than unit test.
* We also make sure to use token authentication
* @throws Exception
*/
@Ignore
public void testLoadFiles() throws Exception{
GSDirectoryListing dirListing = DMUtils.getDirectoryListing(personaldirectoryURL);
TrackLoader loader = new TrackLoader();
Map<String, Exception> exceptions = new HashMap<String, Exception>();
for(GSFileMetadata md: dirListing.getContents()){
String mdurl = md.getUrl();
if(!md.isDirectory() && (mdurl.endsWith(".bed") || mdurl.endsWith(".bam"))){
System.out.println("Loading file " + mdurl);
try{
List<Track> tracks = loader.load(new ResourceLocator(mdurl), genome);
assertNotNull(tracks);
assertNotSame(0, tracks.size());
}catch(Exception e){
exceptions.put(mdurl, e);
}
}
}
for(Map.Entry<String, Exception> entry: exceptions.entrySet()){
System.out.println("Exception loading Path: " + entry.getKey());
System.out.println("StackTrace: ");
for (StackTraceElement el : entry.getValue().getStackTrace()) {
System.out.println(el);
}
}
assertEquals(0, exceptions.size());
}
}
| |
/*
* Copyright 2015 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.platform.plugin;
import java.io.IOException;
import java.lang.annotation.Annotation;
import org.teavm.codegen.SourceWriter;
import org.teavm.dependency.DependencyAgent;
import org.teavm.dependency.DependencyPlugin;
import org.teavm.dependency.MethodDependency;
import org.teavm.javascript.spi.Generator;
import org.teavm.javascript.spi.GeneratorContext;
import org.teavm.javascript.spi.Injector;
import org.teavm.javascript.spi.InjectorContext;
import org.teavm.model.CallLocation;
import org.teavm.model.ClassReader;
import org.teavm.model.MethodDescriptor;
import org.teavm.model.MethodReader;
import org.teavm.model.MethodReference;
import org.teavm.model.ValueType;
import org.teavm.platform.Platform;
import org.teavm.platform.PlatformClass;
import org.teavm.platform.PlatformRunnable;
/**
*
* @author Alexey Andreev
*/
public class PlatformGenerator implements Generator, Injector, DependencyPlugin {
@Override
public void methodAchieved(DependencyAgent agent, MethodDependency method, CallLocation location) {
switch (method.getReference().getName()) {
case "asJavaClass":
method.getResult().propagate(agent.getType("java.lang.Class"));
return;
case "clone":
method.getVariable(1).connect(method.getResult());
break;
case "startThread":
case "schedule": {
MethodDependency launchMethod = agent.linkMethod(new MethodReference(Platform.class,
"launchThread", PlatformRunnable.class, void.class), null);
method.getVariable(1).connect(launchMethod.getVariable(1));
launchMethod.use();
break;
}
case "getCurrentThread":
method.getResult().propagate(agent.getType("java.lang.Thread"));
break;
}
}
@Override
public void generate(InjectorContext context, MethodReference methodRef) throws IOException {
switch (methodRef.getName()) {
case "asJavaClass":
case "classFromResource":
case "objectFromResource":
context.writeExpr(context.getArgument(0));
return;
}
}
@Override
public void generate(GeneratorContext context, SourceWriter writer, MethodReference methodRef) throws IOException {
switch (methodRef.getName()) {
case "newInstanceImpl":
generateNewInstance(context, writer);
break;
case "prepareNewInstance":
generatePrepareNewInstance(context, writer);
break;
case "lookupClass":
generateLookup(context, writer);
break;
case "clone":
generateClone(context, writer);
break;
case "startThread":
generateSchedule(context, writer, false);
break;
case "schedule":
generateSchedule(context, writer, true);
break;
case "getEnumConstants":
generateEnumConstants(context, writer);
break;
case "getAnnotations":
generateAnnotations(context, writer);
break;
}
}
private void generatePrepareNewInstance(GeneratorContext context, SourceWriter writer)
throws IOException {
writer.append("var c").ws().append("=").ws().append("'$$constructor$$';").softNewLine();
for (String clsName : context.getClassSource().getClassNames()) {
ClassReader cls = context.getClassSource().get(clsName);
MethodReader method = cls.getMethod(new MethodDescriptor("<init>", void.class));
if (method != null) {
writer.appendClass(clsName).append("[c]").ws().append("=").ws()
.appendMethodBody(method.getReference()).append(";").softNewLine();
}
}
writer.appendMethodBody(Platform.class, "newInstance", PlatformClass.class, Object.class).ws().append('=').ws()
.appendMethodBody(Platform.class, "newInstanceImpl", PlatformClass.class, Object.class)
.append(";").softNewLine();
}
private void generateNewInstance(GeneratorContext context, SourceWriter writer) throws IOException {
String cls = context.getParameterName(1);
writer.append("if").ws().append("($rt_resuming())").ws().append("{").indent().softNewLine();
writer.append("var $r = $rt_nativeThread().pop();").softNewLine();
writer.append(cls + ".$$constructor$$($r);").softNewLine();
writer.append("return $r;").softNewLine();
writer.outdent().append("}").softNewLine();
writer.append("if").ws().append("(!").append(cls).append(".hasOwnProperty('$$constructor$$'))")
.ws().append("{").indent().softNewLine();
writer.append("return null;").softNewLine();
writer.outdent().append("}").softNewLine();
writer.append("var $r").ws().append('=').ws().append("new ").append(cls).append("();").softNewLine();
writer.append(cls).append(".$$constructor$$($r);").softNewLine();
writer.append("if").ws().append("($rt_suspending())").ws().append("{").indent().softNewLine();
writer.append("return $rt_nativeThread().push($r);").softNewLine();
writer.outdent().append("}").softNewLine();
writer.append("return $r;").softNewLine();
}
private void generateLookup(GeneratorContext context, SourceWriter writer) throws IOException {
String param = context.getParameterName(1);
writer.append("switch ($rt_ustr(" + param + ")) {").softNewLine().indent();
for (String name : context.getClassSource().getClassNames()) {
writer.append("case \"" + name + "\": ").appendClass(name).append(".$clinit(); ")
.append("return ").appendClass(name).append(";").softNewLine();
}
writer.append("default: return null;").softNewLine();
writer.outdent().append("}").softNewLine();
}
private void generateClone(GeneratorContext context, SourceWriter writer) throws IOException {
String obj = context.getParameterName(1);
writer.append("var copy").ws().append("=").ws().append("new ").append(obj).append(".constructor();")
.softNewLine();
writer.append("for").ws().append("(var field in " + obj + ")").ws().append("{").softNewLine().indent();
writer.append("if").ws().append("(!" + obj + ".hasOwnProperty(field))").ws().append("{").softNewLine().indent();
writer.append("continue;").softNewLine().outdent().append("}").softNewLine();
writer.append("copy[field]").ws().append("=").ws().append(obj).append("[field];")
.softNewLine().outdent().append("}").softNewLine();
writer.append("return copy;").softNewLine();
}
private void generateSchedule(GeneratorContext context, SourceWriter writer, boolean timeout) throws IOException {
MethodReference launchRef = new MethodReference(Platform.class, "launchThread",
PlatformRunnable.class, void.class);
String runnable = context.getParameterName(1);
writer.append("return window.setTimeout(function()").ws().append("{").indent().softNewLine();
if (timeout) {
writer.appendMethodBody(launchRef);
} else {
writer.append("$rt_threadStarter(").appendMethodBody(launchRef).append(")");
}
writer.append("(").append(runnable).append(");").softNewLine();
writer.outdent().append("},").ws().append(timeout ? context.getParameterName(2) : "0")
.append(");").softNewLine();
}
private void generateEnumConstants(GeneratorContext context, SourceWriter writer) throws IOException {
writer.append("var c").ws().append("=").ws().append("'$$enumConstants$$';").softNewLine();
for (String clsName : context.getClassSource().getClassNames()) {
ClassReader cls = context.getClassSource().get(clsName);
MethodReader method = cls.getMethod(new MethodDescriptor("values",
ValueType.arrayOf(ValueType.object(clsName))));
if (method != null) {
writer.appendClass(clsName).append("[c]").ws().append("=").ws();
writer.appendMethodBody(method.getReference());
writer.append(";").softNewLine();
}
}
String selfName = writer.getNaming().getFullNameFor(new MethodReference(Platform.class, "getEnumConstants",
PlatformClass.class, Enum[].class));
writer.append(selfName).ws().append("=").ws().append("function(cls)").ws().append("{").softNewLine().indent();
writer.append("if").ws().append("(!cls.hasOwnProperty(c))").ws().append("{").indent().softNewLine();
writer.append("return null;").softNewLine();
writer.outdent().append("}").softNewLine();
writer.append("return cls[c]();").softNewLine();
writer.outdent().append("};").softNewLine();
writer.append("return ").append(selfName).append("(").append(context.getParameterName(1))
.append(");").softNewLine();
}
private void generateAnnotations(GeneratorContext context, SourceWriter writer) throws IOException {
writer.append("var c").ws().append("=").ws().append("'$$annotations$$';").softNewLine();
for (String clsName : context.getClassSource().getClassNames()) {
ClassReader annotCls = context.getClassSource().get(clsName + "$$__annotations__$$");
if (annotCls != null) {
writer.appendClass(clsName).append("[c]").ws().append("=").ws();
MethodReference ctor = new MethodReference(annotCls.getName(), "<init>", ValueType.VOID);
writer.append(writer.getNaming().getNameForInit(ctor));
writer.append("();").softNewLine();
}
}
String selfName = writer.getNaming().getFullNameFor(new MethodReference(Platform.class, "getAnnotations",
PlatformClass.class, Annotation[].class));
writer.append(selfName).ws().append("=").ws().append("function(cls)").ws().append("{").softNewLine().indent();
writer.append("if").ws().append("(!cls.hasOwnProperty(c))").ws().append("{").indent().softNewLine();
writer.append("return null;").softNewLine();
writer.outdent().append("}").softNewLine();
writer.append("return cls[c].").appendMethod("getAnnotations", Annotation[].class).append("();").softNewLine();
writer.outdent().append("};").softNewLine();
writer.append("return ").append(selfName).append("(").append(context.getParameterName(1))
.append(");").softNewLine();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.parquet.tools.command;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.parquet.column.ColumnDescriptor;
import org.apache.parquet.column.ColumnReader;
import org.apache.parquet.column.impl.ColumnReadStoreImpl;
import org.apache.parquet.column.page.DataPage;
import org.apache.parquet.column.page.DataPage.Visitor;
import org.apache.parquet.column.page.DataPageV1;
import org.apache.parquet.column.page.DataPageV2;
import org.apache.parquet.column.page.DictionaryPage;
import org.apache.parquet.column.page.PageReadStore;
import org.apache.parquet.column.page.PageReader;
import org.apache.parquet.column.statistics.Statistics;
import org.apache.parquet.hadoop.ParquetFileReader;
import org.apache.parquet.hadoop.metadata.BlockMetaData;
import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
import org.apache.parquet.hadoop.metadata.ParquetMetadata;
import org.apache.parquet.io.api.Binary;
import org.apache.parquet.io.api.Converter;
import org.apache.parquet.io.api.GroupConverter;
import org.apache.parquet.io.api.PrimitiveConverter;
import org.apache.parquet.schema.MessageType;
import org.apache.parquet.tools.util.MetadataUtils;
import org.apache.parquet.tools.util.PrettyPrintWriter;
import org.apache.parquet.tools.util.PrettyPrintWriter.WhiteSpaceHandler;
import com.google.common.base.Joiner;
import static org.apache.parquet.format.converter.ParquetMetadataConverter.NO_FILTER;
public class DumpCommand extends ArgsOnlyCommand {
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final CharsetDecoder UTF8_DECODER = UTF8.newDecoder();
public static final String TABS = " ";
public static final int BLOCK_BUFFER_SIZE = 64 * 1024;
public static final String[] USAGE = new String[] { "<input>", "where <input> is the parquet file to print to stdout" };
public static final Options OPTIONS;
static {
OPTIONS = new Options();
Option md = OptionBuilder.withLongOpt("disable-meta")
.withDescription("Do not dump row group and page metadata")
.create('m');
Option dt = OptionBuilder.withLongOpt("disable-data")
.withDescription("Do not dump column data")
.create('d');
Option nocrop = OptionBuilder.withLongOpt("disable-crop")
.withDescription("Do not crop the output based on console width")
.create('n');
Option cl = OptionBuilder.withLongOpt("column")
.withDescription("Dump only the given column, can be specified more than once")
.hasArg()
.create('c');
OPTIONS.addOption(md);
OPTIONS.addOption(dt);
OPTIONS.addOption(nocrop);
OPTIONS.addOption(cl);
}
public DumpCommand() {
super(1, 1);
}
@Override
public Options getOptions() {
return OPTIONS;
}
@Override
public String[] getUsageDescription() {
return USAGE;
}
@Override
public void execute(CommandLine options) throws Exception {
super.execute(options);
String[] args = options.getArgs();
String input = args[0];
Configuration conf = new Configuration();
Path inpath = new Path(input);
ParquetMetadata metaData = ParquetFileReader.readFooter(conf, inpath, NO_FILTER);
MessageType schema = metaData.getFileMetaData().getSchema();
boolean showmd = !options.hasOption('m');
boolean showdt = !options.hasOption('d');
boolean cropoutput = !options.hasOption('n');
Set<String> showColumns = null;
if (options.hasOption('c')) {
String[] cols = options.getOptionValues('c');
showColumns = new HashSet<String>(Arrays.asList(cols));
}
PrettyPrintWriter out = prettyPrintWriter(cropoutput);
dump(out, metaData, schema, inpath, showmd, showdt, showColumns);
}
public static void dump(PrettyPrintWriter out, ParquetMetadata meta, MessageType schema, Path inpath, boolean showmd, boolean showdt, Set<String> showColumns) throws IOException {
Configuration conf = new Configuration();
List<BlockMetaData> blocks = meta.getBlocks();
List<ColumnDescriptor> columns = schema.getColumns();
if (showColumns != null) {
columns = new ArrayList<ColumnDescriptor>();
for (ColumnDescriptor column : schema.getColumns()) {
String path = Joiner.on('.').skipNulls().join(column.getPath());
if (showColumns.contains(path)) {
columns.add(column);
}
}
}
ParquetFileReader freader = null;
if (showmd) {
try {
long group = 0;
for (BlockMetaData block : blocks) {
if (group != 0) out.println();
out.format("row group %d%n", group++);
out.rule('-');
List<ColumnChunkMetaData> ccmds = block.getColumns();
if (showColumns != null) {
ccmds = new ArrayList<ColumnChunkMetaData>();
for (ColumnChunkMetaData ccmd : block.getColumns()) {
String path = Joiner.on('.').skipNulls().join(ccmd.getPath().toArray());
if (showColumns.contains(path)) {
ccmds.add(ccmd);
}
}
}
MetadataUtils.showDetails(out, ccmds);
List<BlockMetaData> rblocks = Collections.singletonList(block);
freader = new ParquetFileReader(
conf, meta.getFileMetaData(), inpath, rblocks, columns);
PageReadStore store = freader.readNextRowGroup();
while (store != null) {
out.incrementTabLevel();
for (ColumnDescriptor column : columns) {
out.println();
dump(out, store, column);
}
out.decrementTabLevel();
store = freader.readNextRowGroup();
}
out.flushColumns();
}
} finally {
if (freader != null) {
freader.close();
}
}
}
if (showdt) {
boolean first = true;
for (ColumnDescriptor column : columns) {
if (!first || showmd) out.println();
first = false;
out.format("%s %s%n", column.getType(), Joiner.on('.').skipNulls().join(column.getPath()));
out.rule('-');
try {
long page = 1;
long total = blocks.size();
long offset = 1;
freader = new ParquetFileReader(
conf, meta.getFileMetaData(), inpath, blocks, Collections.singletonList(column));
PageReadStore store = freader.readNextRowGroup();
while (store != null) {
ColumnReadStoreImpl crstore = new ColumnReadStoreImpl(
store, new DumpGroupConverter(), schema,
meta.getFileMetaData().getCreatedBy());
dump(out, crstore, column, page++, total, offset);
offset += store.getRowCount();
store = freader.readNextRowGroup();
}
out.flushColumns();
} finally {
out.flushColumns();
if (freader != null) {
freader.close();
}
}
}
}
}
public static void dump(final PrettyPrintWriter out, PageReadStore store, ColumnDescriptor column) throws IOException {
PageReader reader = store.getPageReader(column);
long vc = reader.getTotalValueCount();
int rmax = column.getMaxRepetitionLevel();
int dmax = column.getMaxDefinitionLevel();
out.format("%s TV=%d RL=%d DL=%d", Joiner.on('.').skipNulls().join(column.getPath()), vc, rmax, dmax);
DictionaryPage dict = reader.readDictionaryPage();
if (dict != null) {
out.format(" DS:%d", dict.getDictionarySize());
out.format(" DE:%s", dict.getEncoding());
}
out.println();
out.rule('-');
DataPage page = reader.readPage();
for (long count = 0; page != null; count++) {
out.format("page %d:", count);
page.accept(new Visitor<Void>() {
@Override
public Void visit(DataPageV1 pageV1) {
out.format(" DLE:%s", pageV1.getDlEncoding());
out.format(" RLE:%s", pageV1.getRlEncoding());
out.format(" VLE:%s", pageV1.getValueEncoding());
Statistics<?> statistics = pageV1.getStatistics();
if (statistics != null) {
out.format(" ST:[%s]", statistics);
} else {
out.format(" ST:[none]");
}
return null;
}
@Override
public Void visit(DataPageV2 pageV2) {
out.format(" DLE:RLE");
out.format(" RLE:RLE");
out.format(" VLE:%s", pageV2.getDataEncoding());
Statistics<?> statistics = pageV2.getStatistics();
if (statistics != null) {
out.format(" ST:[%s]", statistics);
} else {
out.format(" ST:[none]");
}
return null;
}
});
out.format(" SZ:%d", page.getUncompressedSize());
out.format(" VC:%d", page.getValueCount());
out.println();
page = reader.readPage();
}
}
public static void dump(PrettyPrintWriter out, ColumnReadStoreImpl crstore, ColumnDescriptor column, long page, long total, long offset) throws IOException {
int dmax = column.getMaxDefinitionLevel();
ColumnReader creader = crstore.getColumnReader(column);
out.format("*** row group %d of %d, values %d to %d ***%n", page, total, offset, offset + creader.getTotalValueCount() - 1);
for (long i = 0, e = creader.getTotalValueCount(); i < e; ++i) {
int rlvl = creader.getCurrentRepetitionLevel();
int dlvl = creader.getCurrentDefinitionLevel();
out.format("value %d: R:%d D:%d V:", offset+i, rlvl, dlvl);
if (dlvl == dmax) {
switch (column.getType()) {
case BINARY: out.format("%s", binaryToString(creader.getBinary())); break;
case BOOLEAN: out.format("%s", creader.getBoolean()); break;
case DOUBLE: out.format("%s", creader.getDouble()); break;
case FLOAT: out.format("%s", creader.getFloat()); break;
case INT32: out.format("%s", creader.getInteger()); break;
case INT64: out.format("%s", creader.getLong()); break;
case INT96: out.format("%s", binaryToBigInteger(creader.getBinary())); break;
case FIXED_LEN_BYTE_ARRAY: out.format("%s", binaryToString(creader.getBinary())); break;
}
} else {
out.format("<null>");
}
out.println();
creader.consume();
}
}
public static String binaryToString(Binary value) {
byte[] data = value.getBytesUnsafe();
if (data == null) return null;
try {
CharBuffer buffer = UTF8_DECODER.decode(value.toByteBuffer());
return buffer.toString();
} catch (Exception ex) {
}
return "<bytes...>";
}
public static BigInteger binaryToBigInteger(Binary value) {
byte[] data = value.getBytesUnsafe();
if (data == null) return null;
return new BigInteger(data);
}
private static PrettyPrintWriter prettyPrintWriter(boolean cropOutput) {
PrettyPrintWriter.Builder builder = PrettyPrintWriter.stdoutPrettyPrinter()
.withAutoColumn()
.withWhitespaceHandler(WhiteSpaceHandler.ELIMINATE_NEWLINES)
.withColumnPadding(1)
.withMaxBufferedLines(1000000)
.withFlushOnTab();
if (cropOutput) {
builder.withAutoCrop();
}
return builder.build();
}
private static final class DumpGroupConverter extends GroupConverter {
@Override public void start() { }
@Override public void end() { }
@Override public Converter getConverter(int fieldIndex) { return new DumpConverter(); }
}
private static final class DumpConverter extends PrimitiveConverter {
@Override public GroupConverter asGroupConverter() { return new DumpGroupConverter(); }
}
}
| |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.crypto.provider;
import java.util.Locale;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.BadPaddingException;
/**
* This class represents the symmetric algorithms in its various modes
* (<code>ECB</code>, <code>CFB</code>, <code>OFB</code>, <code>CBC</code>,
* <code>PCBC</code>, <code>CTR</code>, and <code>CTS</code>) and
* padding schemes (<code>PKCS5Padding</code>, <code>NoPadding</code>,
* <code>ISO10126Padding</code>).
*
* @author Gigi Ankeny
* @author Jan Luehe
* @see ElectronicCodeBook
* @see CipherFeedback
* @see OutputFeedback
* @see CipherBlockChaining
* @see PCBC
* @see CounterMode
* @see CipherTextStealing
*/
final class CipherCore {
/*
* internal buffer
*/
private byte[] buffer = null;
/*
* internal buffer
*/
private int blockSize = 0;
/*
* unit size (number of input bytes that can be processed at a time)
*/
private int unitBytes = 0;
/*
* index of the content size left in the buffer
*/
private int buffered = 0;
/*
* minimum number of bytes in the buffer required for
* FeedbackCipher.encryptFinal()/decryptFinal() call.
* update() must buffer this many bytes before before starting
* to encrypt/decrypt data.
* currently, only CTS mode has a non-zero value due to its special
* handling on the last two blocks (the last one may be incomplete).
*/
private int minBytes = 0;
/*
* number of bytes needed to make the total input length a multiple
* of the blocksize (this is used in feedback mode, when the number of
* input bytes that are processed at a time is different from the block
* size)
*/
private int diffBlocksize = 0;
/*
* padding class
*/
private Padding padding = null;
/*
* internal cipher engine
*/
private FeedbackCipher cipher = null;
/*
* the cipher mode
*/
private int cipherMode = ECB_MODE;
/*
* are we encrypting or decrypting?
*/
private boolean decrypting = false;
/*
* Block Mode constants
*/
private static final int ECB_MODE = 0;
private static final int CBC_MODE = 1;
private static final int CFB_MODE = 2;
private static final int OFB_MODE = 3;
private static final int PCBC_MODE = 4;
private static final int CTR_MODE = 5;
private static final int CTS_MODE = 6;
/**
* Creates an instance of CipherCore with default ECB mode and
* PKCS5Padding.
*/
CipherCore(SymmetricCipher impl, int blkSize) {
blockSize = blkSize;
unitBytes = blkSize;
diffBlocksize = blkSize;
/*
* The buffer should be usable for all cipher mode and padding
* schemes. Thus, it has to be at least (blockSize+1) for CTS.
* In decryption mode, it also hold the possible padding block.
*/
buffer = new byte[blockSize*2];
// set mode and padding
cipher = new ElectronicCodeBook(impl);
padding = new PKCS5Padding(blockSize);
}
/**
* Sets the mode of this cipher.
*
* @param mode the cipher mode
*
* @exception NoSuchAlgorithmException if the requested cipher mode does
* not exist
*/
void setMode(String mode) throws NoSuchAlgorithmException {
if (mode == null)
throw new NoSuchAlgorithmException("null mode");
String modeUpperCase = mode.toUpperCase(Locale.ENGLISH);
if (modeUpperCase.equals("ECB")) {
return;
}
SymmetricCipher rawImpl = cipher.getEmbeddedCipher();
if (modeUpperCase.equals("CBC")) {
cipherMode = CBC_MODE;
cipher = new CipherBlockChaining(rawImpl);
}
else if (modeUpperCase.equals("CTS")) {
cipherMode = CTS_MODE;
cipher = new CipherTextStealing(rawImpl);
minBytes = blockSize+1;
padding = null;
}
else if (modeUpperCase.equals("CTR")) {
cipherMode = CTR_MODE;
cipher = new CounterMode(rawImpl);
unitBytes = 1;
padding = null;
}
else if (modeUpperCase.startsWith("CFB")) {
cipherMode = CFB_MODE;
unitBytes = getNumOfUnit(mode, "CFB".length(), blockSize);
cipher = new CipherFeedback(rawImpl, unitBytes);
}
else if (modeUpperCase.startsWith("OFB")) {
cipherMode = OFB_MODE;
unitBytes = getNumOfUnit(mode, "OFB".length(), blockSize);
cipher = new OutputFeedback(rawImpl, unitBytes);
}
else if (modeUpperCase.equals("PCBC")) {
cipherMode = PCBC_MODE;
cipher = new PCBC(rawImpl);
}
else {
throw new NoSuchAlgorithmException("Cipher mode: " + mode
+ " not found");
}
}
private static int getNumOfUnit(String mode, int offset, int blockSize)
throws NoSuchAlgorithmException {
int result = blockSize; // use blockSize as default value
if (mode.length() > offset) {
int numInt;
try {
Integer num = Integer.valueOf(mode.substring(offset));
numInt = num.intValue();
result = numInt >> 3;
} catch (NumberFormatException e) {
throw new NoSuchAlgorithmException
("Algorithm mode: " + mode + " not implemented");
}
if ((numInt % 8 != 0) || (result > blockSize)) {
throw new NoSuchAlgorithmException
("Invalid algorithm mode: " + mode);
}
}
return result;
}
/**
* Sets the padding mechanism of this cipher.
*
* @param padding the padding mechanism
*
* @exception NoSuchPaddingException if the requested padding mechanism
* does not exist
*/
void setPadding(String paddingScheme)
throws NoSuchPaddingException
{
if (paddingScheme == null) {
throw new NoSuchPaddingException("null padding");
}
if (paddingScheme.equalsIgnoreCase("NoPadding")) {
padding = null;
} else if (paddingScheme.equalsIgnoreCase("ISO10126Padding")) {
padding = new ISO10126Padding(blockSize);
} else if (!paddingScheme.equalsIgnoreCase("PKCS5Padding")) {
throw new NoSuchPaddingException("Padding: " + paddingScheme
+ " not implemented");
}
if ((padding != null) &&
((cipherMode == CTR_MODE) || (cipherMode == CTS_MODE))) {
padding = null;
throw new NoSuchPaddingException
((cipherMode == CTR_MODE? "CTR":"CTS") +
" mode must be used with NoPadding");
}
}
/**
* Returns the length in bytes that an output buffer would need to be in
* order to hold the result of the next <code>update</code> or
* <code>doFinal</code> operation, given the input length
* <code>inputLen</code> (in bytes).
*
* <p>This call takes into account any unprocessed (buffered) data from a
* previous <code>update</code> call, and padding.
*
* <p>The actual output length of the next <code>update</code> or
* <code>doFinal</code> call may be smaller than the length returned by
* this method.
*
* @param inputLen the input length (in bytes)
*
* @return the required output buffer size (in bytes)
*/
int getOutputSize(int inputLen) {
int totalLen = buffered + inputLen;
if (padding == null)
return totalLen;
if (decrypting)
return totalLen;
if (unitBytes != blockSize) {
if (totalLen < diffBlocksize)
return diffBlocksize;
else
return (totalLen + blockSize -
((totalLen - diffBlocksize) % blockSize));
} else {
return totalLen + padding.padLength(totalLen);
}
}
/**
* Returns the initialization vector (IV) in a new buffer.
*
* <p>This is useful in the case where a random IV has been created
* (see <a href = "#init">init</a>),
* or in the context of password-based encryption or
* decryption, where the IV is derived from a user-provided password.
*
* @return the initialization vector in a new buffer, or null if the
* underlying algorithm does not use an IV, or if the IV has not yet
* been set.
*/
byte[] getIV() {
byte[] iv = cipher.getIV();
return (iv == null) ? null : (byte[])iv.clone();
}
/**
* Returns the parameters used with this cipher.
*
* <p>The returned parameters may be the same that were used to initialize
* this cipher, or may contain the default set of parameters or a set of
* randomly generated parameters used by the underlying cipher
* implementation (provided that the underlying cipher implementation
* uses a default set of parameters or creates new parameters if it needs
* parameters but was not initialized with any).
*
* @return the parameters used with this cipher, or null if this cipher
* does not use any parameters.
*/
AlgorithmParameters getParameters(String algName) {
AlgorithmParameters params = null;
if (cipherMode == ECB_MODE) return null;
byte[] iv = getIV();
if (iv != null) {
AlgorithmParameterSpec ivSpec;
if (algName.equals("RC2")) {
RC2Crypt rawImpl = (RC2Crypt) cipher.getEmbeddedCipher();
ivSpec = new RC2ParameterSpec(rawImpl.getEffectiveKeyBits(),
iv);
} else {
ivSpec = new IvParameterSpec(iv);
}
try {
params = AlgorithmParameters.getInstance(algName, "SunJCE");
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException("Cannot find " + algName +
" AlgorithmParameters implementation in SunJCE provider");
} catch (NoSuchProviderException nspe) {
// should never happen
throw new RuntimeException("Cannot find SunJCE provider");
}
try {
params.init(ivSpec);
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException("IvParameterSpec not supported");
}
}
return params;
}
/**
* Initializes this cipher with a key and a source of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending on
* the value of <code>opmode</code>.
*
* <p>If this cipher requires an initialization vector (IV), it will get
* it from <code>random</code>.
* This behaviour should only be used in encryption or key wrapping
* mode, however.
* When initializing a cipher that requires an IV for decryption or
* key unwrapping, the IV
* (same IV that was used for encryption or key wrapping) must be provided
* explicitly as a
* parameter, in order to get the correct result.
*
* <p>This method also cleans existing buffer and other related state
* information.
*
* @param opmode the operation mode of this cipher (this is one of
* the following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the secret key
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher
*/
void init(int opmode, Key key, SecureRandom random)
throws InvalidKeyException {
try {
init(opmode, key, (AlgorithmParameterSpec)null, random);
} catch (InvalidAlgorithmParameterException e) {
throw new InvalidKeyException(e.getMessage());
}
}
/**
* Initializes this cipher with a key, a set of
* algorithm parameters, and a source of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending on
* the value of <code>opmode</code>.
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes, it will get them from <code>random</code>.
*
* @param opmode the operation mode of this cipher (this is one of
* the following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param params the algorithm parameters
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher
*/
void init(int opmode, Key key, AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
decrypting = (opmode == Cipher.DECRYPT_MODE)
|| (opmode == Cipher.UNWRAP_MODE);
byte[] keyBytes = getKeyBytes(key);
byte[] ivBytes;
if (params == null) {
ivBytes = null;
} else if (params instanceof IvParameterSpec) {
ivBytes = ((IvParameterSpec)params).getIV();
if ((ivBytes == null) || (ivBytes.length != blockSize)) {
throw new InvalidAlgorithmParameterException
("Wrong IV length: must be " + blockSize +
" bytes long");
}
} else if (params instanceof RC2ParameterSpec) {
ivBytes = ((RC2ParameterSpec)params).getIV();
if ((ivBytes != null) && (ivBytes.length != blockSize)) {
throw new InvalidAlgorithmParameterException
("Wrong IV length: must be " + blockSize +
" bytes long");
}
} else {
throw new InvalidAlgorithmParameterException("Wrong parameter "
+ "type: IV "
+ "expected");
}
if (cipherMode == ECB_MODE) {
if (ivBytes != null) {
throw new InvalidAlgorithmParameterException
("ECB mode cannot use IV");
}
} else if (ivBytes == null) {
if (decrypting) {
throw new InvalidAlgorithmParameterException("Parameters "
+ "missing");
}
if (random == null) {
random = SunJCE.RANDOM;
}
ivBytes = new byte[blockSize];
random.nextBytes(ivBytes);
}
buffered = 0;
diffBlocksize = blockSize;
String algorithm = key.getAlgorithm();
cipher.init(decrypting, algorithm, keyBytes, ivBytes);
}
void init(int opmode, Key key, AlgorithmParameters params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
IvParameterSpec ivSpec = null;
if (params != null) {
try {
ivSpec = (IvParameterSpec)params.getParameterSpec
(IvParameterSpec.class);
} catch (InvalidParameterSpecException ipse) {
throw new InvalidAlgorithmParameterException("Wrong parameter "
+ "type: IV "
+ "expected");
}
}
init(opmode, key, ivSpec, random);
}
/**
* Return the key bytes of the specified key. Throw an InvalidKeyException
* if the key is not usable.
*/
static byte[] getKeyBytes(Key key) throws InvalidKeyException {
if (key == null) {
throw new InvalidKeyException("No key given");
}
// note: key.getFormat() may return null
if (!"RAW".equalsIgnoreCase(key.getFormat())) {
throw new InvalidKeyException("Wrong format: RAW bytes needed");
}
byte[] keyBytes = key.getEncoded();
if (keyBytes == null) {
throw new InvalidKeyException("RAW key bytes missing");
}
return keyBytes;
}
/**
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, are processed, and the
* result is stored in a new buffer.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
*
* @return the new buffer with the result
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
*/
byte[] update(byte[] input, int inputOffset, int inputLen) {
byte[] output = null;
byte[] out = null;
try {
output = new byte[getOutputSize(inputLen)];
int len = update(input, inputOffset, inputLen, output,
0);
if (len == output.length) {
out = output;
} else {
out = new byte[len];
System.arraycopy(output, 0, out, 0, len);
}
} catch (ShortBufferException e) {
// never thrown
}
return out;
}
/**
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, are processed, and the
* result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code>.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
*/
int update(byte[] input, int inputOffset, int inputLen, byte[] output,
int outputOffset) throws ShortBufferException {
// figure out how much can be sent to crypto function
int len = buffered + inputLen - minBytes;
if (padding != null && decrypting) {
// do not include the padding bytes when decrypting
len -= blockSize;
}
// do not count the trailing bytes which do not make up a unit
len = (len > 0 ? (len - (len%unitBytes)) : 0);
// check output buffer capacity
if ((output == null) || ((output.length - outputOffset) < len)) {
throw new ShortBufferException("Output buffer must be "
+ "(at least) " + len
+ " bytes long");
}
if (len != 0) {
// there is some work to do
byte[] in = new byte[len];
int inputConsumed = len - buffered;
int bufferedConsumed = buffered;
if (inputConsumed < 0) {
inputConsumed = 0;
bufferedConsumed = len;
}
if (buffered != 0) {
System.arraycopy(buffer, 0, in, 0, bufferedConsumed);
}
if (inputConsumed > 0) {
System.arraycopy(input, inputOffset, in,
bufferedConsumed, inputConsumed);
}
if (decrypting) {
cipher.decrypt(in, 0, len, output, outputOffset);
} else {
cipher.encrypt(in, 0, len, output, outputOffset);
}
// Let's keep track of how many bytes are needed to make
// the total input length a multiple of blocksize when
// padding is applied
if (unitBytes != blockSize) {
if (len < diffBlocksize)
diffBlocksize -= len;
else
diffBlocksize = blockSize -
((len - diffBlocksize) % blockSize);
}
inputLen -= inputConsumed;
inputOffset += inputConsumed;
outputOffset += len;
buffered -= bufferedConsumed;
if (buffered > 0) {
System.arraycopy(buffer, bufferedConsumed, buffer, 0,
buffered);
}
}
// left over again
if (inputLen > 0) {
System.arraycopy(input, inputOffset, buffer, buffered,
inputLen);
}
buffered += inputLen;
return len;
}
/**
* Encrypts or decrypts data in a single-part operation,
* or finishes a multiple-part operation.
* The data is encrypted or decrypted, depending on how this cipher was
* initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, and any input bytes that
* may have been buffered during a previous <code>update</code> operation,
* are processed, with padding (if requested) being applied.
* The result is stored in a new buffer.
*
* <p>The cipher is reset to its initial state (uninitialized) after this
* call.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
*
* @return the new buffer with the result
*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
byte[] doFinal(byte[] input, int inputOffset, int inputLen)
throws IllegalBlockSizeException, BadPaddingException {
byte[] output = null;
byte[] out = null;
try {
output = new byte[getOutputSize(inputLen)];
int len = doFinal(input, inputOffset, inputLen, output, 0);
if (len < output.length) {
out = new byte[len];
if (len != 0)
System.arraycopy(output, 0, out, 0, len);
} else {
out = output;
}
} catch (ShortBufferException e) {
// never thrown
}
return out;
}
/**
* Encrypts or decrypts data in a single-part operation,
* or finishes a multiple-part operation.
* The data is encrypted or decrypted, depending on how this cipher was
* initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, and any input bytes that
* may have been buffered during a previous <code>update</code> operation,
* are processed, with padding (if requested) being applied.
* The result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code>.
*
* <p>The cipher is reset to its initial state (uninitialized) after this
* call.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
int outputOffset)
throws IllegalBlockSizeException, ShortBufferException,
BadPaddingException {
// calculate the total input length
int totalLen = buffered + inputLen;
int paddedLen = totalLen;
int paddingLen = 0;
// will the total input length be a multiple of blockSize?
if (unitBytes != blockSize) {
if (totalLen < diffBlocksize) {
paddingLen = diffBlocksize - totalLen;
} else {
paddingLen = blockSize -
((totalLen - diffBlocksize) % blockSize);
}
} else if (padding != null) {
paddingLen = padding.padLength(totalLen);
}
if ((paddingLen > 0) && (paddingLen != blockSize) &&
(padding != null) && decrypting) {
throw new IllegalBlockSizeException
("Input length must be multiple of " + blockSize +
" when decrypting with padded cipher");
}
// if encrypting and padding not null, add padding
if (!decrypting && padding != null)
paddedLen += paddingLen;
// check output buffer capacity.
// if we are decrypting with padding applied, we can perform this
// check only after we have determined how many padding bytes there
// are.
if (output == null) {
throw new ShortBufferException("Output buffer is null");
}
int outputCapacity = output.length - outputOffset;
if (((!decrypting) || (padding == null)) &&
(outputCapacity < paddedLen) ||
(decrypting && (outputCapacity < (paddedLen - blockSize)))) {
throw new ShortBufferException("Output buffer too short: "
+ outputCapacity + " bytes given, "
+ paddedLen + " bytes needed");
}
// prepare the final input avoiding copying if possible
byte[] finalBuf = input;
int finalOffset = inputOffset;
if ((buffered != 0) || (!decrypting && padding != null)) {
finalOffset = 0;
finalBuf = new byte[paddedLen];
if (buffered != 0) {
System.arraycopy(buffer, 0, finalBuf, 0, buffered);
}
if (inputLen != 0) {
System.arraycopy(input, inputOffset, finalBuf,
buffered, inputLen);
}
if (!decrypting && padding != null) {
padding.padWithLen(finalBuf, totalLen, paddingLen);
}
}
if (decrypting) {
// if the size of specified output buffer is less than
// the length of the cipher text, then the current
// content of cipher has to be preserved in order for
// users to retry the call with a larger buffer in the
// case of ShortBufferException.
if (outputCapacity < paddedLen) {
cipher.save();
}
// create temporary output buffer so that only "real"
// data bytes are passed to user's output buffer.
byte[] outWithPadding = new byte[totalLen];
totalLen = finalNoPadding(finalBuf, finalOffset, outWithPadding,
0, totalLen);
if (padding != null) {
int padStart = padding.unpad(outWithPadding, 0, totalLen);
if (padStart < 0) {
throw new BadPaddingException("Given final block not "
+ "properly padded");
}
totalLen = padStart;
}
if ((output.length - outputOffset) < totalLen) {
// restore so users can retry with a larger buffer
cipher.restore();
throw new ShortBufferException("Output buffer too short: "
+ (output.length-outputOffset)
+ " bytes given, " + totalLen
+ " bytes needed");
}
for (int i = 0; i < totalLen; i++) {
output[outputOffset + i] = outWithPadding[i];
}
} else { // encrypting
totalLen = finalNoPadding(finalBuf, finalOffset, output,
outputOffset, paddedLen);
}
buffered = 0;
diffBlocksize = blockSize;
if (cipherMode != ECB_MODE) {
((FeedbackCipher)cipher).reset();
}
return totalLen;
}
private int finalNoPadding(byte[] in, int inOff, byte[] out, int outOff,
int len)
throws IllegalBlockSizeException
{
if (in == null || len == 0)
return 0;
if ((cipherMode != CFB_MODE) && (cipherMode != OFB_MODE)
&& ((len % unitBytes) != 0) && (cipherMode != CTS_MODE)) {
if (padding != null) {
throw new IllegalBlockSizeException
("Input length (with padding) not multiple of " +
unitBytes + " bytes");
} else {
throw new IllegalBlockSizeException
("Input length not multiple of " + unitBytes
+ " bytes");
}
}
if (decrypting) {
cipher.decryptFinal(in, inOff, len, out, outOff);
} else {
cipher.encryptFinal(in, inOff, len, out, outOff);
}
return len;
}
// Note: Wrap() and Unwrap() are the same in
// each of SunJCE CipherSpi implementation classes.
// They are duplicated due to export control requirements:
// All CipherSpi implementation must be final.
/**
* Wrap a key.
*
* @param key the key to be wrapped.
*
* @return the wrapped key.
*
* @exception IllegalBlockSizeException if this cipher is a block
* cipher, no padding has been requested, and the length of the
* encoding of the key to be wrapped is not a
* multiple of the block size.
*
* @exception InvalidKeyException if it is impossible or unsafe to
* wrap the key with this cipher (e.g., a hardware protected key is
* being passed to a software only cipher).
*/
byte[] wrap(Key key)
throws IllegalBlockSizeException, InvalidKeyException {
byte[] result = null;
try {
byte[] encodedKey = key.getEncoded();
if ((encodedKey == null) || (encodedKey.length == 0)) {
throw new InvalidKeyException("Cannot get an encoding of " +
"the key to be wrapped");
}
result = doFinal(encodedKey, 0, encodedKey.length);
} catch (BadPaddingException e) {
// Should never happen
}
return result;
}
/**
* Unwrap a previously wrapped key.
*
* @param wrappedKey the key to be unwrapped.
*
* @param wrappedKeyAlgorithm the algorithm the wrapped key is for.
*
* @param wrappedKeyType the type of the wrapped key.
* This is one of <code>Cipher.SECRET_KEY</code>,
* <code>Cipher.PRIVATE_KEY</code>, or <code>Cipher.PUBLIC_KEY</code>.
*
* @return the unwrapped key.
*
* @exception NoSuchAlgorithmException if no installed providers
* can create keys of type <code>wrappedKeyType</code> for the
* <code>wrappedKeyAlgorithm</code>.
*
* @exception InvalidKeyException if <code>wrappedKey</code> does not
* represent a wrapped key of type <code>wrappedKeyType</code> for
* the <code>wrappedKeyAlgorithm</code>.
*/
Key unwrap(byte[] wrappedKey, String wrappedKeyAlgorithm,
int wrappedKeyType)
throws InvalidKeyException, NoSuchAlgorithmException {
byte[] encodedKey;
try {
encodedKey = doFinal(wrappedKey, 0, wrappedKey.length);
} catch (BadPaddingException ePadding) {
throw new InvalidKeyException("The wrapped key is not padded " +
"correctly");
} catch (IllegalBlockSizeException eBlockSize) {
throw new InvalidKeyException("The wrapped key does not have " +
"the correct length");
}
return ConstructKeys.constructKey(encodedKey, wrappedKeyAlgorithm,
wrappedKeyType);
}
}
| |
/*
* Copyright 2016 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.config;
import com.thoughtworks.go.domain.CommentRenderer;
import com.thoughtworks.go.domain.ConfigErrors;
import com.thoughtworks.go.domain.DefaultCommentRenderer;
import com.thoughtworks.go.util.StringUtil;
import com.thoughtworks.go.util.XmlUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.http.client.utils.URIBuilder;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.regex.Pattern;
/**
* @understands mingle project for pipeline
*/
@ConfigTag("mingle")
public class MingleConfig implements ParamsAttributeAware, Validatable, CommentRenderer {
@ConfigAttribute(value = "baseUrl", optional = false)
private String baseUrl;
@ConfigAttribute(value = "projectIdentifier", optional = false)
private String projectIdentifier;
@ConfigSubtag
private MqlCriteria mqlCriteria = new MqlCriteria();
private final ConfigErrors configErrors = new ConfigErrors();
private static final String DELIMITER = "/";
public static final String BASE_URL = "baseUrl";
public static final String PROJECT_IDENTIFIER = "projectIdentifier";
public static final String MQL_GROUPING_CONDITIONS = "mqlCriteria";
private static final String MINGLE_URL_PATTERN = "https://.+";
private static final Pattern MINGLE_URL_PATTERN_REGEX = Pattern.compile(String.format("^(%s)$", MINGLE_URL_PATTERN));
private static final String PROJECT_IDENTIFIER_PATTERN = "[^\\s]+";
private static final Pattern PROJECT_IDENTIFIER_PATTERN_REGEX = Pattern.compile(String.format("^(%s)$", PROJECT_IDENTIFIER_PATTERN));
public MingleConfig() {
}
public MingleConfig(String baseUrl, String projectIdentifier, String mql) {
this(baseUrl, projectIdentifier);
this.mqlCriteria = new MqlCriteria(mql);
}
public MingleConfig(String baseUrl, String projectIdentifier) {
this.baseUrl = baseUrl;
this.projectIdentifier = projectIdentifier;
}
public boolean validateTree(ValidationContext validationContext) {
validate(validationContext);
return errors().isEmpty();
}
public void validate(ValidationContext validationContext) {
if (isDefined() && XmlUtils.doesNotMatchUsingXsdRegex(MINGLE_URL_PATTERN_REGEX, baseUrl)) {
configErrors.add(BASE_URL, "Should be a URL starting with https://");
}
if (projectIdentifier != null && XmlUtils.doesNotMatchUsingXsdRegex(PROJECT_IDENTIFIER_PATTERN_REGEX, projectIdentifier)) {
configErrors.add(PROJECT_IDENTIFIER, "Should be a valid mingle identifier.");
}
}
public boolean isDefined() {
return baseUrl != null;
}
public ConfigErrors errors() {
return configErrors;
}
public void addError(String fieldName, String message) {
configErrors.add(fieldName, message);
}
public String urlFor(String path) throws MalformedURLException, URISyntaxException {
URIBuilder baseUri = new URIBuilder(baseUrl);
String originalPath = baseUri.getPath();
if (originalPath == null) {
originalPath = "";
}
if (originalPath.endsWith(DELIMITER) && path.startsWith(DELIMITER)) {
path = path.replaceFirst(DELIMITER, "");
}
return baseUri.setPath(originalPath + path).toString();
}
public String getProjectIdentifier() {
return projectIdentifier;
}
public void setProjectIdentifier(String projectIdentifier) {
this.projectIdentifier = projectIdentifier;
}
public String getQuotedMql() {
String mqlString = mqlCriteria.equals(new MqlCriteria()) ? "" : mqlCriteria.getMql();
return StringUtil.quoteJavascriptString(mqlString);
}
public String getQuotedProjectIdentifier() {
return StringUtil.quoteJavascriptString(projectIdentifier);
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public MqlCriteria getMqlCriteria() {
return mqlCriteria;
}
public void setMqlCriteria(String mql) {
this.mqlCriteria = new MqlCriteria(mql);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MingleConfig that = (MingleConfig) o;
if (baseUrl != null ? !baseUrl.equals(that.baseUrl) : that.baseUrl != null) {
return false;
}
if (mqlCriteria != null ? !mqlCriteria.equals(that.mqlCriteria) : that.mqlCriteria != null) {
return false;
}
if (projectIdentifier != null ? !projectIdentifier.equals(that.projectIdentifier) : that.projectIdentifier != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = baseUrl != null ? baseUrl.hashCode() : 0;
result = 31 * result + (projectIdentifier != null ? projectIdentifier.hashCode() : 0);
result = 31 * result + (mqlCriteria != null ? mqlCriteria.hashCode() : 0);
return result;
}
@Override
public String toString() {
return new ToStringBuilder(this).
append("baseUrl", baseUrl).
append("projectName", projectIdentifier).
append("mqlCriteria", mqlCriteria).
toString();
}
public void setConfigAttributes(Object attributes) {
if (attributes == null) {
return;
}
Map attributeMap = (Map) attributes;
if (attributeMap.containsKey(BASE_URL)) {
baseUrl = (String) attributeMap.get(BASE_URL);
}
if (attributeMap.containsKey(PROJECT_IDENTIFIER)) {
projectIdentifier = (String) attributeMap.get(PROJECT_IDENTIFIER);
}
if (attributeMap.containsKey(MQL_GROUPING_CONDITIONS)) {
mqlCriteria = (mqlCriteria == null) ? new MqlCriteria() : mqlCriteria;
mqlCriteria.setConfigAttributes(attributeMap.get(MQL_GROUPING_CONDITIONS));
}
}
public static MingleConfig create(Object attributes) {
MingleConfig mingleConfig = new MingleConfig();
mingleConfig.setConfigAttributes(attributes);
return mingleConfig;
}
public boolean isDifferentFrom(MingleConfig other) {
if (baseUrl != null ? !baseUrl.equals(other.baseUrl) : other.baseUrl != null) {
return false;
}
if (projectIdentifier != null ? !projectIdentifier.equals(other.projectIdentifier) : other.projectIdentifier != null) {
return false;
}
return true;
}
public String render(String text) {
try {
String urlPart = urlFor(String.format("/projects/%s/cards/", projectIdentifier));
return new DefaultCommentRenderer(urlPart + "${ID}", "#(\\d+)").render(text);
} catch (MalformedURLException | URISyntaxException e) {
throw new RuntimeException("Could not construct the URL to generate the link.", e);
}
}
}
| |
/*
* Copyright (C) 2014 Abhishek
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package userInterface.pharmacy;
import userInterface.pharmaceuticalCompany.*;
import userInterface.patient.*;
import baseClasses.enterprise.CityEnterprise;
import baseClasses.enterprise.CountryEnterprise;
import baseClasses.enterprise.Enterprise;
import baseClasses.enterprise.HospitalEnterprise;
import baseClasses.enterprise.PharmaceuticalCompanyEnterprise;
import baseClasses.enterprise.PharmacyEnterprise;
import baseClasses.enterprise.StateEnterprise;
import baseClasses.network.Network;
import baseClasses.organization.DoctorOrganization;
import baseClasses.organization.Organization;
import baseClasses.organization.PatientOrganization;
import baseClasses.userAccount.UserAccount;
import javax.swing.JOptionPane;
import workQueue.DoctorMail;
import workQueue.HospitalMail;
import workQueue.PatientMail;
import workQueue.PharmaceuticalCompanyMail;
import workQueue.PharmacyMail;
/**
*
* @author Abhishek
*/
public class ComposeMail extends javax.swing.JPanel {
/**
* Creates new form ComposeMail
*/
private Network internationalNetwork;
private DoctorOrganization doctorOrganization = null;
private PharmaceuticalCompanyEnterprise pharmaceuticalCompanyEnterprise = null;
private PharmacyEnterprise pharmacyEnterprise = null;
private HospitalEnterprise hospitalEnterprise = null;
private PatientOrganization patientOrganization = null;
private CityEnterprise cityEnterprise = null;
private UserAccount userAccount = null;
public ComposeMail(Network internationalNetwork, UserAccount userAccount) {
initComponents();
this.internationalNetwork = internationalNetwork;
this.userAccount = userAccount;
populateCountryList();
cmbStateList.setEnabled(false);
cmbCityList.setEnabled(false);
cmbRole.setEnabled(false);
cmbPerson.setEnabled(false);
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
txtSubject = new javax.swing.JTextField();
lblName3 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
btnClear = new javax.swing.JButton();
lblName1 = new javax.swing.JLabel();
cmbRole = new javax.swing.JComboBox();
lblSelectCountry4 = new javax.swing.JLabel();
cmbCountryList = new javax.swing.JComboBox();
cmbStateList = new javax.swing.JComboBox();
lblSelectCountry1 = new javax.swing.JLabel();
lblSelectCountry2 = new javax.swing.JLabel();
cmbCityList = new javax.swing.JComboBox();
btnSend = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
taBody = new javax.swing.JTextArea();
lblSelectCountry3 = new javax.swing.JLabel();
cmbPerson = new javax.swing.JComboBox();
btnLoadContacts = new javax.swing.JButton();
calendar = new com.toedter.calendar.JCalendar();
setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/baseClasses/healtech logo.PNG"))); // NOI18N
txtSubject.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtSubject.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtSubjectActionPerformed(evt);
}
});
lblName3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
lblName3.setForeground(new java.awt.Color(0, 153, 51));
lblName3.setText("To");
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel9.setForeground(new java.awt.Color(0, 153, 51));
jLabel9.setText("Subject");
btnClear.setBackground(new java.awt.Color(255, 255, 255));
btnClear.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
btnClear.setForeground(new java.awt.Color(0, 153, 0));
btnClear.setText("Clear");
btnClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnClearActionPerformed(evt);
}
});
lblName1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
lblName1.setForeground(new java.awt.Color(0, 153, 51));
lblName1.setText(" Compose Mail");
cmbRole.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
cmbRole.setForeground(new java.awt.Color(0, 153, 51));
cmbRole.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Doctor", "Pharmacy", "Pharmaceutical Company", "Hospital", "Patient" }));
cmbRole.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbRoleActionPerformed(evt);
}
});
lblSelectCountry4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
lblSelectCountry4.setForeground(new java.awt.Color(0, 153, 51));
lblSelectCountry4.setText("Select Country:");
cmbCountryList.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
cmbCountryList.setForeground(new java.awt.Color(0, 153, 51));
cmbCountryList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbCountryListActionPerformed(evt);
}
});
cmbStateList.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
cmbStateList.setForeground(new java.awt.Color(0, 153, 51));
cmbStateList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbStateListActionPerformed(evt);
}
});
lblSelectCountry1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
lblSelectCountry1.setForeground(new java.awt.Color(0, 153, 51));
lblSelectCountry1.setText("Select State:");
lblSelectCountry2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
lblSelectCountry2.setForeground(new java.awt.Color(0, 153, 51));
lblSelectCountry2.setText("Role:");
cmbCityList.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
cmbCityList.setForeground(new java.awt.Color(0, 153, 51));
cmbCityList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbCityListActionPerformed(evt);
}
});
btnSend.setBackground(new java.awt.Color(255, 255, 255));
btnSend.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
btnSend.setForeground(new java.awt.Color(0, 153, 0));
btnSend.setText("Send");
btnSend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSendActionPerformed(evt);
}
});
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel10.setForeground(new java.awt.Color(0, 153, 51));
jLabel10.setText("Body");
taBody.setColumns(20);
taBody.setRows(5);
jScrollPane1.setViewportView(taBody);
lblSelectCountry3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
lblSelectCountry3.setForeground(new java.awt.Color(0, 153, 51));
lblSelectCountry3.setText("Select City:");
cmbPerson.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
cmbPerson.setForeground(new java.awt.Color(0, 153, 51));
btnLoadContacts.setBackground(new java.awt.Color(255, 255, 255));
btnLoadContacts.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
btnLoadContacts.setForeground(new java.awt.Color(0, 153, 0));
btnLoadContacts.setText("Load Contacts");
btnLoadContacts.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadContactsActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(226, 226, 226)
.addComponent(btnClear)
.addGap(289, 289, 289)
.addComponent(btnSend)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(lblName3)
.addGap(195, 195, 195)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lblSelectCountry4)
.addGap(40, 40, 40)
.addComponent(cmbCountryList, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(lblSelectCountry1)
.addGap(65, 65, 65)
.addComponent(cmbStateList, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblSelectCountry2)
.addComponent(lblSelectCountry3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(cmbRole, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmbCityList, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cmbPerson, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnLoadContacts, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
.addGap(101, 101, 101)
.addComponent(calendar, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9)
.addGap(170, 170, 170)
.addComponent(txtSubject, javax.swing.GroupLayout.PREFERRED_SIZE, 735, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblName1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel10)
.addGap(195, 195, 195)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 735, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(0, 484, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(lblName1)
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(lblName3)
.addGap(277, 277, 277))
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbCountryList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblSelectCountry4))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(lblSelectCountry1))
.addComponent(cmbStateList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbCityList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblSelectCountry3)))
.addComponent(calendar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbRole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblSelectCountry2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnLoadContacts)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cmbPerson, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(txtSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnClear)
.addComponent(btnSend))
.addGap(27, 27, 27))))
);
}// </editor-fold>//GEN-END:initComponents
private void txtSubjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSubjectActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtSubjectActionPerformed
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
// TODO add your handling code here:
txtSubject.setText("");
taBody.setText("");
}//GEN-LAST:event_btnClearActionPerformed
private void cmbCountryListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCountryListActionPerformed
// TODO add your handling code here:
cmbStateList.setEnabled(true);
populateStateList((CountryEnterprise) cmbCountryList.getSelectedItem());
}//GEN-LAST:event_cmbCountryListActionPerformed
private void cmbStateListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbStateListActionPerformed
// TODO add your handling code here:
cmbCityList.setEnabled(true);
populateCityList((StateEnterprise) cmbStateList.getSelectedItem());
}//GEN-LAST:event_cmbStateListActionPerformed
private void cmbCityListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCityListActionPerformed
// TODO add your handling code here:
cmbRole.setEnabled(true);
}//GEN-LAST:event_cmbCityListActionPerformed
private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
// TODO add your handling code here:
// if ((txtSubject.getText().equals(""))) {
// int result = JOptionPane.showConfirmDialog(this, "Do you want to send the mail without a subject?", "Confirm", JOptionPane.YES_NO_OPTION);
// if (result == JOptionPane.YES_OPTION) {
cityEnterprise = (CityEnterprise) cmbCityList.getSelectedItem();
if (((String) cmbRole.getSelectedItem()).equals("Doctor")) {
DoctorMail doctorMail = new DoctorMail();
UserAccount receiver = (UserAccount) cmbPerson.getSelectedItem();
doctorMail.setReceiver(receiver);
doctorMail.setSubject(txtSubject.getText());
doctorMail.setMessage(taBody.getText());
doctorMail.setSender(userAccount);
doctorMail.setRequestDate(calendar.getDate());
receiver.getWorkQueue().getWorkRequestList().add(doctorMail);
userAccount.getWorkQueue().getWorkRequestList().add(doctorMail);
} else if (((String) cmbRole.getSelectedItem()).equals("Patient")) {
PatientMail patientMail = new PatientMail();
UserAccount receiver = (UserAccount) cmbPerson.getSelectedItem();
patientMail.setReceiver(receiver);
patientMail.setSubject(txtSubject.getText());
patientMail.setMessage(taBody.getText());
patientMail.setSender(userAccount);
patientMail.setRequestDate(calendar.getDate());
receiver.getWorkQueue().getWorkRequestList().add(patientMail);
userAccount.getWorkQueue().getWorkRequestList().add(patientMail);
} else if (((String) cmbRole.getSelectedItem()).equals("Hospital")) {
HospitalMail hospitalMail = new HospitalMail();
HospitalEnterprise receiver = (HospitalEnterprise) cmbPerson.getSelectedItem();
hospitalMail.setReceiver(receiver);
hospitalMail.setSubject(txtSubject.getText());
hospitalMail.setMessage(taBody.getText());
hospitalMail.setSender(userAccount);
hospitalMail.setRequestDate(calendar.getDate());
receiver.getWorkQueue().getWorkRequestList().add(hospitalMail);
userAccount.getWorkQueue().getWorkRequestList().add(hospitalMail);
} else if (((String) cmbRole.getSelectedItem()).equals("Pharmacy")) {
PharmacyMail pharmacyMail = new PharmacyMail();
PharmacyEnterprise receiver = (PharmacyEnterprise) cmbCityList.getSelectedItem();
pharmacyMail.setReceiver(receiver);
pharmacyMail.setSubject(txtSubject.getText());
pharmacyMail.setMessage(taBody.getText());
pharmacyMail.setSender(userAccount);
pharmacyMail.setRequestDate(calendar.getDate());
receiver.getWorkQueue().getWorkRequestList().add(pharmacyMail);
userAccount.getWorkQueue().getWorkRequestList().add(pharmacyMail);
} else if (((String) cmbRole.getSelectedItem()).equals("Pharmaceutical Company")) {
PharmaceuticalCompanyMail pharmaceuticalCompanyMail = new PharmaceuticalCompanyMail();
PharmaceuticalCompanyEnterprise receiver = (PharmaceuticalCompanyEnterprise) cmbPerson.getSelectedItem();
pharmaceuticalCompanyMail.setReceiver(receiver);
pharmaceuticalCompanyMail.setSubject(txtSubject.getText());
pharmaceuticalCompanyMail.setMessage(taBody.getText());
pharmaceuticalCompanyMail.setSender(userAccount);
pharmaceuticalCompanyMail.setRequestDate(calendar.getDate());
receiver.getWorkQueue().getWorkRequestList().add(pharmaceuticalCompanyMail);
userAccount.getWorkQueue().getWorkRequestList().add(pharmaceuticalCompanyMail);
// }}
}
}//GEN-LAST:event_btnSendActionPerformed
private void cmbRoleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbRoleActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cmbRoleActionPerformed
private void btnLoadContactsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadContactsActionPerformed
// TODO add your handling code here:
cmbPerson.removeAllItems();
cmbPerson.setEnabled(true);
cityEnterprise = (CityEnterprise) cmbCityList.getSelectedItem();
if (((String) cmbRole.getSelectedItem()).equals("Doctor")) {
System.out.println("printing from compose mail: " + cityEnterprise.getCityNetwork().getEnterpriseDirectory().getEnterpriseList());
for (Enterprise hospital : cityEnterprise.getCityNetwork().getEnterpriseDirectory().getEnterpriseList()) {
if (hospital.getClass() == HospitalEnterprise.class) {
hospitalEnterprise = (HospitalEnterprise) hospital;
System.out.println("org" + hospitalEnterprise.getOrganizationDirectory().getOrganizationList());
for (Organization org : hospitalEnterprise.getOrganizationDirectory().getOrganizationList()) {
if (org.getClass() == DoctorOrganization.class) {
doctorOrganization = (DoctorOrganization) org;
System.out.println("user account: " + doctorOrganization.getUserAccountDirectory().getUserAccountList());
for (UserAccount ua : doctorOrganization.getUserAccountDirectory().getUserAccountList()) {
cmbPerson.addItem(ua);
}
}
}
}
}
} else if (((String) cmbRole.getSelectedItem()).equals("Pharmaceutical Company")) {
for (Enterprise hospital : cityEnterprise.getCityNetwork().getEnterpriseDirectory().getEnterpriseList()) {
if (hospital.getClass() == PharmaceuticalCompanyEnterprise.class) {
pharmaceuticalCompanyEnterprise = (PharmaceuticalCompanyEnterprise) hospital;
cmbPerson.addItem(pharmaceuticalCompanyEnterprise);
}
}
} else if (((String) cmbRole.getSelectedItem()).equals("Pharmacy")) {
for (Enterprise hospital : cityEnterprise.getCityNetwork().getEnterpriseDirectory().getEnterpriseList()) {
if (hospital.getClass() == PharmacyEnterprise.class) {
pharmacyEnterprise = (PharmacyEnterprise) hospital;
cmbPerson.addItem(pharmacyEnterprise);
}
}
} else if (((String) cmbRole.getSelectedItem()).equals("Hospital")) {
for (Enterprise hospital : cityEnterprise.getCityNetwork().getEnterpriseDirectory().getEnterpriseList()) {
if (hospital.getClass() == HospitalEnterprise.class) {
hospitalEnterprise = (HospitalEnterprise) hospital;
cmbPerson.addItem(hospitalEnterprise);
}
}
} else if (((String) cmbRole.getSelectedItem()).equals("Patient")) {
System.out.println("printing from compose mail patient: " + cityEnterprise.getCityNetwork().getEnterpriseDirectory().getEnterpriseList());
for (Enterprise hospital : cityEnterprise.getCityNetwork().getEnterpriseDirectory().getEnterpriseList()) {
if (hospital.getClass() == HospitalEnterprise.class) {
hospitalEnterprise = (HospitalEnterprise) hospital;
System.out.println("org" + hospitalEnterprise.getOrganizationDirectory().getOrganizationList());
for (Organization org : hospitalEnterprise.getOrganizationDirectory().getOrganizationList()) {
if (org.getClass() == PatientOrganization.class) {
patientOrganization = (PatientOrganization) org;
System.out.println("user account: " + doctorOrganization.getUserAccountDirectory().getUserAccountList());
for (UserAccount ua : patientOrganization.getUserAccountDirectory().getUserAccountList()) {
cmbPerson.addItem(ua);
}
}
}
}
}
}
}//GEN-LAST:event_btnLoadContactsActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnClear;
private javax.swing.JButton btnLoadContacts;
private javax.swing.JButton btnSend;
private com.toedter.calendar.JCalendar calendar;
private javax.swing.JComboBox cmbCityList;
private javax.swing.JComboBox cmbCountryList;
private javax.swing.JComboBox cmbPerson;
private javax.swing.JComboBox cmbRole;
private javax.swing.JComboBox cmbStateList;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblName1;
private javax.swing.JLabel lblName3;
private javax.swing.JLabel lblSelectCountry1;
private javax.swing.JLabel lblSelectCountry2;
private javax.swing.JLabel lblSelectCountry3;
private javax.swing.JLabel lblSelectCountry4;
private javax.swing.JTextArea taBody;
private javax.swing.JTextField txtSubject;
// End of variables declaration//GEN-END:variables
private void populateCountryList() {
cmbCountryList.removeAllItems();
CountryEnterprise countryEnterprise;
for (Enterprise country : internationalNetwork.getEnterpriseDirectory().getEnterpriseList()) {
cmbCountryList.addItem((CountryEnterprise) country);
}
}
private void populateStateList(CountryEnterprise countryEnterprise) {
cmbStateList.removeAllItems();
for (Enterprise state : countryEnterprise.getCountryNetwork().getEnterpriseDirectory().getEnterpriseList())
{
if(state.getClass() == StateEnterprise.class)
cmbStateList.addItem((StateEnterprise) state);
}
}
private void populateCityList(StateEnterprise stateEnterprise) {
cmbCityList.removeAllItems();
System.out.println("State Enterprise List size" + stateEnterprise.getStateNetwork().getEnterpriseDirectory().getEnterpriseList().size());
for (Enterprise city : stateEnterprise.getStateNetwork().getEnterpriseDirectory().getEnterpriseList()) {
System.out.println("City Enterprise" + city);
cmbCityList.addItem((CityEnterprise) city);
}
}
}
| |
/*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.recipe_app.client.content_provider;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
import com.recipe_app.client.database.RecipeIngredientTable;
import com.recipe_app.client.database.RecipeInstructionsTable;
import com.recipe_app.client.database.RecipeNoteTable;
import com.recipe_app.client.database.RecipeTable;
/**
* Created by simister on 10/21/14.
*/
public class RecipeContentProvider extends ContentProvider {
// database
private RecipeDatabaseHelper database;
// used for the UriMacher
private static final int RECIPES = 10;
private static final int RECIPE_ID = 20;
private static final int RECIPE_INGREDIENTS = 30;
private static final int RECIPE_INSTRUCTIONS = 40;
private static final int RECIPE_NOTES = 50;
private static final String AUTHORITY = "com.recipe_app";
private static final String BASE_PATH = "recipe";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI(AUTHORITY, BASE_PATH, RECIPES);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/ingredients/*", RECIPE_INGREDIENTS);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/instructions/*", RECIPE_INSTRUCTIONS);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/notes/*", RECIPE_NOTES);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/*", RECIPE_ID);
}
@Override
public boolean onCreate() {
database = new RecipeDatabaseHelper(getContext());
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
int uriType = sURIMatcher.match(uri);
if (uriType == RECIPES) {
return getAllRecipes(projection);
} else if (uriType == RECIPE_ID) {
return getRecipe(uri);
} else if (uriType == RECIPE_INGREDIENTS) {
return getIngredientsByRecipe(uri);
} else if (uriType == RECIPE_INSTRUCTIONS) {
return getInstructionsByRecipe(uri);
} else if (uriType == RECIPE_NOTES) {
return getNoteByRecipe(uri);
} else {
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
public Cursor getAllRecipes(String[] projection) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(RecipeTable.TABLE + ", " + RecipeNoteTable.TABLE);
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = queryBuilder.query(db, projection, null, null, null, null, null);
return cursor;
}
public Cursor getRecipe(Uri uri) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(RecipeTable.TABLE);
String[] projection = {RecipeTable.ID, RecipeTable.TITLE,
RecipeTable.DESCRIPTION, RecipeTable.PHOTO,
RecipeTable.PREP_TIME};
SQLiteDatabase db = database.getReadableDatabase();
queryBuilder.appendWhere(RecipeTable.ID + "='"
+ uri.getLastPathSegment() + "'");
Cursor cursor = queryBuilder.query(db, projection, null,
null, null, null, null);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
public Cursor getIngredientsByRecipe(Uri uri) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(RecipeTable.TABLE + ", " + RecipeIngredientTable.TABLE);
queryBuilder.appendWhere(RecipeTable.ID + "='" + uri.getLastPathSegment() + "' AND " +
RecipeIngredientTable.RECIPE_ID + "=" + RecipeTable.ID);
String[] projection = {RecipeIngredientTable.AMOUNT, RecipeIngredientTable.DESCRIPTION};
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = queryBuilder.query(db, projection, null, null, null, null, null);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
public Cursor getInstructionsByRecipe(Uri uri) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(RecipeTable.TABLE + ", " + RecipeInstructionsTable.TABLE);
queryBuilder.appendWhere(RecipeTable.ID + "='" + uri.getLastPathSegment() + "' AND " +
RecipeInstructionsTable.RECIPE_ID + "=" + RecipeTable.ID);
String[] projection = {RecipeInstructionsTable.NUM, RecipeInstructionsTable.DESCRIPTION,
RecipeInstructionsTable.PHOTO};
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = queryBuilder.query(db, projection, null, null, null, null, null);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
public Cursor getNoteByRecipe(Uri uri) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(RecipeTable.TABLE + ", " + RecipeNoteTable.TABLE);
queryBuilder.appendWhere(RecipeTable.ID + "='" + uri.getLastPathSegment() + "' AND " +
RecipeNoteTable.RECIPE_ID + "=" + RecipeTable.ID);
String[] projection = {RecipeNoteTable.TEXT};
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = queryBuilder.query(db, projection, null, null, null, null, null);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
public Uri insertNoteForRecipe(Uri uri, ContentValues values) {
String sql = "INSERT INTO `" + RecipeNoteTable.TABLE + "` (`" + RecipeNoteTable
.RECIPE_ID_COLUMN + "`, `" + RecipeNoteTable.TEXT_COLUMN + "`) VALUES ('" + uri
.getLastPathSegment() + "', '" + values.get(RecipeNoteTable.TEXT_COLUMN) + "')";
database.getWritableDatabase().execSQL(sql);
return uri;
}
public int deleteNoteForRecipe(Uri uri) {
String sql = "DELETE FROM `" + RecipeNoteTable.TABLE + "` WHERE `" + RecipeNoteTable
.RECIPE_ID_COLUMN + "` = '" + uri.getLastPathSegment() + "'";
database.getWritableDatabase().execSQL(sql);
return 1;
}
public int updateNoteForRecipe(Uri uri, ContentValues values) {
String sql = "UPDATE `" + RecipeNoteTable.TABLE + "` SET `" + RecipeNoteTable.TEXT_COLUMN
+ "` = '" + values.get(RecipeNoteTable.TEXT_COLUMN) + "' where `" +
RecipeNoteTable.RECIPE_ID_COLUMN + "` = '" + uri.getLastPathSegment() + "'";
database.getWritableDatabase().execSQL(sql);
return 1;
}
@Override
public String getType(Uri uri) {
return BASE_PATH;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
if (uriType == RECIPE_NOTES) {
return insertNoteForRecipe(uri, values);
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
if (uriType == RECIPE_NOTES) {
return deleteNoteForRecipe(uri);
}
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
if (uriType == RECIPE_NOTES) {
return updateNoteForRecipe(uri, values);
}
return 0;
}
/**
* This helper loads the SQLite database included with the app
* in the assets folder.
*/
public class RecipeDatabaseHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "recipes.db";
private static final int DATABASE_VERSION = 1;
public RecipeDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
}
| |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chromoting.cardboard;
import android.content.Intent;
import android.graphics.PointF;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import com.google.vrtoolkit.cardboard.CardboardActivity;
import com.google.vrtoolkit.cardboard.CardboardView;
import org.chromium.chromoting.InputStub;
import org.chromium.chromoting.R;
import org.chromium.chromoting.jni.Client;
import java.util.ArrayList;
/**
* Virtual desktop activity for Cardboard.
*/
public class DesktopActivity extends CardboardActivity {
// Flag to indicate whether the current activity is going to switch to normal
// desktop activity.
private boolean mSwitchToDesktopActivity;
private Client mClient;
private CardboardRenderer mRenderer;
private SpeechRecognizer mSpeechRecognizer;
// Flag to indicate whether the speech recognizer is listening or not.
private boolean mIsListening;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cardboard_desktop);
mClient = Client.getInstance();
mSwitchToDesktopActivity = false;
CardboardView cardboardView = (CardboardView) findViewById(R.id.cardboard_view);
// THE CODE BELOW IS BROKEN.
// To make it work, you have to somehow get the reference to the Display object and pass
// it into the constructor.
mRenderer = new CardboardRenderer(this, mClient, null);
mIsListening = false;
// Associate a CardboardView.StereoRenderer with cardboard view.
cardboardView.setRenderer(mRenderer);
// Associate the cardboard view with this activity.
setCardboardView(cardboardView);
}
@Override
public void onCardboardTrigger() {
if (mRenderer.isMenuBarVisible()) {
if (mRenderer.isLookingAtMenuBar()) {
switch (mRenderer.getMenuItem().getType()) {
case BACK:
mSwitchToDesktopActivity = true;
finish();
break;
case VOICE_INPUT:
listenForVoiceInput();
break;
case ZOOM_IN:
mRenderer.moveTowardsDesktop();
break;
case ZOOM_OUT:
mRenderer.moveAwayFromDesktop();
break;
}
} else {
mRenderer.setMenuBarVisible(false);
}
} else {
if (mRenderer.isLookingAtDesktop()) {
PointF coordinates = mRenderer.getMouseCoordinates();
mClient.sendMouseEvent((int) coordinates.x, (int) coordinates.y,
InputStub.BUTTON_LEFT, true);
mClient.sendMouseEvent((int) coordinates.x, (int) coordinates.y,
InputStub.BUTTON_LEFT, false);
} else {
if (mRenderer.isLookingFarawayFromDesktop()) {
getCardboardView().resetHeadTracker();
} else {
mRenderer.setMenuBarVisible(true);
}
}
}
}
@Override
protected void onStart() {
super.onStart();
mClient.enableVideoChannel(true);
}
@Override
protected void onPause() {
super.onPause();
if (!mSwitchToDesktopActivity) {
mClient.enableVideoChannel(false);
}
if (mSpeechRecognizer != null) {
mSpeechRecognizer.stopListening();
}
}
@Override
protected void onResume() {
super.onResume();
mClient.enableVideoChannel(true);
}
@Override
protected void onStop() {
super.onStop();
if (mSwitchToDesktopActivity) {
mSwitchToDesktopActivity = false;
} else {
mClient.enableVideoChannel(false);
}
if (mSpeechRecognizer != null) {
mSpeechRecognizer.stopListening();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mSpeechRecognizer != null) {
mSpeechRecognizer.cancel();
mSpeechRecognizer.destroy();
}
}
private void listenForVoiceInput() {
if (mIsListening) {
return;
}
if (mSpeechRecognizer == null) {
if (SpeechRecognizer.isRecognitionAvailable(this)) {
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new VoiceInputRecognitionListener());
} else {
return;
}
}
mIsListening = true;
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// LANGUAGE_MODEL_FREE_FORM is used to improve dictation accuracy
// for the voice keyboard.
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizer.startListening(intent);
}
private class VoiceInputRecognitionListener implements RecognitionListener {
public void onReadyForSpeech(Bundle params) {
}
public void onBeginningOfSpeech() {
}
public void onRmsChanged(float rmsdB){
}
public void onBufferReceived(byte[] buffer) {
}
public void onEndOfSpeech() {
mIsListening = false;
}
public void onError(int error) {
mIsListening = false;
}
public void onResults(Bundle results) {
// TODO(shichengfeng): If necessary, provide a list of choices for user to pick.
ArrayList<String> data =
results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (!data.isEmpty()) {
mClient.sendTextEvent(data.get(0));
}
}
public void onPartialResults(Bundle partialResults) {
}
public void onEvent(int eventType, Bundle params) {
}
}
}
| |
package com.itranswarp.recurring.subscription.service;
import com.itranswarp.recurring.account.model.Account;
import com.itranswarp.recurring.account.service.AccountService;
import com.itranswarp.recurring.base.util.BeanUtil;
import com.itranswarp.recurring.common.exception.APIArgumentException;
import com.itranswarp.recurring.db.Database;
import com.itranswarp.recurring.db.PagedResults;
import com.itranswarp.recurring.period.service.PeriodService;
import com.itranswarp.recurring.price.service.PriceService;
import com.itranswarp.recurring.product.model.ChargeData;
import com.itranswarp.recurring.subscription.dto.SubscriptionChargeDto;
import com.itranswarp.recurring.subscription.dto.SubscriptionDataDto;
import com.itranswarp.recurring.subscription.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import javax.inject.Named;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
@Named
public class SubscriptionService {
@Inject
Database database;
@Inject
PriceService priceService;
@Inject
PeriodService periodService;
@Inject
AccountService accountService;
@Transactional
public Subscription create(SubscriptionDataDto subscriptionDataDto) {
this.validSaveSubscriptionData(subscriptionDataDto);
Subscription subscription = new Subscription();
subscription.setSubscriptionDataId("");
subscription.setStatus(Subscription.SubscriptionStatus.DRAFT);
subscription.setAccountId("");
database.save(subscription);
SubscriptionData subscriptionData = createSubscriptionData(subscription, subscriptionDataDto);
subscription.setSubscriptionDataId(subscriptionData.getId());
subscription.setAccountId(subscriptionData.getAccountId());
database.update(subscription);
return subscription;
}
@Transactional
public Subscription update(String subscriptionId, SubscriptionDataDto subscriptionDataDto) {
this.validSaveSubscriptionData(subscriptionDataDto);
Subscription subscription = database.fetch(Subscription.class, subscriptionId);
SubscriptionData subscriptionData = createSubscriptionData(subscription, subscriptionDataDto);
subscription.setSubscriptionDataId(subscriptionData.getId());
subscription.setAccountId(subscriptionData.getAccountId());
database.update(subscription);
return subscription;
}
private SubscriptionData createSubscriptionData(Subscription subscription, SubscriptionDataDto subscriptionDataDto) {
SubscriptionData subscriptionData = subscriptionDataDto.getSubscriptionData();
subscriptionData.setSubscriptionId(subscription.getId());
subscriptionData.setPreviousId(StringUtils.trimToEmpty(subscription.getSubscriptionDataId()));
database.save(subscriptionData);
subscriptionDataDto.getSubscriptionChargeList().stream().forEach((SubscriptionChargeDto chargeDto) -> {
SubscriptionCharge subscriptionCharge = chargeDto.getSubscriptionCharge();
subscriptionCharge.setSubscriptionDataId(subscriptionData.getId());
database.save(subscriptionCharge);
ChargeData chargeData = database.fetch(ChargeData.class, subscriptionCharge.getChargeDataId());
chargeDto.getSubscriptionChargeSegmentList().stream().forEach((SubscriptionChargeSegment segment) -> {
segment.setSubscriptionChargeId(subscriptionCharge.getId());
segment.setChargeDataId(subscriptionCharge.getChargeDataId());
BeanUtils.copyProperties(chargeData, segment, BeanUtil.getNotNullPropertyNames(segment));
segment.setId(null);
database.save(segment);
});
});
return subscriptionData;
}
public Subscription read(String subscriptionId) {
Subscription subscription = database.fetch(Subscription.class, subscriptionId);
return subscription;
}
public SubscriptionDataDto readSubscriptionData(String subscriptionDataId) {
SubscriptionData subscriptionData = database.fetch(SubscriptionData.class, subscriptionDataId);
List<SubscriptionCharge> subscriptionChargeList = database.from(SubscriptionCharge.class).where(" subscriptionDataId = ? ", subscriptionDataId).list();
List<SubscriptionChargeDto> subscriptionChargeDtoList = subscriptionChargeList.stream().map((SubscriptionCharge subscriptionCharge) -> {
List<SubscriptionChargeSegment> chargeSegmentList = database.from(SubscriptionChargeSegment.class).where(" subscriptionChargeId = ? ", subscriptionCharge.getId()).list();
ChargeData chargeData = database.fetch(ChargeData.class, subscriptionCharge.getChargeDataId());
SubscriptionChargeDto chargeDto = new SubscriptionChargeDto().build(subscriptionCharge, chargeSegmentList, chargeData);
return chargeDto;
}).collect(Collectors.toList());
SubscriptionDataDto dto = new SubscriptionDataDto().build(subscriptionData, subscriptionChargeDtoList);
return dto;
}
@Transactional
public Subscription delete(String subscriptionId) {
Subscription subscription = database.fetch(Subscription.class, subscriptionId);
subscription.setStatus(Subscription.SubscriptionStatus.DELETE);
database.update(subscription);
return subscription;
}
private void validSaveSubscriptionData(SubscriptionDataDto subscriptionDataDto) {
LocalDate subscriptionStartDate = subscriptionDataDto.getSubscriptionData().getStartDate();
LocalDate subscriptionEndDate = subscriptionDataDto.getSubscriptionData().getEndDate();
if (subscriptionStartDate == null) {
throw new APIArgumentException("subscriptionData-startDate", "subscription's start date can not be null.");
}
if (subscriptionEndDate == null) {
throw new APIArgumentException("subscriptionData-endDate", "subscription's end date can not be null.");
}
if (StringUtils.isBlank(subscriptionDataDto.getSubscriptionData().getAccountId())) {
throw new APIArgumentException("subscriptionData-accountId", "subscription's account id can not be null.");
}
Account account = accountService.readAccount(subscriptionDataDto.getSubscriptionData().getAccountId());
if (account == null) {
throw new APIArgumentException("subscriptionData-accountId", "subscription's account not exist.");
} else if (StringUtils.equalsIgnoreCase(account.getStatus(), Account.AccountStatus.EXPIRED)) {
throw new APIArgumentException("subscriptionData-accountId", "subscription's account expired.");
}
subscriptionDataDto.getSubscriptionChargeList().stream().forEach((SubscriptionChargeDto subscriptionChargeDto) -> {
subscriptionChargeDto.getSubscriptionChargeSegmentList().stream().forEach((SubscriptionChargeSegment subscriptionChargeSegment) -> {
if (subscriptionChargeSegment.getStartDate() == null || subscriptionChargeSegment.getStartDate().isBefore(subscriptionStartDate)) {
throw new APIArgumentException("subscriptionChargeSegment-startDate", "subscription charge segment's start date can not be null or before subscription's start date.");
}
if (subscriptionChargeSegment.getEndDate() == null || subscriptionChargeSegment.getEndDate().isAfter(subscriptionEndDate)) {
throw new APIArgumentException("subscriptionChargeSegment-endDate", "subscription charge segment's end date can not be null or after subscription's end date.");
}
if ((null != subscriptionChargeSegment.getBillingType() && null == subscriptionChargeSegment.getBillingData())
|| (null == subscriptionChargeSegment.getBillingType() && null != subscriptionChargeSegment.getBillingData())
) {
throw new APIArgumentException("subscriptionChargeSegment-billingData", "subscription charge segment's billing type and billing data must be all null or all have value.");
}
if ((null == subscriptionChargeSegment.getPriceType() && null != subscriptionChargeSegment.getPriceData())
|| (null != subscriptionChargeSegment.getPriceType() && null == subscriptionChargeSegment.getPriceData())
) {
throw new APIArgumentException("subscriptionChargeSegment-priceData", "subscription charge segment's billing type and billing data must be all null or all have value.");
}
if (null != subscriptionChargeSegment.getBillingType() && null != subscriptionChargeSegment.getBillingData()) {
periodService.checkBillingData(subscriptionChargeSegment.getBillingType(), subscriptionChargeSegment.getBillingData());
}
if (null != subscriptionChargeSegment.getPriceType() && null != subscriptionChargeSegment.getPriceData()) {
priceService.checkPriceData(subscriptionChargeSegment.getPriceType(), subscriptionChargeSegment.getPriceData());
}
});
});
}
@Transactional
public void active(String subscriptionId) {
Subscription subscription = database.fetch(Subscription.class, subscriptionId);
subscription.setStatus(Subscription.SubscriptionStatus.ACTIVE);
database.update(subscription);
//send message
}
public PagedResults<Subscription> readSubscriptions(String status, Integer pageIndex, Integer itemsPerPage) {
PagedResults<Subscription> subscriptionList = null;
if (StringUtils.isEmpty(status)) {
subscriptionList = database.from(Subscription.class).list(pageIndex, itemsPerPage);
} else {
subscriptionList = database.from(Subscription.class).where("status=?", status).list(pageIndex, itemsPerPage);
}
return subscriptionList;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cassandra.db;
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.ExecutionException;
import org.apache.commons.lang3.StringUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.apache.cassandra.OrderedJUnit4ClassRunner;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.UpdateBuilder;
import org.apache.cassandra.Util;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.cql3.Operator;
import org.apache.cassandra.cql3.QueryProcessor;
import org.apache.cassandra.cql3.UntypedResultSet;
import org.apache.cassandra.db.compaction.CompactionManager;
import org.apache.cassandra.db.compaction.OperationType;
import org.apache.cassandra.db.compaction.Scrubber;
import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
import org.apache.cassandra.db.lifecycle.TransactionLogs;
import org.apache.cassandra.db.marshal.*;
import org.apache.cassandra.db.marshal.UUIDType;
import org.apache.cassandra.db.partitions.Partition;
import org.apache.cassandra.db.partitions.PartitionUpdate;
import org.apache.cassandra.dht.ByteOrderedPartitioner;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.RequestExecutionException;
import org.apache.cassandra.exceptions.WriteTimeoutException;
import org.apache.cassandra.io.compress.CompressionMetadata;
import org.apache.cassandra.io.sstable.*;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.utils.ByteBufferUtil;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
@RunWith(OrderedJUnit4ClassRunner.class)
public class ScrubTest
{
public static final String KEYSPACE = "Keyspace1";
public static final String CF = "Standard1";
public static final String CF2 = "Standard2";
public static final String CF3 = "Standard3";
public static final String COUNTER_CF = "Counter1";
public static final String CF_UUID = "UUIDKeys";
public static final String CF_INDEX1 = "Indexed1";
public static final String CF_INDEX2 = "Indexed2";
public static final String CF_INDEX1_BYTEORDERED = "Indexed1_ordered";
public static final String CF_INDEX2_BYTEORDERED = "Indexed2_ordered";
public static final String COL_INDEX = "birthdate";
public static final String COL_NON_INDEX = "notbirthdate";
public static final Integer COMPRESSION_CHUNK_LENGTH = 4096;
@BeforeClass
public static void defineSchema() throws ConfigurationException
{
SchemaLoader.loadSchema();
SchemaLoader.createKeyspace(KEYSPACE,
KeyspaceParams.simple(1),
SchemaLoader.standardCFMD(KEYSPACE, CF),
SchemaLoader.standardCFMD(KEYSPACE, CF2),
SchemaLoader.standardCFMD(KEYSPACE, CF3),
SchemaLoader.counterCFMD(KEYSPACE, COUNTER_CF)
.compression(SchemaLoader.getCompressionParameters(COMPRESSION_CHUNK_LENGTH)),
SchemaLoader.standardCFMD(KEYSPACE, CF_UUID, 0, UUIDType.instance),
SchemaLoader.keysIndexCFMD(KEYSPACE, CF_INDEX1, true),
SchemaLoader.compositeIndexCFMD(KEYSPACE, CF_INDEX2, true),
SchemaLoader.keysIndexCFMD(KEYSPACE, CF_INDEX1_BYTEORDERED, true).copy(ByteOrderedPartitioner.instance),
SchemaLoader.compositeIndexCFMD(KEYSPACE, CF_INDEX2_BYTEORDERED, true).copy(ByteOrderedPartitioner.instance));
}
@Test
public void testScrubOneRow() throws ExecutionException, InterruptedException
{
CompactionManager.instance.disableAutoCompaction();
Keyspace keyspace = Keyspace.open(KEYSPACE);
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF);
cfs.clearUnsafe();
// insert data and verify we get it back w/ range query
fillCF(cfs, 1);
assertOrderedAll(cfs, 1);
CompactionManager.instance.performScrub(cfs, false, true);
// check data is still there
assertOrderedAll(cfs, 1);
}
@Test
public void testScrubCorruptedCounterRow() throws IOException, WriteTimeoutException
{
// When compression is enabled, for testing corrupted chunks we need enough partitions to cover
// at least 3 chunks of size COMPRESSION_CHUNK_LENGTH
int numPartitions = 1000;
CompactionManager.instance.disableAutoCompaction();
Keyspace keyspace = Keyspace.open(KEYSPACE);
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(COUNTER_CF);
cfs.clearUnsafe();
fillCounterCF(cfs, numPartitions);
assertOrderedAll(cfs, numPartitions);
assertEquals(1, cfs.getLiveSSTables().size());
SSTableReader sstable = cfs.getLiveSSTables().iterator().next();
//make sure to override at most 1 chunk when compression is enabled
overrideWithGarbage(sstable, ByteBufferUtil.bytes("0"), ByteBufferUtil.bytes("1"));
// with skipCorrupted == false, the scrub is expected to fail
try (LifecycleTransaction txn = cfs.getTracker().tryModify(Arrays.asList(sstable), OperationType.SCRUB);
Scrubber scrubber = new Scrubber(cfs, txn, false, false, true))
{
scrubber.scrub();
fail("Expected a CorruptSSTableException to be thrown");
}
catch (IOError err) {}
// with skipCorrupted == true, the corrupt rows will be skipped
Scrubber.ScrubResult scrubResult;
try (LifecycleTransaction txn = cfs.getTracker().tryModify(Arrays.asList(sstable), OperationType.SCRUB);
Scrubber scrubber = new Scrubber(cfs, txn, true, false, true))
{
scrubResult = scrubber.scrubWithResult();
}
assertNotNull(scrubResult);
boolean compression = Boolean.parseBoolean(System.getProperty("cassandra.test.compression", "false"));
if (compression)
{
assertEquals(0, scrubResult.emptyRows);
assertEquals(numPartitions, scrubResult.badRows + scrubResult.goodRows);
//because we only corrupted 1 chunk and we chose enough partitions to cover at least 3 chunks
assertTrue(scrubResult.goodRows >= scrubResult.badRows * 2);
}
else
{
assertEquals(0, scrubResult.emptyRows);
assertEquals(1, scrubResult.badRows);
assertEquals(numPartitions-1, scrubResult.goodRows);
}
assertEquals(1, cfs.getLiveSSTables().size());
assertOrderedAll(cfs, scrubResult.goodRows);
}
@Test
public void testScrubCorruptedRowInSmallFile() throws IOException, WriteTimeoutException
{
// cannot test this with compression
assumeTrue(!Boolean.parseBoolean(System.getProperty("cassandra.test.compression", "false")));
CompactionManager.instance.disableAutoCompaction();
Keyspace keyspace = Keyspace.open(KEYSPACE);
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(COUNTER_CF);
cfs.clearUnsafe();
fillCounterCF(cfs, 2);
assertOrderedAll(cfs, 2);
SSTableReader sstable = cfs.getLiveSSTables().iterator().next();
// overwrite one row with garbage
overrideWithGarbage(sstable, ByteBufferUtil.bytes("0"), ByteBufferUtil.bytes("1"));
// with skipCorrupted == false, the scrub is expected to fail
try (LifecycleTransaction txn = cfs.getTracker().tryModify(Arrays.asList(sstable), OperationType.SCRUB);
Scrubber scrubber = new Scrubber(cfs, txn, false, false, true))
{
// with skipCorrupted == true, the corrupt row will be skipped
scrubber.scrub();
fail("Expected a CorruptSSTableException to be thrown");
}
catch (IOError err) {}
try (LifecycleTransaction txn = cfs.getTracker().tryModify(Arrays.asList(sstable), OperationType.SCRUB);
Scrubber scrubber = new Scrubber(cfs, txn, true, false, true))
{
// with skipCorrupted == true, the corrupt row will be skipped
scrubber.scrub();
scrubber.close();
}
assertEquals(1, cfs.getLiveSSTables().size());
// verify that we can read all of the rows, and there is now one less row
assertOrderedAll(cfs, 1);
}
@Test
public void testScrubOneRowWithCorruptedKey() throws IOException, ExecutionException, InterruptedException, ConfigurationException
{
// cannot test this with compression
assumeTrue(!Boolean.parseBoolean(System.getProperty("cassandra.test.compression", "false")));
CompactionManager.instance.disableAutoCompaction();
Keyspace keyspace = Keyspace.open(KEYSPACE);
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF);
cfs.clearUnsafe();
// insert data and verify we get it back w/ range query
fillCF(cfs, 4);
assertOrderedAll(cfs, 4);
SSTableReader sstable = cfs.getLiveSSTables().iterator().next();
overrideWithGarbage(sstable, 0, 2);
CompactionManager.instance.performScrub(cfs, false, true);
// check data is still there
assertOrderedAll(cfs, 4);
}
@Test
public void testScrubCorruptedCounterRowNoEarlyOpen() throws IOException, WriteTimeoutException
{
boolean oldDisabledVal = SSTableRewriter.disableEarlyOpeningForTests;
try
{
SSTableRewriter.disableEarlyOpeningForTests = true;
testScrubCorruptedCounterRow();
}
finally
{
SSTableRewriter.disableEarlyOpeningForTests = oldDisabledVal;
}
}
@Test
public void testScrubMultiRow() throws ExecutionException, InterruptedException
{
CompactionManager.instance.disableAutoCompaction();
Keyspace keyspace = Keyspace.open(KEYSPACE);
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF);
cfs.clearUnsafe();
// insert data and verify we get it back w/ range query
fillCF(cfs, 10);
assertOrderedAll(cfs, 10);
CompactionManager.instance.performScrub(cfs, false, true);
// check data is still there
assertOrderedAll(cfs, 10);
}
@Test
public void testScrubNoIndex() throws IOException, ExecutionException, InterruptedException, ConfigurationException
{
CompactionManager.instance.disableAutoCompaction();
Keyspace keyspace = Keyspace.open(KEYSPACE);
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF);
cfs.clearUnsafe();
// insert data and verify we get it back w/ range query
fillCF(cfs, 10);
assertOrderedAll(cfs, 10);
for (SSTableReader sstable : cfs.getLiveSSTables())
new File(sstable.descriptor.filenameFor(Component.PRIMARY_INDEX)).delete();
CompactionManager.instance.performScrub(cfs, false, true, true);
// check data is still there
assertOrderedAll(cfs, 10);
}
@Test
public void testScrubOutOfOrder() throws Exception
{
// This test assumes ByteOrderPartitioner to create out-of-order SSTable
IPartitioner oldPartitioner = DatabaseDescriptor.getPartitioner();
DatabaseDescriptor.setPartitionerUnsafe(new ByteOrderedPartitioner());
// Create out-of-order SSTable
File tempDir = File.createTempFile("ScrubTest.testScrubOutOfOrder", "").getParentFile();
// create ks/cf directory
File tempDataDir = new File(tempDir, String.join(File.separator, KEYSPACE, CF3));
tempDataDir.mkdirs();
try
{
CompactionManager.instance.disableAutoCompaction();
Keyspace keyspace = Keyspace.open(KEYSPACE);
String columnFamily = CF3;
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(columnFamily);
cfs.clearUnsafe();
List<String> keys = Arrays.asList("t", "a", "b", "z", "c", "y", "d");
String filename = cfs.getSSTablePath(tempDataDir);
Descriptor desc = Descriptor.fromFilename(filename);
try (SSTableTxnWriter writer = SSTableTxnWriter.create(desc,
keys.size(),
0L,
0,
SerializationHeader.make(cfs.metadata,
Collections.emptyList())))
{
for (String k : keys)
{
PartitionUpdate update = UpdateBuilder.create(cfs.metadata, Util.dk(k))
.newRow("someName").add("val", "someValue")
.build();
writer.append(update.unfilteredIterator());
}
writer.finish(false);
}
try
{
SSTableReader.open(desc, cfs.metadata);
fail("SSTR validation should have caught the out-of-order rows");
}
catch (IllegalStateException ise)
{ /* this is expected */ }
// open without validation for scrubbing
Set<Component> components = new HashSet<>();
if (new File(desc.filenameFor(Component.COMPRESSION_INFO)).exists())
components.add(Component.COMPRESSION_INFO);
components.add(Component.DATA);
components.add(Component.PRIMARY_INDEX);
components.add(Component.FILTER);
components.add(Component.STATS);
components.add(Component.SUMMARY);
components.add(Component.TOC);
SSTableReader sstable = SSTableReader.openNoValidation(desc, components, cfs);
if (sstable.last.compareTo(sstable.first) < 0)
sstable.last = sstable.first;
try (LifecycleTransaction txn = LifecycleTransaction.offline(OperationType.SCRUB, sstable);
Scrubber scrubber = new Scrubber(cfs, txn, false, true, true))
{
scrubber.scrub();
}
TransactionLogs.waitForDeletions();
cfs.loadNewSSTables();
assertOrderedAll(cfs, 7);
}
finally
{
FileUtils.deleteRecursive(tempDataDir);
// reset partitioner
DatabaseDescriptor.setPartitionerUnsafe(oldPartitioner);
}
}
private void overrideWithGarbage(SSTableReader sstable, ByteBuffer key1, ByteBuffer key2) throws IOException
{
boolean compression = Boolean.parseBoolean(System.getProperty("cassandra.test.compression", "false"));
long startPosition, endPosition;
if (compression)
{ // overwrite with garbage the compression chunks from key1 to key2
CompressionMetadata compData = CompressionMetadata.create(sstable.getFilename());
CompressionMetadata.Chunk chunk1 = compData.chunkFor(
sstable.getPosition(PartitionPosition.ForKey.get(key1, sstable.getPartitioner()), SSTableReader.Operator.EQ).position);
CompressionMetadata.Chunk chunk2 = compData.chunkFor(
sstable.getPosition(PartitionPosition.ForKey.get(key2, sstable.getPartitioner()), SSTableReader.Operator.EQ).position);
startPosition = Math.min(chunk1.offset, chunk2.offset);
endPosition = Math.max(chunk1.offset + chunk1.length, chunk2.offset + chunk2.length);
compData.close();
}
else
{ // overwrite with garbage from key1 to key2
long row0Start = sstable.getPosition(PartitionPosition.ForKey.get(key1, sstable.getPartitioner()), SSTableReader.Operator.EQ).position;
long row1Start = sstable.getPosition(PartitionPosition.ForKey.get(key2, sstable.getPartitioner()), SSTableReader.Operator.EQ).position;
startPosition = Math.min(row0Start, row1Start);
endPosition = Math.max(row0Start, row1Start);
}
overrideWithGarbage(sstable, startPosition, endPosition);
}
private void overrideWithGarbage(SSTableReader sstable, long startPosition, long endPosition) throws IOException
{
RandomAccessFile file = new RandomAccessFile(sstable.getFilename(), "rw");
file.seek(startPosition);
file.writeBytes(StringUtils.repeat('z', (int) (endPosition - startPosition)));
file.close();
}
private static void assertOrderedAll(ColumnFamilyStore cfs, int expectedSize)
{
assertOrdered(Util.cmd(cfs).build(), expectedSize);
}
private static void assertOrdered(ReadCommand cmd, int expectedSize)
{
int size = 0;
DecoratedKey prev = null;
for (Partition partition : Util.getAllUnfiltered(cmd))
{
DecoratedKey current = partition.partitionKey();
assertTrue("key " + current + " does not sort after previous key " + prev, prev == null || prev.compareTo(current) < 0);
prev = current;
++size;
}
assertEquals(expectedSize, size);
}
protected void fillCF(ColumnFamilyStore cfs, int partitionsPerSSTable)
{
for (int i = 0; i < partitionsPerSSTable; i++)
{
PartitionUpdate update = UpdateBuilder.create(cfs.metadata, String.valueOf(i))
.newRow("r1").add("val", "1")
.newRow("r1").add("val", "1")
.build();
new Mutation(update).applyUnsafe();
}
cfs.forceBlockingFlush();
}
public static void fillIndexCF(ColumnFamilyStore cfs, boolean composite, long ... values)
{
assertTrue(values.length % 2 == 0);
for (int i = 0; i < values.length; i +=2)
{
UpdateBuilder builder = UpdateBuilder.create(cfs.metadata, String.valueOf(i));
if (composite)
{
builder.newRow("c" + i)
.add(COL_INDEX, values[i])
.add(COL_NON_INDEX, values[i + 1]);
}
else
{
builder.newRow()
.add(COL_INDEX, values[i])
.add(COL_NON_INDEX, values[i + 1]);
}
new Mutation(builder.build()).applyUnsafe();
}
cfs.forceBlockingFlush();
}
protected void fillCounterCF(ColumnFamilyStore cfs, int partitionsPerSSTable) throws WriteTimeoutException
{
for (int i = 0; i < partitionsPerSSTable; i++)
{
PartitionUpdate update = UpdateBuilder.create(cfs.metadata, String.valueOf(i))
.newRow("r1").add("val", 100L)
.build();
new CounterMutation(new Mutation(update), ConsistencyLevel.ONE).apply();
}
cfs.forceBlockingFlush();
}
@Test
public void testScrubColumnValidation() throws InterruptedException, RequestExecutionException, ExecutionException
{
QueryProcessor.process(String.format("CREATE TABLE \"%s\".test_compact_static_columns (a bigint, b timeuuid, c boolean static, d text, PRIMARY KEY (a, b))", KEYSPACE), ConsistencyLevel.ONE);
Keyspace keyspace = Keyspace.open(KEYSPACE);
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("test_compact_static_columns");
QueryProcessor.executeInternal(String.format("INSERT INTO \"%s\".test_compact_static_columns (a, b, c, d) VALUES (123, c3db07e8-b602-11e3-bc6b-e0b9a54a6d93, true, 'foobar')", KEYSPACE));
cfs.forceBlockingFlush();
CompactionManager.instance.performScrub(cfs, false, true);
QueryProcessor.process("CREATE TABLE \"Keyspace1\".test_scrub_validation (a text primary key, b int)", ConsistencyLevel.ONE);
ColumnFamilyStore cfs2 = keyspace.getColumnFamilyStore("test_scrub_validation");
new Mutation(UpdateBuilder.create(cfs2.metadata, "key").newRow().add("b", LongType.instance.decompose(1L)).build()).apply();
cfs2.forceBlockingFlush();
CompactionManager.instance.performScrub(cfs2, false, false);
}
/**
* For CASSANDRA-6892 too, check that for a compact table with one cluster column, we can insert whatever
* we want as value for the clustering column, including something that would conflict with a CQL column definition.
*/
@Test
public void testValidationCompactStorage() throws Exception
{
QueryProcessor.process(String.format("CREATE TABLE \"%s\".test_compact_dynamic_columns (a int, b text, c text, PRIMARY KEY (a, b)) WITH COMPACT STORAGE", KEYSPACE), ConsistencyLevel.ONE);
Keyspace keyspace = Keyspace.open(KEYSPACE);
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("test_compact_dynamic_columns");
QueryProcessor.executeInternal(String.format("INSERT INTO \"%s\".test_compact_dynamic_columns (a, b, c) VALUES (0, 'a', 'foo')", KEYSPACE));
QueryProcessor.executeInternal(String.format("INSERT INTO \"%s\".test_compact_dynamic_columns (a, b, c) VALUES (0, 'b', 'bar')", KEYSPACE));
QueryProcessor.executeInternal(String.format("INSERT INTO \"%s\".test_compact_dynamic_columns (a, b, c) VALUES (0, 'c', 'boo')", KEYSPACE));
cfs.forceBlockingFlush();
CompactionManager.instance.performScrub(cfs, true, true);
// Scrub is silent, but it will remove broken records. So reading everything back to make sure nothing to "scrubbed away"
UntypedResultSet rs = QueryProcessor.executeInternal(String.format("SELECT * FROM \"%s\".test_compact_dynamic_columns", KEYSPACE));
assertEquals(3, rs.size());
Iterator<UntypedResultSet.Row> iter = rs.iterator();
assertEquals("foo", iter.next().getString("c"));
assertEquals("bar", iter.next().getString("c"));
assertEquals("boo", iter.next().getString("c"));
}
@Test /* CASSANDRA-5174 */
public void testScrubKeysIndex_preserveOrder() throws IOException, ExecutionException, InterruptedException
{
//If the partitioner preserves the order then SecondaryIndex uses BytesType comparator,
// otherwise it uses LocalByPartitionerType
testScrubIndex(CF_INDEX1_BYTEORDERED, COL_INDEX, false, true);
}
@Test /* CASSANDRA-5174 */
public void testScrubCompositeIndex_preserveOrder() throws IOException, ExecutionException, InterruptedException
{
testScrubIndex(CF_INDEX2_BYTEORDERED, COL_INDEX, true, true);
}
@Test /* CASSANDRA-5174 */
public void testScrubKeysIndex() throws IOException, ExecutionException, InterruptedException
{
testScrubIndex(CF_INDEX1, COL_INDEX, false, true);
}
@Test /* CASSANDRA-5174 */
public void testScrubCompositeIndex() throws IOException, ExecutionException, InterruptedException
{
testScrubIndex(CF_INDEX2, COL_INDEX, true, true);
}
@Test /* CASSANDRA-5174 */
public void testFailScrubKeysIndex() throws IOException, ExecutionException, InterruptedException
{
testScrubIndex(CF_INDEX1, COL_INDEX, false, false);
}
@Test /* CASSANDRA-5174 */
public void testFailScrubCompositeIndex() throws IOException, ExecutionException, InterruptedException
{
testScrubIndex(CF_INDEX2, COL_INDEX, true, false);
}
@Test /* CASSANDRA-5174 */
public void testScrubTwice() throws IOException, ExecutionException, InterruptedException
{
testScrubIndex(CF_INDEX1, COL_INDEX, false, true, true);
}
private void testScrubIndex(String cfName, String colName, boolean composite, boolean ... scrubs)
throws IOException, ExecutionException, InterruptedException
{
CompactionManager.instance.disableAutoCompaction();
Keyspace keyspace = Keyspace.open(KEYSPACE);
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName);
cfs.clearUnsafe();
int numRows = 1000;
long[] colValues = new long [numRows * 2]; // each row has two columns
for (int i = 0; i < colValues.length; i+=2)
{
colValues[i] = (i % 4 == 0 ? 1L : 2L); // index column
colValues[i+1] = 3L; //other column
}
fillIndexCF(cfs, composite, colValues);
// check index
assertOrdered(Util.cmd(cfs).filterOn(colName, Operator.EQ, 1L).build(), numRows / 2);
// scrub index
Set<ColumnFamilyStore> indexCfss = cfs.indexManager.getIndexesBackedByCfs();
assertTrue(indexCfss.size() == 1);
for(ColumnFamilyStore indexCfs : indexCfss)
{
for (int i = 0; i < scrubs.length; i++)
{
boolean failure = !scrubs[i];
if (failure)
{ //make sure the next scrub fails
overrideWithGarbage(indexCfs.getLiveSSTables().iterator().next(), ByteBufferUtil.bytes(1L), ByteBufferUtil.bytes(2L));
}
CompactionManager.AllSSTableOpStatus result = indexCfs.scrub(false, false, true, true);
assertEquals(failure ?
CompactionManager.AllSSTableOpStatus.ABORTED :
CompactionManager.AllSSTableOpStatus.SUCCESSFUL,
result);
}
}
// check index is still working
assertOrdered(Util.cmd(cfs).filterOn(colName, Operator.EQ, 1L).build(), numRows / 2);
}
}
| |
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2015 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.recurly.model;
import com.google.common.base.Objects;
import org.joda.time.DateTime;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlList;
import java.math.BigDecimal;
import java.util.List;
@XmlRootElement(name = "adjustment")
public class Adjustment extends RecurlyObject {
@XmlElement(name = "account")
private Account account;
@XmlElement(name = "bill_for_account")
private Account billForAccount;
@XmlElement(name = "subscription")
private Subscription subscription;
@XmlElement(name = "uuid")
private String uuid;
@XmlElement(name = "type")
private String type;
@XmlElement(name = "description")
private String description;
@XmlElement(name = "accounting_code")
private String accountingCode;
@XmlElement(name = "origin")
private String origin;
@XmlElement(name = "unit_amount_in_cents")
private Integer unitAmountInCents;
@XmlElement(name = "quantity")
private Integer quantity;
@XmlElement(name = "discount_in_cents")
private Integer discountInCents;
@XmlElement(name = "tax_in_cents")
private Integer taxInCents;
@XmlElement(name = "total_in_cents")
private Integer totalInCents;
@XmlElement(name = "currency")
private String currency;
@XmlElement(name = "taxable")
private Boolean taxable;
@XmlElement(name = "tax_type")
private String taxType;
@XmlElement(name = "tax_region")
private String taxRegion;
@XmlElement(name = "tax_rate")
private String taxRate;
@XmlElement(name = "tax_code")
private String taxCode;
@XmlElement(name = "tax_exempt")
private Boolean taxExempt;
@XmlList
@XmlElementWrapper(name = "tax_details")
private List<TaxDetail> taxDetails;
@XmlElement(name = "product_code")
private String productCode;
@XmlElement(name = "item_code")
private String itemCode;
@XmlElement(name = "external_sku")
private String externalSku;
@XmlElement(name = "start_date")
private DateTime startDate;
@XmlElement(name = "end_date")
private DateTime endDate;
@XmlElement(name = "created_at")
private DateTime createdAt;
@XmlElement(name = "updated_at")
private DateTime updatedAt;
@XmlElement(name = "revenue_schedule_type")
private RevenueScheduleType revenueScheduleType;
@XmlElement(name = "credit_reason_code")
private String creditReasonCode;
@XmlElement(name = "original_adjustment_uuid")
private String originalAdjustmentUuid;
@XmlElement(name = "shipping_address")
private ShippingAddress shippingAddress;
@XmlElement(name = "shipping_address_id")
private Long shippingAddressId;
@XmlElement(name = "refundable_total_in_cents")
private Integer refundableTotalInCents;
@XmlElement(name = "state")
private String state;
@XmlElement(name = "proration_rate")
private BigDecimal prorationRate;
@XmlElement(name = "surcharge_in_cents")
private Integer surchargeInCents;
public Account getAccount() {
if (account != null && account.getCreatedAt() == null) {
account = fetch(account, Account.class);
}
return account;
}
public void setAccount(final Account account) {
this.account = account;
}
public Account getBillForAccount() {
if (billForAccount != null && billForAccount.getCreatedAt() == null) {
billForAccount = fetch(billForAccount, Account.class);
}
return billForAccount;
}
public void setBillForAccount(final Account billForAccount) {
this.billForAccount = billForAccount;
}
public String getSubscriptionId() {
if (subscription != null && subscription.getHref() != null) {
String[] parts = subscription.getHref().split("/");
return parts[parts.length - 1];
}
return null;
}
public void setSubscription(final Subscription subscription) {
this.subscription = subscription;
}
public String getUuid() {
return uuid;
}
public void setUuid(final Object uuid) {
this.uuid = stringOrNull(uuid);
}
public String getType() {
return type;
}
public void setType(final Object type) {
this.type = stringOrNull(type);
}
public String getDescription() {
return description;
}
public void setDescription(final Object description) {
this.description = stringOrNull(description);
}
public String getAccountingCode() {
return accountingCode;
}
public void setAccountingCode(final Object accountingCode) {
this.accountingCode = stringOrNull(accountingCode);
}
public String getOrigin() {
return origin;
}
public void setOrigin(final Object origin) {
this.origin = stringOrNull(origin);
}
public Integer getUnitAmountInCents() {
return unitAmountInCents;
}
public void setUnitAmountInCents(final Object unitAmountInCents) {
this.unitAmountInCents = integerOrNull(unitAmountInCents);
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(final Object quantity) {
this.quantity = integerOrNull(quantity);
}
public Integer getDiscountInCents() {
return discountInCents;
}
public void setDiscountInCents(final Object discountInCents) {
this.discountInCents = integerOrNull(discountInCents);
}
public Integer getTaxInCents() {
return taxInCents;
}
public void setTaxInCents(final Object taxInCents) {
this.taxInCents = integerOrNull(taxInCents);
}
public Integer getTotalInCents() {
return totalInCents;
}
public void setTotalInCents(final Object totalInCents) {
this.totalInCents = integerOrNull(totalInCents);
}
public String getCurrency() {
return currency;
}
public void setCurrency(final Object currency) {
this.currency = stringOrNull(currency);
}
public Boolean getTaxable() {
return taxable;
}
public void setTaxable(final Object taxable) {
this.taxable = booleanOrNull(taxable);
}
public String getTaxType() {
return taxType;
}
public void setTaxType(final Object taxType) {
this.taxType = stringOrNull(taxType);
}
public String getTaxRegion() {
return taxRegion;
}
public void setTaxRegion(final Object taxRegion) {
this.taxRegion = stringOrNull(taxRegion);
}
public String getTaxRate() {
return taxRate;
}
public void setTaxRate(final Object taxRate) {
this.taxRate = stringOrNull(taxRate);
}
public String getTaxCode() {
return taxCode;
}
public void setTaxCode(final Object taxCode) {
this.taxCode = stringOrNull(taxCode);
}
public Boolean getTaxExempt() {
return taxExempt;
}
public void setTaxExempt(final Object taxExempt) {
this.taxExempt = booleanOrNull(taxExempt);
}
public List<TaxDetail> getTaxDetails() {
return taxDetails;
}
public void setTaxDetails(final List<TaxDetail> taxDetails) {
this.taxDetails = taxDetails;
}
public String getProductCode() { return productCode; }
public void setProductCode(final Object productCode) { this.productCode = stringOrNull(productCode); }
public String getItemCode() { return itemCode; }
public void setItemCode(final Object itemCode) { this.itemCode = stringOrNull(itemCode); }
public String getExternalSku() { return externalSku; }
public void setExternalSku(final Object externalSku) { this.externalSku = stringOrNull(externalSku); }
public DateTime getStartDate() {
return startDate;
}
public void setStartDate(final Object startDate) {
this.startDate = dateTimeOrNull(startDate);
}
public DateTime getEndDate() {
return endDate;
}
public void setEndDate(final Object endDate) {
this.endDate = dateTimeOrNull(endDate);
}
public DateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(final Object createdAt) {
this.createdAt = dateTimeOrNull(createdAt);
}
public DateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(final Object updatedAt) {
this.updatedAt = dateTimeOrNull(updatedAt);
}
public AdjustmentRefund toAdjustmentRefund() {
final AdjustmentRefund adjustmentRefund = new AdjustmentRefund();
adjustmentRefund.setUuid(uuid);
adjustmentRefund.setQuantity(quantity);
adjustmentRefund.setProrate(false);
return adjustmentRefund;
}
public RevenueScheduleType getRevenueScheduleType() {
return revenueScheduleType;
}
public void setRevenueScheduleType(final Object revenueScheduleType) {
this.revenueScheduleType = enumOrNull(RevenueScheduleType.class, revenueScheduleType, true);
}
public String getCreditReasonCode() {
return creditReasonCode;
}
public void setCreditReasonCode(final Object creditReasonCode) {
this.creditReasonCode = stringOrNull(creditReasonCode);
}
public String getOriginalAdjustmentUuid() {
return originalAdjustmentUuid;
}
public void setOriginalAdjustmentUuid(final Object originalAdjustmentUuid) {
this.originalAdjustmentUuid = stringOrNull(originalAdjustmentUuid);
}
public ShippingAddress getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(final ShippingAddress shippingAddress) {
this.shippingAddress = shippingAddress;
}
public Long getShippingAddressId() {
return shippingAddressId;
}
public void setShippingAddressId(final Object shippingAddressId) {
this.shippingAddressId = longOrNull(shippingAddressId);
}
public Integer getRefundableTotalInCents() {
return refundableTotalInCents;
}
public void setRefundableTotalInCents(final Object refundableTotalInCents) {
this.refundableTotalInCents = integerOrNull(refundableTotalInCents);
}
public String getState() {
return state;
}
public void setState(final Object state) {
this.state = stringOrNull(state);
}
public BigDecimal getProrationRate() {
return prorationRate;
}
public void setProrationRate(final Object prorationRate) {
this.prorationRate = bigDecimalOrNull(prorationRate);
}
public Integer getSurchargeInCents() {
return surchargeInCents;
}
public void setSurchargeInCents(final Object surchargeInCents) {
this.surchargeInCents = integerOrNull(surchargeInCents);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Adjustment");
sb.append("{account=").append(account);
sb.append(", billForAccount=").append(billForAccount);
sb.append(", uuid='").append(uuid).append('\'');
sb.append(", type=").append(type);
sb.append(", description='").append(description).append('\'');
sb.append(", accountingCode='").append(accountingCode).append('\'');
sb.append(", origin='").append(origin).append('\'');
sb.append(", unitAmountInCents=").append(unitAmountInCents);
sb.append(", quantity=").append(quantity);
sb.append(", discountInCents=").append(discountInCents);
sb.append(", taxInCents=").append(taxInCents);
sb.append(", taxType=").append(taxType);
sb.append(", taxRegion=").append(taxRegion);
sb.append(", taxRate=").append(taxRate);
sb.append(", taxCode=").append(taxCode);
sb.append(", taxExempt=").append(taxExempt);
sb.append(", taxDetails=").append(taxDetails);
sb.append(", totalInCents=").append(totalInCents);
sb.append(", currency='").append(currency).append('\'');
sb.append(", taxable=").append(taxable);
sb.append(", productCode=").append(productCode);
sb.append(", itemCode=").append(itemCode);
sb.append(", externalSku=").append(externalSku);
sb.append(", startDate=").append(startDate);
sb.append(", endDate=").append(endDate);
sb.append(", createdAt=").append(createdAt);
sb.append(", updatedAt=").append(updatedAt);
sb.append(", revenueScheduleType=").append(revenueScheduleType);
sb.append(", creditReasonCode=").append(creditReasonCode);
sb.append(", originalAdjustmentUuid=").append(originalAdjustmentUuid);
sb.append(", shippingAddress=").append(shippingAddress);
sb.append(", shippingAddressId=").append(shippingAddressId);
sb.append(", refundableTotalInCents=").append(refundableTotalInCents);
sb.append(", state=").append(state);
sb.append(", prorationRate=").append(prorationRate);
sb.append(", surchargeInCents=").append(surchargeInCents);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Adjustment that = (Adjustment) o;
if (account != null ? !account.equals(that.account) : that.account != null) {
return false;
}
if (billForAccount != null ? !billForAccount.equals(that.billForAccount) : that.billForAccount != null) {
return false;
}
if (accountingCode != null ? !accountingCode.equals(that.accountingCode) : that.accountingCode != null) {
return false;
}
if (createdAt != null ? createdAt.compareTo(that.createdAt) != 0 : that.createdAt != null) {
return false;
}
if (currency != null ? !currency.equals(that.currency) : that.currency != null) {
return false;
}
if (creditReasonCode != null ? !creditReasonCode.equals(that.creditReasonCode) : that.creditReasonCode != null) {
return false;
}
if (description != null ? !description.equals(that.description) : that.description != null) {
return false;
}
if (discountInCents != null ? !discountInCents.equals(that.discountInCents) : that.discountInCents != null) {
return false;
}
if (endDate != null ? !endDate.equals(that.endDate) : that.endDate != null) {
return false;
}
if (origin != null ? !origin.equals(that.origin) : that.origin != null) {
return false;
}
if (originalAdjustmentUuid != null ? !originalAdjustmentUuid.equals(that.originalAdjustmentUuid) : that.originalAdjustmentUuid != null) {
return false;
}
if (productCode != null ? !productCode.equals(that.productCode) : that.productCode != null) {
return false;
}
if (itemCode != null ? !itemCode.equals(that.itemCode) : that.itemCode != null) {
return false;
}
if (externalSku != null ? !externalSku.equals(that.externalSku) : that.externalSku != null) {
return false;
}
if (quantity != null ? !quantity.equals(that.quantity) : that.quantity != null) {
return false;
}
if (shippingAddress != null ? !shippingAddress.equals(that.shippingAddress) : that.shippingAddress != null) {
return false;
}
if (shippingAddressId != null ? !shippingAddressId.equals(that.shippingAddressId) : that.shippingAddressId != null) {
return false;
}
if (startDate != null ? !startDate.equals(that.startDate) : that.startDate != null) {
return false;
}
if (surchargeInCents != null ? !surchargeInCents.equals(that.surchargeInCents) : that.surchargeInCents != null) {
return false;
}
if (taxInCents != null ? !taxInCents.equals(that.taxInCents) : that.taxInCents != null) {
return false;
}
if (taxable != null ? !taxable.equals(that.taxable) : that.taxable != null) {
return false;
}
if (type != null ? !type.equals(that.type) : that.type != null) {
return false;
}
if (taxType != null ? !taxType.equals(that.taxType) : that.taxType != null) {
return false;
}
if (taxRegion != null ? !taxRegion.equals(that.taxRegion) : that.taxRegion != null) {
return false;
}
if (taxRate != null ? !taxRate.equals(that.taxRate) : that.taxRate != null) {
return false;
}
if (taxCode != null ? !taxCode.equals(that.taxCode) : that.taxCode != null) {
return false;
}
if (taxExempt != null ? !taxExempt.equals(that.taxExempt) : that.taxExempt != null) {
return false;
}
if (taxDetails != null ? !taxDetails.equals(that.taxDetails) : that.taxDetails != null) {
return false;
}
if (totalInCents != null ? !totalInCents.equals(that.totalInCents) : that.totalInCents != null) {
return false;
}
if (unitAmountInCents != null ? !unitAmountInCents.equals(that.unitAmountInCents) : that.unitAmountInCents != null) {
return false;
}
if (uuid != null ? !uuid.equals(that.uuid) : that.uuid != null) {
return false;
}
if (updatedAt != null ? updatedAt.compareTo(that.updatedAt) != 0 : that.updatedAt != null) {
return false;
}
if (revenueScheduleType != null ? !revenueScheduleType.equals(that.revenueScheduleType) : that.revenueScheduleType != null) {
return false;
}
if (refundableTotalInCents != null ? !refundableTotalInCents.equals(that.refundableTotalInCents) : that.refundableTotalInCents != null) {
return false;
}
if (state != null ? !state.equals(that.state) : that.state != null) {
return false;
}
if (prorationRate != null ? !prorationRate.equals(that.prorationRate) : that.prorationRate != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(
account,
billForAccount,
uuid,
type,
description,
accountingCode,
origin,
unitAmountInCents,
quantity,
productCode,
itemCode,
externalSku,
discountInCents,
taxInCents,
totalInCents,
currency,
taxable,
taxType,
taxRegion,
taxRate,
taxCode,
taxExempt,
taxDetails,
startDate,
endDate,
createdAt,
updatedAt,
revenueScheduleType,
creditReasonCode,
originalAdjustmentUuid,
shippingAddress,
shippingAddressId,
refundableTotalInCents,
state,
prorationRate,
surchargeInCents
);
}
}
| |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.spider.parser;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.FormControl;
import net.htmlparser.jericho.FormControlType;
import net.htmlparser.jericho.FormField;
import net.htmlparser.jericho.FormFields;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import org.parosproxy.paros.network.HtmlParameter;
import org.parosproxy.paros.network.HtmlParameter.Type;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.spider.SpiderParam;
import org.zaproxy.zap.spider.URLCanonicalizer;
/**
* The Class SpiderHtmlFormParser is used for parsing HTML files for processing forms.
*/
public class SpiderHtmlFormParser extends SpiderParser {
private static final String ENCODING_TYPE = "UTF-8";
private static final String DEFAULT_NUMBER_VALUE = "1";
private static final String DEFAULT_FILE_VALUE = "test_file.txt";
private static final String DEFAULT_TEXT_VALUE = org.parosproxy.paros.Constant.PROGRAM_NAME_SHORT;
private static final String METHOD_POST = "POST";
private static final String ATTR_TYPE = "type";
private static final String DEFAULT_EMPTY_VALUE = "";
private static final String DEFAULT_PASS_VALUE = DEFAULT_TEXT_VALUE;
/** The spider parameters. */
private final SpiderParam param;
/**
* The default {@code Date} to be used for default values of date fields.
* <p>
* Default is {@code null}.
*
* @see #setDefaultDate(Date)
*/
private Date defaultDate;
/**
* Instantiates a new spider html form parser.
*
* @param param the parameters for the spider
* @throws IllegalArgumentException if {@code param} is null.
*/
public SpiderHtmlFormParser(SpiderParam param) {
super();
if (param == null) {
throw new IllegalArgumentException("Parameter param must not be null.");
}
this.param = param;
}
@Override
public boolean parseResource(HttpMessage message, Source source, int depth) {
log.debug("Parsing an HTML message for forms...");
// If form processing is disabled, don't parse anything
if (!param.isProcessForm()) {
return false;
}
// Prepare the source, if not provided
if (source == null) {
source = new Source(message.getResponseBody().toString());
}
// Get the context (base url)
String baseURL = message.getRequestHeader().getURI().toString();
// Try to see if there's any BASE tag that could change the base URL
Element base = source.getFirstElement(HTMLElementName.BASE);
if (base != null) {
if (log.isDebugEnabled()) {
log.debug("Base tag was found in HTML: " + base.getDebugInfo());
}
String href = base.getAttributeValue("href");
if (href != null && !href.isEmpty()) {
baseURL = href;
}
}
// Go through the forms
List<Element> forms = source.getAllElements(HTMLElementName.FORM);
for (Element form : forms) {
// Get method and action
String method = form.getAttributeValue("method");
String action = form.getAttributeValue("action");
log.debug("Found new form with method: '" + method + "' and action: " + action);
// If no action, skip the form
if (action == null) {
log.debug("No form 'action' defined. Using base URL: " + baseURL);
action = baseURL;
}
// If POSTing forms is not enabled, skip processing of forms with POST method
if (!param.isPostForm() && method != null && method.trim().equalsIgnoreCase(METHOD_POST)) {
log.debug("Skipping form with POST method because of user settings.");
continue;
}
// Clear the fragment, if any, as it does not have any relevance for the server
if (action.contains("#")) {
int fs = action.lastIndexOf("#");
action = action.substring(0, fs);
}
FormData formData = prepareFormDataSet(form.getFormFields());
// Process the case of a POST method
if (method != null && method.trim().equalsIgnoreCase(METHOD_POST)) {
// Build the absolute canonical URL
String fullURL = URLCanonicalizer.getCanonicalURL(action, baseURL);
if (fullURL == null) {
return false;
}
log.debug("Canonical URL constructed using '" + action + "': " + fullURL);
/*
* Ignore encoding, as we will not POST files anyway, so using
* "application/x-www-form-urlencoded" is adequate
*/
// String encoding = form.getAttributeValue("enctype");
// if (encoding != null && encoding.equals("multipart/form-data"))
String baseRequestBody = buildEncodedUrlQuery(formData.getFields());
if (formData.getSubmitFields().isEmpty()) {
notifyPostResourceFound(message, depth, fullURL, baseRequestBody);
continue;
}
for (HtmlParameter submitField : formData.getSubmitFields()) {
notifyPostResourceFound(
message,
depth,
fullURL,
appendEncodedUrlQueryParameter(baseRequestBody, submitField));
}
} // Process anything else as a GET method
else {
// Process the final URL
if (action.contains("?")) {
if (action.endsWith("?")) {
processGetForm(message, depth, action, baseURL, formData);
} else {
processGetForm(message, depth, action + "&", baseURL, formData);
}
} else {
processGetForm(message, depth, action + "?", baseURL, formData);
}
}
}
return false;
}
/**
* Processes the given GET form data into, possibly, several URLs.
* <p>
* For each submit field present in the form data is processed one URL, which includes remaining normal fields.
*
* @param message the source message
* @param depth the current depth
* @param action the action
* @param baseURL the base URL
* @param formData the GET form data
* @see #processURL(HttpMessage, int, String, String)
*/
private void processGetForm(HttpMessage message, int depth, String action, String baseURL, FormData formData) {
String baseQuery = buildEncodedUrlQuery(formData.getFields());
if (formData.getSubmitFields().isEmpty()) {
log.debug("Submiting form with GET method and query with form parameters: " + baseQuery);
processURL(message, depth, action + baseQuery, baseURL);
} else {
for (HtmlParameter submitField : formData.getSubmitFields()) {
String query = appendEncodedUrlQueryParameter(baseQuery, submitField);
log.debug("Submiting form with GET method and query with form parameters: " + query);
processURL(message, depth, action + query, baseURL);
}
}
}
/**
* Prepares the form data set. A form data set is a sequence of control-name/current-value pairs
* constructed from successful controls, which will be sent with a GET/POST request for a form.
*
* @see <a href="https://www.w3.org/TR/REC-html40/interact/forms.html#form-data-set">HTML 4.01 Specification - 17.13.3
* Processing form data</a>
* @see <a href="https://html.spec.whatwg.org/multipage/forms.html#association-of-controls-and-forms">HTML 5 - 4.10.18.3
* Association of controls and forms</a>
* @param form the form
* @return the list
*/
private FormData prepareFormDataSet(FormFields form) {
List<HtmlParameter> formDataSet = new LinkedList<>();
List<HtmlParameter> submitFields = new ArrayList<>();
// Process each form field
Iterator<FormField> it = form.iterator();
while (it.hasNext()) {
FormField field = it.next();
if (log.isDebugEnabled()) {
log.debug("New form field: " + field.getDebugInfo());
}
List<HtmlParameter> currentList = formDataSet;
if (field.getFormControl().getFormControlType().isSubmit()) {
currentList = submitFields;
}
for (String value : getValues(field)) {
currentList.add(new HtmlParameter(Type.form, field.getName(), value));
}
}
return new FormData(formDataSet, submitFields);
}
/**
* Gets the values for the given {@code field}.
* <p>
* If the field is of submit type it returns its predefined values.
*
* @param field the field
* @return a list with the values
* @see #getDefaultTextValue(FormField)
*/
private List<String> getValues(FormField field) {
if (field.getFormControl().getFormControlType().isSubmit()) {
return new ArrayList<>(field.getPredefinedValues());
}
// Get its value(s)
List<String> values = field.getValues();
if (log.isDebugEnabled()) {
log.debug("Existing values: " + values);
}
// If there are no values at all or only an empty value
if (values.isEmpty() || (values.size() == 1 && values.get(0).isEmpty())) {
String finalValue = DEFAULT_EMPTY_VALUE;
// Check if we can use predefined values
Collection<String> predefValues = field.getPredefinedValues();
if (!predefValues.isEmpty()) {
// Try first elements
Iterator<String> iterator = predefValues.iterator();
finalValue = iterator.next();
// If there are more values, don't use the first, as it usually is a "No select"
// item
if (iterator.hasNext()) {
finalValue = iterator.next();
}
} else {
/*
* In all cases, according to Jericho documentation, the only left option is for
* it to be a TEXT field, without any predefined value. We check if it has only
* one userValueCount, and, if so, fill it with a default value.
*/
if (field.getUserValueCount() > 0) {
finalValue = getDefaultTextValue(field);
}
}
log.debug("No existing value for field " + field.getName() + ". Generated: " + finalValue);
values = new ArrayList<>(1);
values.add(finalValue);
}
return values;
}
/**
* Notifies listeners that a new POST resource was found.
*
* @param message the source message
* @param depth the current depth
* @param url the URL of the resource
* @param requestBody the request body
* @see #notifyListenersPostResourceFound(HttpMessage, int, String, String)
*/
private void notifyPostResourceFound(HttpMessage message, int depth, String url, String requestBody) {
log.debug("Submiting form with POST method and message body with form parameters (normal encoding): " + requestBody);
notifyListenersPostResourceFound(message, depth + 1, url, requestBody);
}
/**
* Gets the default value that the input field, including HTML5 types, should have.
*
* <p>
* Generates accurate field values for following types:
* <ul>
* <li>Text/Password/Search - DEFAULT_TEXT_VALUE</li>
* <li>number/range - if min is defined, then use min, otherwise if max is defined use max
* otherwise DEFAULT_NUMBER_VALUE;</li>
* <li>url - http://www.example.com</li>
* <li>email - contact@example.com</li>
* <li>color - #000000</li>
* <li>tel - 9999999999</li>
* <li>date/datetime/time/month/week/datetime-local - current date in the proper format</li>
* <li>file - DEFAULT_FILE_VALUE</li>
* </ul>
*
* @param field the field
* @return the default text value
* @see #getDefaultDate()
*/
private String getDefaultTextValue(FormField field) {
FormControl fc = field.getFormControl();
if (fc.getFormControlType() == FormControlType.TEXT) {
// If the control type was reduced to a TEXT type by the Jericho library, check the
// HTML5 type and use proper values
String type = fc.getAttributesMap().get(ATTR_TYPE);
if (type == null || type.equalsIgnoreCase("text")) {
return DEFAULT_TEXT_VALUE;
}
if (type.equalsIgnoreCase("number") || type.equalsIgnoreCase("range")) {
String min = fc.getAttributesMap().get("min");
if (min != null) {
return min;
}
String max = fc.getAttributesMap().get("max");
if (max != null) {
return max;
}
return DEFAULT_NUMBER_VALUE;
}
if (type.equalsIgnoreCase("url")) {
return "http://www.example.com";
}
if (type.equalsIgnoreCase("email")) {
return "foo-bar@example.com";
}
if (type.equalsIgnoreCase("color")) {
return "#ffffff";
}
if (type.equalsIgnoreCase("tel")) {
return "9999999999";
}
if (type.equalsIgnoreCase("datetime")) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
return format.format(getDefaultDate());
}
if (type.equalsIgnoreCase("datetime-local")) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
return format.format(getDefaultDate());
}
if (type.equalsIgnoreCase("date")) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.format(getDefaultDate());
}
if (type.equalsIgnoreCase("time")) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
return format.format(getDefaultDate());
}
if (type.equalsIgnoreCase("month")) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
return format.format(getDefaultDate());
}
if (type.equalsIgnoreCase("week")) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-'W'ww");
return format.format(getDefaultDate());
}
} else if (fc.getFormControlType() == FormControlType.PASSWORD) {
return DEFAULT_PASS_VALUE;
} else if (fc.getFormControlType() == FormControlType.FILE) {
return DEFAULT_FILE_VALUE;
}
return DEFAULT_EMPTY_VALUE;
}
/**
* Gets the default {@code Date}, to be used for default values of date fields.
*
* @return the date, never {@code null}.
* @see #setDefaultDate(Date)
*/
private Date getDefaultDate() {
if (defaultDate == null) {
return new Date();
}
return defaultDate;
}
/**
* Sets the default {@code Date}, to be used for default values of date fields.
* <p>
* If none ({@code null}) is set it's used the current date when generating the values for the fields.
*
* @param date the default date, might be {@code null}.
* @since TODO add version
*/
public void setDefaultDate(Date date) {
this.defaultDate = date;
}
/**
* Builds the query, encoded with "application/x-www-form-urlencoded".
*
* @see <a href="https://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type">HTML 4.01 Specification - 17.13.4
* Form content types</a>
* @param formDataSet the form data set
* @return the query
*/
private String buildEncodedUrlQuery(List<HtmlParameter> formDataSet) {
StringBuilder request = new StringBuilder();
// Build the query
for (HtmlParameter p : formDataSet) {
String v;
try {
v = URLEncoder.encode(p.getName(), ENCODING_TYPE);
request.append(v);
request.append("=");
v = URLEncoder.encode(p.getValue(), ENCODING_TYPE);
request.append(v);
} catch (UnsupportedEncodingException e) {
log.warn("Error while encoding query for form.", e);
}
request.append("&");
}
// Delete the last ampersand
if (request.length() > 0) {
request.deleteCharAt(request.length() - 1);
}
return request.toString();
}
/**
* Appends the given {@code parameter} into the given {@code query}.
*
* @param query the query
* @param parameter the parameter to append
* @return the query with the parameter appended
*/
private static String appendEncodedUrlQueryParameter(String query, HtmlParameter parameter) {
StringBuilder strBuilder = new StringBuilder(query);
if (strBuilder.length() != 0) {
strBuilder.append('&');
}
try {
strBuilder.append(URLEncoder.encode(parameter.getName(), ENCODING_TYPE))
.append('=')
.append(URLEncoder.encode(parameter.getValue(), ENCODING_TYPE));
} catch (UnsupportedEncodingException e) {
log.warn("Error while encoding query for form.", e);
}
return strBuilder.toString();
}
@Override
public boolean canParseResource(HttpMessage message, String path, boolean wasAlreadyConsumed) {
// Fallback parser - if it's a HTML message which has not already been processed
return !wasAlreadyConsumed && message.getResponseHeader().isHtml();
}
/**
* The fields (and its values) of a HTML form.
* <p>
* Normal fields and submit fields are kept apart.
*/
private static class FormData {
private final List<HtmlParameter> fields;
private final List<HtmlParameter> submitFields;
public FormData(List<HtmlParameter> fields, List<HtmlParameter> submitFields) {
this.fields = fields;
this.submitFields = submitFields;
}
public List<HtmlParameter> getFields() {
return fields;
}
public List<HtmlParameter> getSubmitFields() {
return submitFields;
}
}
}
| |
/*
* Copyright 2013-2014 must-be.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.roots.impl;
import com.google.common.base.Predicate;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Processor;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import org.consulo.lombok.annotations.Logger;
import org.consulo.module.extension.*;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mustbe.consulo.roots.ContentFolderScopes;
import org.mustbe.consulo.roots.ContentFolderTypeProvider;
import org.mustbe.consulo.roots.impl.ExcludedContentFolderTypeProvider;
import org.mustbe.consulo.roots.impl.OrderEntryTypeProviders;
import java.util.*;
/**
* @author VISTALL
* @since 29.07.14
*/
@Logger
public class ModuleRootLayerImpl implements ModifiableModuleRootLayer, Disposable {
private static class ContentComparator implements Comparator<ContentEntry> {
public static final ContentComparator INSTANCE = new ContentComparator();
@Override
public int compare(@NotNull final ContentEntry o1, @NotNull final ContentEntry o2) {
return o1.getUrl().compareTo(o2.getUrl());
}
}
private static class CollectDependentModules extends RootPolicy<List<String>> {
@NotNull
@Override
public List<String> visitModuleOrderEntry(@NotNull ModuleOrderEntry moduleOrderEntry, @NotNull List<String> arrayList) {
arrayList.add(moduleOrderEntry.getModuleName());
return arrayList;
}
}
private class Order extends ArrayList<OrderEntry> {
@Override
public void clear() {
super.clear();
clearCachedEntries();
}
@NotNull
@Override
public OrderEntry set(int i, @NotNull OrderEntry orderEntry) {
super.set(i, orderEntry);
((OrderEntryBaseImpl)orderEntry).setIndex(i);
clearCachedEntries();
return orderEntry;
}
@Override
public boolean add(@NotNull OrderEntry orderEntry) {
super.add(orderEntry);
((OrderEntryBaseImpl)orderEntry).setIndex(size() - 1);
clearCachedEntries();
return true;
}
@Override
public void add(int i, OrderEntry orderEntry) {
super.add(i, orderEntry);
clearCachedEntries();
setIndicies(i);
}
@Override
public OrderEntry remove(int i) {
OrderEntry entry = super.remove(i);
setIndicies(i);
clearCachedEntries();
return entry;
}
@Override
public boolean remove(Object o) {
int index = indexOf(o);
if (index < 0) return false;
remove(index);
clearCachedEntries();
return true;
}
@Override
public boolean addAll(Collection<? extends OrderEntry> collection) {
int startSize = size();
boolean result = super.addAll(collection);
setIndicies(startSize);
clearCachedEntries();
return result;
}
@Override
public boolean addAll(int i, Collection<? extends OrderEntry> collection) {
boolean result = super.addAll(i, collection);
setIndicies(i);
clearCachedEntries();
return result;
}
@Override
public void removeRange(int i, int i1) {
super.removeRange(i, i1);
clearCachedEntries();
setIndicies(i);
}
@Override
public boolean removeAll(@NotNull Collection<?> collection) {
boolean result = super.removeAll(collection);
setIndicies(0);
clearCachedEntries();
return result;
}
@Override
public boolean retainAll(@NotNull Collection<?> collection) {
boolean result = super.retainAll(collection);
setIndicies(0);
clearCachedEntries();
return result;
}
private void clearCachedEntries() {
myCachedOrderEntries = null;
}
private void setIndicies(int startIndex) {
for (int j = startIndex; j < size(); j++) {
((OrderEntryBaseImpl)get(j)).setIndex(j);
}
}
}
private final Set<ContentEntry> myContent = new TreeSet<ContentEntry>(ContentComparator.INSTANCE);
private final List<OrderEntry> myOrderEntries = new Order();
// cleared by myOrderEntries modification, see Order
@Nullable
private OrderEntry[] myCachedOrderEntries;
private final Set<ModuleExtension<?>> myExtensions = new LinkedHashSet<ModuleExtension<?>>();
private final List<Element> myUnknownModuleExtensions = new SmartList<Element>();
private RootModelImpl myRootModel;
@NotNull
private final ModuleLibraryTable myModuleLibraryTable;
public ModuleRootLayerImpl(@Nullable ModuleRootLayerImpl originalLayer, @NotNull RootModelImpl rootModel) {
myRootModel = rootModel;
myModuleLibraryTable = new ModuleLibraryTable(this);
if (originalLayer != null) {
createMutableExtensions(originalLayer);
setContentEntriesFrom(originalLayer);
setOrderEntriesFrom(originalLayer);
}
else {
init();
}
}
public void readExternal(@NotNull Element element) throws InvalidDataException {
removeAllContentEntries();
removeAllOrderEntries();
List<Element> moduleExtensionChild = element.getChildren("extension");
for (Element child : moduleExtensionChild) {
final String id = child.getAttributeValue("id");
ModuleExtensionProviderEP providerEP = ModuleExtensionProviderEP.findProviderEP(id);
if (providerEP != null) {
ModuleExtension<?> moduleExtension = getExtensionWithoutCheck(id);
assert moduleExtension != null;
moduleExtension.loadState(child);
}
else {
myUnknownModuleExtensions.add(child.clone());
}
}
final List<Element> contentChildren = element.getChildren(ContentEntryImpl.ELEMENT_NAME);
for (Element child : contentChildren) {
ContentEntryImpl contentEntry = new ContentEntryImpl(child, this);
myContent.add(contentEntry);
}
final List<Element> orderElements = element.getChildren(OrderEntryTypeProviders.ORDER_ENTRY_ELEMENT_NAME);
boolean moduleSourceAdded = false;
for (Element child : orderElements) {
final OrderEntry orderEntry = OrderEntryTypeProviders.loadOrderEntry(child, this);
if (orderEntry == null) {
continue;
}
if (orderEntry instanceof ModuleSourceOrderEntry) {
if (moduleSourceAdded) {
continue;
}
moduleSourceAdded = true;
}
myOrderEntries.add(orderEntry);
}
if (!moduleSourceAdded) {
myOrderEntries.add(new ModuleSourceOrderEntryImpl(this));
}
}
public void writeExternal(@NotNull Element element) {
List<Element> moduleExtensionElements = new ArrayList<Element>();
for (ModuleExtension<?> extension : myExtensions) {
final Element state = extension.getState();
if (state == null) {
continue;
}
moduleExtensionElements.add(state);
}
for (Element unknownModuleExtension : myUnknownModuleExtensions) {
moduleExtensionElements.add(unknownModuleExtension.clone());
}
Collections.sort(moduleExtensionElements, new Comparator<Element>() {
@Override
public int compare(Element o1, Element o2) {
return Comparing.compare(o1.getAttributeValue("id"), o2.getAttributeValue("id"));
}
});
element.addContent(moduleExtensionElements);
for (ContentEntry contentEntry : getContent()) {
if (contentEntry instanceof ContentEntryImpl) {
final Element subElement = new Element(ContentEntryImpl.ELEMENT_NAME);
((ContentEntryImpl)contentEntry).writeExternal(subElement);
element.addContent(subElement);
}
}
for (OrderEntry orderEntry : getOrderEntries()) {
Element newElement = OrderEntryTypeProviders.storeOrderEntry(orderEntry);
element.addContent(newElement);
}
}
@SuppressWarnings("unchecked")
public boolean copy(@NotNull ModuleRootLayerImpl toSet, boolean notifyExtensionListener) {
boolean changed = false;
if (areOrderEntriesChanged(toSet)) {
toSet.setOrderEntriesFrom(this);
changed = true;
}
if (areContentEntriesChanged(toSet)) {
toSet.setContentEntriesFrom(this);
changed = true;
}
ModuleExtensionChangeListener moduleExtensionChangeListener = getModule().getProject().getMessageBus().syncPublisher(ModuleExtension.CHANGE_TOPIC);
for (ModuleExtension extension : myExtensions) {
MutableModuleExtension mutableExtension = (MutableModuleExtension)extension;
ModuleExtension originalExtension = toSet.getExtensionWithoutCheck(extension.getId());
assert originalExtension != null;
if (mutableExtension.isModified(originalExtension)) {
if (notifyExtensionListener) {
moduleExtensionChangeListener.beforeExtensionChanged(originalExtension, mutableExtension);
}
originalExtension.commit(mutableExtension);
changed = true;
}
}
toSet.myUnknownModuleExtensions.addAll(myUnknownModuleExtensions);
return changed;
}
@SuppressWarnings("unchecked")
public void createMutableExtensions(@Nullable ModuleRootLayerImpl layer) {
for (ModuleExtensionProviderEP providerEP : ModuleExtensionProviderEP.EP_NAME.getExtensions()) {
MutableModuleExtension mutable = providerEP.createMutable(this);
if (mutable == null) {
continue;
}
if (layer != null) {
final ModuleExtension<?> originalExtension = layer.getExtensionWithoutCheck(providerEP.getKey());
assert originalExtension != null;
mutable.commit(originalExtension);
}
myExtensions.add(mutable);
}
}
private void setOrderEntriesFrom(@NotNull ModuleRootLayerImpl layer) {
removeAllOrderEntries();
for (OrderEntry orderEntry : layer.myOrderEntries) {
if (orderEntry instanceof ClonableOrderEntry) {
myOrderEntries.add(((ClonableOrderEntry)orderEntry).cloneEntry(this));
}
}
}
private void setContentEntriesFrom(@NotNull ModuleRootLayerImpl layer) {
removeAllContentEntries();
for (ContentEntry contentEntry : layer.myContent) {
if (contentEntry instanceof ClonableContentEntry) {
myContent.add(((ClonableContentEntry)contentEntry).cloneEntry(this));
}
}
}
public void init() {
removeAllOrderEntries();
myExtensions.clear();
addSourceOrderEntries();
createMutableExtensions(null);
}
public void addSourceOrderEntries() {
myOrderEntries.add(new ModuleSourceOrderEntryImpl(this));
}
@NotNull
private ContentEntry addContentEntry(@NotNull ContentEntry e) {
if (myContent.contains(e)) {
for (ContentEntry contentEntry : getContentEntries()) {
if (ContentComparator.INSTANCE.compare(contentEntry, e) == 0) return contentEntry;
}
}
myContent.add(e);
return e;
}
public boolean areContentEntriesChanged(@NotNull ModuleRootLayerImpl original) {
return ArrayUtil.lexicographicCompare(getContentEntries(), original.getContentEntries()) != 0;
}
public boolean areOrderEntriesChanged(@NotNull ModuleRootLayerImpl original) {
OrderEntry[] orderEntries = getOrderEntries();
OrderEntry[] sourceOrderEntries = original.getOrderEntries();
if (orderEntries.length != sourceOrderEntries.length) return true;
for (int i = 0; i < orderEntries.length; i++) {
OrderEntry orderEntry = orderEntries[i];
OrderEntry sourceOrderEntry = sourceOrderEntries[i];
if (!orderEntriesEquals(orderEntry, sourceOrderEntry)) {
return true;
}
}
return false;
}
public RootModelImpl getRootModel() {
return myRootModel;
}
public boolean areExtensionsChanged(@NotNull ModuleRootLayerImpl original) {
for (ModuleExtension<?> extension : myExtensions) {
MutableModuleExtension mutableExtension = (MutableModuleExtension)extension;
ModuleExtension<?> originalExtension = original.getExtensionWithoutCheck(extension.getId());
assert originalExtension != null;
if (mutableExtension.isModified(originalExtension)) {
return true;
}
}
return false;
}
private static boolean orderEntriesEquals(@NotNull OrderEntry orderEntry1, @NotNull OrderEntry orderEntry2) {
if (orderEntry1.getClass() != orderEntry2.getClass()) {
return false;
}
if (orderEntry1 instanceof ExportableOrderEntry) {
if (!(((ExportableOrderEntry)orderEntry1).isExported() == ((ExportableOrderEntry)orderEntry2).isExported())) {
return false;
}
if (!(((ExportableOrderEntry)orderEntry1).getScope() == ((ExportableOrderEntry)orderEntry2).getScope())) {
return false;
}
}
return orderEntry1.isEquivalentTo(orderEntry2);
}
@NotNull
public Collection<ContentEntry> getContent() {
return myContent;
}
public Iterator<OrderEntry> getOrderIterator() {
return Collections.unmodifiableList(myOrderEntries).iterator();
}
@Override
@NotNull
public Project getProject() {
return getModule().getProject();
}
public boolean isChanged(@NotNull ModuleRootLayerImpl original) {
return areExtensionsChanged(original) || areOrderEntriesChanged(original) || areContentEntriesChanged(original);
}
@NotNull
@Override
public Module getModule() {
return myRootModel.getModule();
}
@Override
public ContentEntry[] getContentEntries() {
final Collection<ContentEntry> content = getContent();
return content.toArray(new ContentEntry[content.size()]);
}
@Override
public boolean iterateContentEntries(@NotNull Processor<ContentEntry> processor) {
for (ContentEntry contentEntry : myContent) {
if(!processor.process(contentEntry)) {
return false;
}
}
return true;
}
@NotNull
@Override
public OrderEntry[] getOrderEntries() {
OrderEntry[] cachedOrderEntries = myCachedOrderEntries;
if (cachedOrderEntries == null) {
myCachedOrderEntries = cachedOrderEntries = myOrderEntries.toArray(new OrderEntry[myOrderEntries.size()]);
}
return cachedOrderEntries;
}
@NotNull
@Override
public VirtualFile[] getContentRoots() {
final ArrayList<VirtualFile> result = new ArrayList<VirtualFile>();
for (ContentEntry contentEntry : getContent()) {
final VirtualFile file = contentEntry.getFile();
if (file != null) {
result.add(file);
}
}
return VfsUtilCore.toVirtualFileArray(result);
}
@NotNull
@Override
public String[] getContentRootUrls() {
if (getContent().isEmpty()) return ArrayUtil.EMPTY_STRING_ARRAY;
final ArrayList<String> result = new ArrayList<String>(getContent().size());
for (ContentEntry contentEntry : getContent()) {
result.add(contentEntry.getUrl());
}
return ArrayUtil.toStringArray(result);
}
@NotNull
@Override
public String[] getContentFolderUrls(@NotNull Predicate<ContentFolderTypeProvider> predicate) {
List<String> result = new SmartList<String>();
for (ContentEntry contentEntry : getContent()) {
Collections.addAll(result, contentEntry.getFolderUrls(predicate));
}
return ArrayUtil.toStringArray(result);
}
@NotNull
@Override
public VirtualFile[] getContentFolderFiles(@NotNull Predicate<ContentFolderTypeProvider> predicate) {
List<VirtualFile> result = new SmartList<VirtualFile>();
for (ContentEntry contentEntry : getContent()) {
Collections.addAll(result, contentEntry.getFolderFiles(predicate));
}
return VfsUtilCore.toVirtualFileArray(result);
}
@NotNull
@Override
public ContentFolder[] getContentFolders(@NotNull Predicate<ContentFolderTypeProvider> predicate) {
List<ContentFolder> result = new SmartList<ContentFolder>();
for (ContentEntry contentEntry : getContent()) {
Collections.addAll(result, contentEntry.getFolders(predicate));
}
return result.isEmpty() ? ContentFolder.EMPTY_ARRAY : result.toArray(new ContentFolder[result.size()]);
}
@NotNull
@Override
public VirtualFile[] getExcludeRoots() {
final List<VirtualFile> result = new SmartList<VirtualFile>();
for (ContentEntry contentEntry : getContent()) {
Collections.addAll(result, contentEntry.getFolderFiles(ContentFolderScopes.of(ExcludedContentFolderTypeProvider.getInstance())));
}
return VfsUtilCore.toVirtualFileArray(result);
}
@NotNull
@Override
public String[] getExcludeRootUrls() {
final List<String> result = new SmartList<String>();
for (ContentEntry contentEntry : getContent()) {
Collections.addAll(result, contentEntry.getFolderUrls(ContentFolderScopes.of(ExcludedContentFolderTypeProvider.getInstance())));
}
return ArrayUtil.toStringArray(result);
}
@NotNull
@Override
public VirtualFile[] getSourceRoots() {
return getSourceRoots(true);
}
@NotNull
@Override
public VirtualFile[] getSourceRoots(boolean includingTests) {
List<VirtualFile> result = new SmartList<VirtualFile>();
for (ContentEntry contentEntry : getContent()) {
Collections.addAll(result, includingTests
? contentEntry.getFolderFiles(ContentFolderScopes.productionAndTest())
: contentEntry.getFolderFiles(ContentFolderScopes.production()));
}
return VfsUtilCore.toVirtualFileArray(result);
}
@NotNull
@Override
public String[] getSourceRootUrls() {
return getSourceRootUrls(true);
}
@NotNull
@Override
public String[] getSourceRootUrls(boolean includingTests) {
List<String> result = new SmartList<String>();
for (ContentEntry contentEntry : getContent()) {
Collections.addAll(result, includingTests
? contentEntry.getFolderUrls(ContentFolderScopes.productionAndTest())
: contentEntry.getFolderUrls(ContentFolderScopes.production()));
}
return ArrayUtil.toStringArray(result);
}
@Override
public <R> R processOrder(RootPolicy<R> policy, R initialValue) {
R result = initialValue;
for (OrderEntry orderEntry : getOrderEntries()) {
result = orderEntry.accept(policy, result);
}
return result;
}
@NotNull
@Override
public OrderEnumerator orderEntries() {
return new ModuleOrderEnumerator(this, null);
}
@NotNull
@Override
public String[] getDependencyModuleNames() {
List<String> result =
orderEntries().withoutSdk().withoutLibraries().withoutModuleSourceEntries().process(new CollectDependentModules(), new ArrayList<String>());
return ArrayUtil.toStringArray(result);
}
@NotNull
@Override
public ModuleExtension[] getExtensions() {
if (myExtensions.isEmpty()) {
return ModuleExtension.EMPTY_ARRAY;
}
List<ModuleExtension> list = new ArrayList<ModuleExtension>(myExtensions.size());
for (ModuleExtension<?> extension : myExtensions) {
if (extension.isEnabled()) {
list.add(extension);
}
}
return list.toArray(new ModuleExtension[list.size()]);
}
@NotNull
@Override
public Module[] getModuleDependencies() {
return getModuleDependencies(true);
}
@NotNull
@Override
public Module[] getModuleDependencies(boolean includeTests) {
final List<Module> result = new ArrayList<Module>();
for (OrderEntry entry : getOrderEntries()) {
if (entry instanceof ModuleOrderEntry) {
ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)entry;
final DependencyScope scope = moduleOrderEntry.getScope();
if (!includeTests && !scope.isForProductionCompile() && !scope.isForProductionRuntime()) {
continue;
}
final Module module1 = moduleOrderEntry.getModule();
if (module1 != null) {
result.add(module1);
}
}
}
return result.isEmpty() ? Module.EMPTY_ARRAY : ContainerUtil.toArray(result, new Module[result.size()]);
}
@Override
@Nullable
public <T extends ModuleExtension> T getExtension(Class<T> clazz) {
for (ModuleExtension<?> extension : myExtensions) {
if (extension.isEnabled() && clazz.isAssignableFrom(extension.getClass())) {
//noinspection unchecked
return (T)extension;
}
}
return null;
}
@Override
@Nullable
public <T extends ModuleExtension> T getExtension(@NotNull String key) {
for (ModuleExtension<?> extension : myExtensions) {
if (extension.isEnabled() && Comparing.equal(extension.getId(), key)) {
//noinspection unchecked
return (T)extension;
}
}
return null;
}
@Override
@Nullable
public <T extends ModuleExtension> T getExtensionWithoutCheck(Class<T> clazz) {
for (ModuleExtension<?> extension : myExtensions) {
if (clazz.isAssignableFrom(extension.getClass())) {
//noinspection unchecked
return (T)extension;
}
}
return null;
}
@Override
@Nullable
public <T extends ModuleExtension> T getExtensionWithoutCheck(@NotNull String key) {
for (ModuleExtension<?> extension : myExtensions) {
if (Comparing.equal(extension.getId(), key)) {
//noinspection unchecked
return (T)extension;
}
}
return null;
}
@NotNull
@Override
public ContentEntry addContentEntry(@NotNull VirtualFile file) {
return addContentEntry(new ContentEntryImpl(file, this));
}
@NotNull
@Override
public ContentEntry addContentEntry(@NotNull String url) {
return addContentEntry(new ContentEntryImpl(url, this));
}
@Override
public void removeContentEntry(@NotNull ContentEntry entry) {
LOGGER.assertTrue(myContent.contains(entry));
if (entry instanceof Disposable) {
Disposer.dispose((Disposable)entry);
}
myContent.remove(entry);
}
@Override
public void addOrderEntry(@NotNull OrderEntry entry) {
LOGGER.assertTrue(!myOrderEntries.contains(entry));
myOrderEntries.add(entry);
}
@NotNull
@Override
public LibraryOrderEntry addLibraryEntry(@NotNull Library library) {
final LibraryOrderEntry libraryOrderEntry = new LibraryOrderEntryImpl(library, this);
assert libraryOrderEntry.isValid();
myOrderEntries.add(libraryOrderEntry);
return libraryOrderEntry;
}
@NotNull
@Override
public ModuleExtensionWithSdkOrderEntry addModuleExtensionSdkEntry(@NotNull ModuleExtensionWithSdk<?> moduleExtension) {
final ModuleExtensionWithSdkOrderEntryImpl moduleSdkOrderEntry = new ModuleExtensionWithSdkOrderEntryImpl(moduleExtension.getId(), this);
assert moduleSdkOrderEntry.isValid();
// add module extension sdk entry after another SDK entry or before module source
int sourcePosition = -1, sdkPosition = -1;
for (int j = 0; j < myOrderEntries.size(); j++) {
OrderEntry orderEntry = myOrderEntries.get(j);
if (orderEntry instanceof ModuleSourceOrderEntry) {
sourcePosition = j;
}
else if (orderEntry instanceof ModuleExtensionWithSdkOrderEntry) {
sdkPosition = j;
}
}
if (sdkPosition >= 0) {
myOrderEntries.add(sdkPosition + 1, moduleSdkOrderEntry);
}
else if (sourcePosition >= 0) {
myOrderEntries.add(sourcePosition, moduleSdkOrderEntry);
}
else {
myOrderEntries.add(0, moduleSdkOrderEntry);
}
return moduleSdkOrderEntry;
}
@NotNull
@Override
public LibraryOrderEntry addInvalidLibrary(@NotNull @NonNls String name, @NotNull String level) {
final LibraryOrderEntry libraryOrderEntry = new LibraryOrderEntryImpl(name, level, this);
myOrderEntries.add(libraryOrderEntry);
return libraryOrderEntry;
}
@NotNull
@Override
public ModuleOrderEntry addModuleOrderEntry(@NotNull Module module) {
LOGGER.assertTrue(!module.equals(getModule()));
LOGGER.assertTrue(Comparing.equal(myRootModel.getModule().getProject(), module.getProject()));
final ModuleOrderEntryImpl moduleOrderEntry = new ModuleOrderEntryImpl(module, this);
myOrderEntries.add(moduleOrderEntry);
return moduleOrderEntry;
}
@NotNull
@Override
public ModuleOrderEntry addInvalidModuleEntry(@NotNull String name) {
LOGGER.assertTrue(!name.equals(getModule().getName()));
final ModuleOrderEntryImpl moduleOrderEntry = new ModuleOrderEntryImpl(name, this);
myOrderEntries.add(moduleOrderEntry);
return moduleOrderEntry;
}
@Nullable
@Override
public LibraryOrderEntry findLibraryOrderEntry(@NotNull Library library) {
for (OrderEntry orderEntry : getOrderEntries()) {
if (orderEntry instanceof LibraryOrderEntry && library.equals(((LibraryOrderEntry)orderEntry).getLibrary())) {
return (LibraryOrderEntry)orderEntry;
}
}
return null;
}
@Nullable
@Override
public ModuleExtensionWithSdkOrderEntry findModuleExtensionSdkEntry(@NotNull ModuleExtension extension) {
for (OrderEntry orderEntry : getOrderEntries()) {
if (orderEntry instanceof ModuleExtensionWithSdkOrderEntry &&
extension.getId().equals(((ModuleExtensionWithSdkOrderEntry)orderEntry).getModuleExtensionId())) {
return (ModuleExtensionWithSdkOrderEntry)orderEntry;
}
}
return null;
}
@Override
public void removeOrderEntry(@NotNull OrderEntry orderEntry) {
removeOrderEntryInternal(orderEntry);
}
private void removeOrderEntryInternal(OrderEntry entry) {
LOGGER.assertTrue(myOrderEntries.contains(entry));
Disposer.dispose((OrderEntryBaseImpl)entry);
myOrderEntries.remove(entry);
}
@Override
public void rearrangeOrderEntries(@NotNull OrderEntry[] newEntries) {
assertValidRearrangement(newEntries);
myOrderEntries.clear();
ContainerUtil.addAll(myOrderEntries, newEntries);
}
private void assertValidRearrangement(@NotNull OrderEntry[] newEntries) {
String error = checkValidRearrangement(newEntries);
LOGGER.assertTrue(error == null, error);
}
@Nullable
private String checkValidRearrangement(@NotNull OrderEntry[] newEntries) {
if (newEntries.length != myOrderEntries.size()) {
return "Size mismatch: old size=" + myOrderEntries.size() + "; new size=" + newEntries.length;
}
Set<OrderEntry> set = new HashSet<OrderEntry>();
for (OrderEntry newEntry : newEntries) {
if (!myOrderEntries.contains(newEntry)) {
return "Trying to add nonexisting order entry " + newEntry;
}
if (set.contains(newEntry)) {
return "Trying to add duplicate order entry " + newEntry;
}
set.add(newEntry);
}
return null;
}
public void removeAllContentEntries() {
for (ContentEntry entry : myContent) {
if (entry instanceof BaseModuleRootLayerChild) {
Disposer.dispose((BaseModuleRootLayerChild)entry);
}
}
myContent.clear();
}
public void removeAllOrderEntries() {
for (OrderEntry entry : myOrderEntries) {
Disposer.dispose((OrderEntryBaseImpl)entry);
}
myOrderEntries.clear();
}
@Override
public void dispose() {
removeAllContentEntries();
removeAllOrderEntries();
for (ModuleExtension<?> extension : myExtensions) {
if(extension instanceof Disposable) {
Disposer.dispose((Disposable)extension);
}
}
myExtensions.clear();
}
@NotNull
@Override
public LibraryTable getModuleLibraryTable() {
return myModuleLibraryTable;
}
@Override
public <T extends OrderEntry> void replaceEntryOfType(Class<T> entryClass, T entry) {
for (int i = 0; i < myOrderEntries.size(); i++) {
OrderEntry orderEntry = myOrderEntries.get(i);
if (entryClass.isInstance(orderEntry)) {
myOrderEntries.remove(i);
if (entry != null) {
myOrderEntries.add(i, entry);
}
return;
}
}
if (entry != null) {
myOrderEntries.add(0, entry);
}
}
}
| |
/*
* Copyright 2003-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovy.util;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;
import groovy.lang.GroovyResourceLoader;
import groovy.lang.Script;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.classgen.GeneratorContext;
import org.codehaus.groovy.control.ClassNodeResolver;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.Phases;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.customizers.CompilationCustomizer;
import org.codehaus.groovy.runtime.IOGroovyMethods;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.tools.gse.DependencyTracker;
import org.codehaus.groovy.tools.gse.StringSetMap;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Specific script engine able to reload modified scripts as well as dealing properly
* with dependent scripts.
*
* @author sam
* @author Marc Palmer
* @author Guillaume Laforge
* @author Jochen Theodorou
* @author Mattias Reichel
*/
public class GroovyScriptEngine implements ResourceConnector {
private static final ClassLoader CL_STUB = new ClassLoader() {
};
private static final URL[] EMPTY_URL_ARRAY = new URL[0];
private static class LocalData {
CompilationUnit cu;
StringSetMap dependencyCache = new StringSetMap();
Map<String, String> precompiledEntries = new HashMap<String, String>();
}
private static WeakReference<ThreadLocal<LocalData>> localData = new WeakReference<ThreadLocal<LocalData>>(null);
private static synchronized ThreadLocal<LocalData> getLocalData() {
ThreadLocal<LocalData> local = localData.get();
if (local != null) return local;
local = new ThreadLocal<LocalData>();
localData = new WeakReference<ThreadLocal<LocalData>>(local);
return local;
}
private URL[] roots;
private ResourceConnector rc;
private final ClassLoader parentLoader;
private final GroovyClassLoader groovyLoader;
private final Map<String, ScriptCacheEntry> scriptCache = new ConcurrentHashMap<String, ScriptCacheEntry>();
private CompilerConfiguration config;
{
config = new CompilerConfiguration(CompilerConfiguration.DEFAULT);
config.setSourceEncoding("UTF-8");
}
//TODO: more finals?
private static class ScriptCacheEntry {
private final Class scriptClass;
private final long lastModified, lastCheck;
private final Set<String> dependencies;
private final boolean sourceNewer;
public ScriptCacheEntry(Class clazz, long modified, long lastCheck, Set<String> depend, boolean sourceNewer) {
this.scriptClass = clazz;
this.lastModified = modified;
this.lastCheck = lastCheck;
this.dependencies = depend;
this.sourceNewer = sourceNewer;
}
public ScriptCacheEntry(ScriptCacheEntry old, long lastCheck, boolean sourceNewer) {
this(old.scriptClass, old.lastModified, lastCheck, old.dependencies, sourceNewer);
}
}
private class ScriptClassLoader extends GroovyClassLoader {
public ScriptClassLoader(GroovyClassLoader loader) {
super(loader);
}
public ScriptClassLoader(ClassLoader loader, CompilerConfiguration config) {
super(loader, config, false);
setResLoader();
}
private void setResLoader() {
final GroovyResourceLoader rl = getResourceLoader();
setResourceLoader(new GroovyResourceLoader() {
public URL loadGroovySource(String className) throws MalformedURLException {
String filename;
for (String extension : getConfig().getScriptExtensions()) {
filename = className.replace('.', File.separatorChar) + "." + extension;
try {
URLConnection dependentScriptConn = rc.getResourceConnection(filename);
return dependentScriptConn.getURL();
} catch (ResourceException e) {
//TODO: maybe do something here?
}
}
return rl.loadGroovySource(className);
}
});
}
@Override
protected CompilationUnit createCompilationUnit(CompilerConfiguration configuration, CodeSource source) {
CompilationUnit cu = super.createCompilationUnit(configuration, source);
LocalData local = getLocalData().get();
local.cu = cu;
final StringSetMap cache = local.dependencyCache;
final Map<String, String> precompiledEntries = local.precompiledEntries;
// "." is used to transfer compilation dependencies, which will be
// recollected later during compilation
for (String depSourcePath : cache.get(".")) {
try {
cache.get(depSourcePath);
cu.addSource(getResourceConnection(depSourcePath).getURL());
} catch (ResourceException e) {
/* ignore */
}
}
// remove all old entries including the "." entry
cache.clear();
cu.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() {
@Override
public void call(final SourceUnit source, GeneratorContext context, ClassNode classNode)
throws CompilationFailedException {
// GROOVY-4013: If it is an inner class, tracking its dependencies doesn't really
// serve any purpose and also interferes with the caching done to track dependencies
if (classNode instanceof InnerClassNode) return;
DependencyTracker dt = new DependencyTracker(source, cache, precompiledEntries);
dt.visitClass(classNode);
}
}, Phases.CLASS_GENERATION);
cu.setClassNodeResolver(new ClassNodeResolver() {
@Override
public LookupResult findClassNode(String origName, CompilationUnit compilationUnit) {
CompilerConfiguration cc = compilationUnit.getConfiguration();
String name = origName.replace('.', '/');
for (String ext : cc.getScriptExtensions()) {
try {
String finalName = name + "." + ext;
URLConnection conn = rc.getResourceConnection(finalName);
URL url = conn.getURL();
String path = url.toExternalForm();
ScriptCacheEntry entry = scriptCache.get(path);
Class clazz = null;
if (entry != null) clazz = entry.scriptClass;
if (GroovyScriptEngine.this.isSourceNewer(entry)) {
try {
SourceUnit su = compilationUnit.addSource(url);
return new LookupResult(su, null);
} finally {
forceClose(conn);
}
} else {
precompiledEntries.put(origName, path);
}
if (clazz != null) {
ClassNode cn = new ClassNode(clazz);
return new LookupResult(null, cn);
}
} catch (ResourceException re) {
// skip
}
}
return super.findClassNode(origName, compilationUnit);
}
});
final List<CompilationCustomizer> customizers = config.getCompilationCustomizers();
if (customizers != null) {
// GROOVY-4813 : apply configuration customizers
for (CompilationCustomizer customizer : customizers) {
cu.addPhaseOperation(customizer, customizer.getPhase().getPhaseNumber());
}
}
return cu;
}
@Override
public Class parseClass(GroovyCodeSource codeSource, boolean shouldCacheSource) throws CompilationFailedException {
synchronized (sourceCache) {
return doParseClass(codeSource);
}
}
private Class doParseClass(GroovyCodeSource codeSource) {
// local is kept as hard reference to avoid garbage collection
ThreadLocal<LocalData> localTh = getLocalData();
LocalData localData = new LocalData();
localTh.set(localData);
StringSetMap cache = localData.dependencyCache;
// we put the old dependencies into local cache so createCompilationUnit
// can pick it up. We put that entry under the name "."
ScriptCacheEntry origEntry = scriptCache.get(codeSource.getName());
Set<String> origDep = null;
if (origEntry != null) origDep = origEntry.dependencies;
if (origDep != null) {
Set<String> newDep = new HashSet<String>(origDep.size());
for (String depName : origDep) {
ScriptCacheEntry dep = scriptCache.get(depName);
try {
if (origEntry == dep || GroovyScriptEngine.this.isSourceNewer(dep)) {
newDep.add(depName);
}
} catch (ResourceException re) {
}
}
cache.put(".", newDep);
}
Class answer = super.parseClass(codeSource, false);
cache.makeTransitiveHull();
long time = getCurrentTime();
Set<String> entryNames = new HashSet<String>();
for (Map.Entry<String, Set<String>> entry : cache.entrySet()) {
String className = entry.getKey();
Class clazz = getClassCacheEntry(className);
if (clazz == null) continue;
String entryName = getPath(clazz, localData.precompiledEntries);
if (entryNames.contains(entryName)) continue;
entryNames.add(entryName);
Set<String> value = convertToPaths(entry.getValue(), localData.precompiledEntries);
long lastModified;
try {
lastModified = getLastModified(entryName);
} catch (ResourceException e) {
lastModified = time;
}
ScriptCacheEntry cacheEntry = new ScriptCacheEntry(clazz, lastModified, time, value, false);
scriptCache.put(entryName, cacheEntry);
}
cache.clear();
localTh.set(null);
return answer;
}
private String getPath(Class clazz, Map<String, String> precompiledEntries) {
CompilationUnit cu = getLocalData().get().cu;
String name = clazz.getName();
ClassNode classNode = cu.getClassNode(name);
if (classNode == null) {
// this is a precompiled class!
String path = precompiledEntries.get(name);
if (path == null) throw new GroovyBugError("Precompiled class " + name + " should be available in precompiled entries map, but was not.");
return path;
} else {
return classNode.getModule().getContext().getName();
}
}
private Set<String> convertToPaths(Set<String> orig, Map<String, String> precompiledEntries) {
Set<String> ret = new HashSet<String>();
for (String className : orig) {
Class clazz = getClassCacheEntry(className);
if (clazz == null) continue;
ret.add(getPath(clazz, precompiledEntries));
}
return ret;
}
}
/**
* Simple testing harness for the GSE. Enter script roots as arguments and
* then input script names to run them.
*
* @param urls an array of URLs
* @throws Exception if something goes wrong
*/
public static void main(String[] urls) throws Exception {
GroovyScriptEngine gse = new GroovyScriptEngine(urls);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while (true) {
System.out.print("groovy> ");
if ((line = br.readLine()) == null || line.equals("quit")) {
break;
}
try {
System.out.println(gse.run(line, new Binding()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Initialize a new GroovyClassLoader with a default or
* constructor-supplied parentClassLoader.
*
* @return the parent classloader used to load scripts
*/
private GroovyClassLoader initGroovyLoader() {
return (GroovyClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
if (parentLoader instanceof GroovyClassLoader) {
return new ScriptClassLoader((GroovyClassLoader) parentLoader);
} else {
return new ScriptClassLoader(parentLoader, config);
}
}
});
}
/**
* Get a resource connection as a <code>URLConnection</code> to retrieve a script
* from the <code>ResourceConnector</code>.
*
* @param resourceName name of the resource to be retrieved
* @return a URLConnection to the resource
* @throws ResourceException
*/
public URLConnection getResourceConnection(String resourceName) throws ResourceException {
// Get the URLConnection
URLConnection groovyScriptConn = null;
ResourceException se = null;
for (URL root : roots) {
URL scriptURL = null;
try {
scriptURL = new URL(root, resourceName);
groovyScriptConn = openConnection(scriptURL);
break; // Now this is a bit unusual
} catch (MalformedURLException e) {
String message = "Malformed URL: " + root + ", " + resourceName;
if (se == null) {
se = new ResourceException(message);
} else {
se = new ResourceException(message, se);
}
} catch (IOException e1) {
String message = "Cannot open URL: " + root + resourceName;
groovyScriptConn = null;
if (se == null) {
se = new ResourceException(message);
} else {
se = new ResourceException(message, se);
}
}
}
if (se == null) se = new ResourceException("No resource for " + resourceName + " was found");
// If we didn't find anything, report on all the exceptions that occurred.
if (groovyScriptConn == null) throw se;
return groovyScriptConn;
}
private static URLConnection openConnection(URL scriptURL) throws IOException {
URLConnection urlConnection = scriptURL.openConnection();
verifyInputStream(urlConnection);
return scriptURL.openConnection();
}
/**
* This method closes a {@link URLConnection} by getting its {@link InputStream} and calling the
* {@link InputStream#close()} method on it. The {@link URLConnection} doesn't have a close() method
* and relies on garbage collection to close the underlying connection to the file.
* Relying on garbage collection could lead to the application exhausting the number of files the
* user is allowed to have open at any one point in time and cause the application to crash
* ({@link java.io.FileNotFoundException} (Too many open files)).
* Hence the need for this method to explicitly close the underlying connection to the file.
*
* @param urlConnection the {@link URLConnection} to be "closed" to close the underlying file descriptors.
*/
private static void forceClose(URLConnection urlConnection) {
if (urlConnection != null) {
// We need to get the input stream and close it to force the open
// file descriptor to be released. Otherwise, we will reach the limit
// for number of files open at one time.
try {
verifyInputStream(urlConnection);
} catch (Exception e) {
// Do nothing: We were not going to use it anyway.
}
}
}
private static void verifyInputStream(URLConnection urlConnection) throws IOException {
InputStream in = null;
try {
in = urlConnection.getInputStream();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignore) {
}
}
}
}
/**
* The groovy script engine will run groovy scripts and reload them and
* their dependencies when they are modified. This is useful for embedding
* groovy in other containers like games and application servers.
*
* @param roots This an array of URLs where Groovy scripts will be stored. They should
* be laid out using their package structure like Java classes
*/
private GroovyScriptEngine(URL[] roots, ClassLoader parent, ResourceConnector rc) {
if (roots == null) roots = EMPTY_URL_ARRAY;
this.roots = roots;
if (rc == null) rc = this;
this.rc = rc;
if (parent == CL_STUB) parent = this.getClass().getClassLoader();
this.parentLoader = parent;
this.groovyLoader = initGroovyLoader();
for (URL root : roots) this.groovyLoader.addURL(root);
}
public GroovyScriptEngine(URL[] roots) {
this(roots, CL_STUB, null);
}
public GroovyScriptEngine(URL[] roots, ClassLoader parentClassLoader) {
this(roots, parentClassLoader, null);
}
public GroovyScriptEngine(String[] urls) throws IOException {
this(createRoots(urls), CL_STUB, null);
}
private static URL[] createRoots(String[] urls) throws MalformedURLException {
if (urls == null) return null;
URL[] roots = new URL[urls.length];
for (int i = 0; i < roots.length; i++) {
if (urls[i].indexOf("://") != -1) {
roots[i] = new URL(urls[i]);
} else {
roots[i] = new File(urls[i]).toURI().toURL();
}
}
return roots;
}
public GroovyScriptEngine(String[] urls, ClassLoader parentClassLoader) throws IOException {
this(createRoots(urls), parentClassLoader, null);
}
public GroovyScriptEngine(String url) throws IOException {
this(new String[]{url});
}
public GroovyScriptEngine(String url, ClassLoader parentClassLoader) throws IOException {
this(new String[]{url}, parentClassLoader);
}
public GroovyScriptEngine(ResourceConnector rc) {
this(null, CL_STUB, rc);
}
public GroovyScriptEngine(ResourceConnector rc, ClassLoader parentClassLoader) {
this(null, parentClassLoader, rc);
}
/**
* Get the <code>ClassLoader</code> that will serve as the parent ClassLoader of the
* {@link GroovyClassLoader} in which scripts will be executed. By default, this is the
* ClassLoader that loaded the <code>GroovyScriptEngine</code> class.
*
* @return the parent classloader used to load scripts
*/
public ClassLoader getParentClassLoader() {
return parentLoader;
}
/**
* Get the class of the scriptName in question, so that you can instantiate
* Groovy objects with caching and reloading.
*
* @param scriptName resource name pointing to the script
* @return the loaded scriptName as a compiled class
* @throws ResourceException if there is a problem accessing the script
* @throws ScriptException if there is a problem parsing the script
*/
public Class loadScriptByName(String scriptName) throws ResourceException, ScriptException {
URLConnection conn = rc.getResourceConnection(scriptName);
String path = conn.getURL().toExternalForm();
ScriptCacheEntry entry = scriptCache.get(path);
Class clazz = null;
if (entry != null) clazz = entry.scriptClass;
try {
if (isSourceNewer(entry)) {
try {
String encoding = conn.getContentEncoding() != null ? conn.getContentEncoding() : config.getSourceEncoding();
String content = IOGroovyMethods.getText(conn.getInputStream(), encoding);
clazz = groovyLoader.parseClass(content, path);
} catch (IOException e) {
throw new ResourceException(e);
}
}
} finally {
forceClose(conn);
}
return clazz;
}
/**
* Run a script identified by name with a single argument.
*
* @param scriptName name of the script to run
* @param argument a single argument passed as a variable named <code>arg</code> in the binding
* @return a <code>toString()</code> representation of the result of the execution of the script
* @throws ResourceException if there is a problem accessing the script
* @throws ScriptException if there is a problem parsing the script
*/
public String run(String scriptName, String argument) throws ResourceException, ScriptException {
Binding binding = new Binding();
binding.setVariable("arg", argument);
Object result = run(scriptName, binding);
return result == null ? "" : result.toString();
}
/**
* Run a script identified by name with a given binding.
*
* @param scriptName name of the script to run
* @param binding the binding to pass to the script
* @return an object
* @throws ResourceException if there is a problem accessing the script
* @throws ScriptException if there is a problem parsing the script
*/
public Object run(String scriptName, Binding binding) throws ResourceException, ScriptException {
return createScript(scriptName, binding).run();
}
/**
* Creates a Script with a given scriptName and binding.
*
* @param scriptName name of the script to run
* @param binding the binding to pass to the script
* @return the script object
* @throws ResourceException if there is a problem accessing the script
* @throws ScriptException if there is a problem parsing the script
*/
public Script createScript(String scriptName, Binding binding) throws ResourceException, ScriptException {
return InvokerHelper.createScript(loadScriptByName(scriptName), binding);
}
private long getLastModified(String scriptName) throws ResourceException {
URLConnection conn = rc.getResourceConnection(scriptName);
long lastMod = 0;
try {
lastMod = conn.getLastModified();
} finally {
// getResourceConnection() opening the inputstream, let's ensure all streams are closed
forceClose(conn);
}
return lastMod;
}
protected boolean isSourceNewer(ScriptCacheEntry entry) throws ResourceException {
if (entry == null) return true;
long mainEntryLastCheck = entry.lastCheck;
long now = 0;
boolean returnValue = false;
for (String scriptName : entry.dependencies) {
ScriptCacheEntry depEntry = scriptCache.get(scriptName);
if (depEntry.sourceNewer) return true;
// check if maybe dependency was recompiled, but this one here not
if (mainEntryLastCheck < depEntry.lastModified) {
returnValue = true;
continue;
}
if (now == 0) now = getCurrentTime();
long nextSourceCheck = depEntry.lastCheck + config.getMinimumRecompilationInterval();
if (nextSourceCheck > now) continue;
long lastMod = getLastModified(scriptName);
if (depEntry.lastModified < lastMod) {
depEntry = new ScriptCacheEntry(depEntry, lastMod, true);
scriptCache.put(scriptName, depEntry);
returnValue = true;
} else {
depEntry = new ScriptCacheEntry(depEntry, now, false);
scriptCache.put(scriptName, depEntry);
}
}
return returnValue;
}
/**
* Returns the GroovyClassLoader associated with this script engine instance.
* Useful if you need to pass the class loader to another library.
*
* @return the GroovyClassLoader
*/
public GroovyClassLoader getGroovyClassLoader() {
return groovyLoader;
}
/**
* @return a non null compiler configuration
*/
public CompilerConfiguration getConfig() {
return config;
}
/**
* sets a compiler configuration
*
* @param config - the compiler configuration
* @throws NullPointerException if config is null
*/
public void setConfig(CompilerConfiguration config) {
if (config == null) throw new NullPointerException("configuration cannot be null");
this.config = config;
}
protected long getCurrentTime() {
return System.currentTimeMillis();
}
}
| |
/*
* Copyright 2013 Proofpoint Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kairosdb.core;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.google.gson.Gson;
import com.google.inject.*;
import org.apache.commons.io.FileUtils;
import org.h2.util.StringUtils;
import org.json.JSONException;
import org.json.JSONWriter;
import org.kairosdb.core.datastore.KairosDatastore;
import org.kairosdb.core.datastore.QueryCallback;
import org.kairosdb.core.datastore.QueryMetric;
import org.kairosdb.core.exception.DatastoreException;
import org.kairosdb.core.exception.KairosDBException;
import org.kairosdb.core.http.rest.json.JsonMetricParser;
import org.kairosdb.core.http.rest.json.ValidationErrors;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;
import java.io.*;
import java.lang.reflect.Constructor;
import java.nio.charset.Charset;
import java.util.*;
public class Main
{
public static final Logger logger = (Logger) LoggerFactory.getLogger(Main.class);
public static final Charset UTF_8 = Charset.forName("UTF-8");
public static final String SERVICE_PREFIX = "kairosdb.service";
private final static Object s_shutdownObject = new Object();
private static final Arguments arguments = new Arguments();
private Injector m_injector;
private List<KairosDBService> m_services = new ArrayList<KairosDBService>();
private void loadPlugins(Properties props, final File propertiesFile) throws IOException
{
File propDir = propertiesFile.getParentFile();
if (propDir == null)
propDir = new File(".");
String[] pluginProps = propDir.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return (name.endsWith(".properties") && !name.equals(propertiesFile.getName()));
}
});
ClassLoader cl = getClass().getClassLoader();
for (String prop : pluginProps)
{
logger.info("Loading plugin properties: {}", prop);
//Load the properties file from a jar if there is one first.
//This way defaults can be set
InputStream propStream = cl.getResourceAsStream(prop);
if (propStream != null)
{
props.load(propStream);
propStream.close();
}
//Load the file in
FileInputStream fis = new FileInputStream(new File(propDir, prop));
props.load(fis);
fis.close();
}
}
public Main(File propertiesFile) throws IOException
{
Properties props = new Properties();
InputStream is = getClass().getClassLoader().getResourceAsStream("kairosdb.properties");
props.load(is);
is.close();
if (propertiesFile != null)
{
FileInputStream fis = new FileInputStream(propertiesFile);
props.load(fis);
fis.close();
loadPlugins(props, propertiesFile);
}
List<Module> moduleList = new ArrayList<Module>();
moduleList.add(new CoreModule(props));
for (String propName : props.stringPropertyNames())
{
if (propName.startsWith(SERVICE_PREFIX))
{
Class<?> aClass;
try
{
if ("".equals(props.getProperty(propName)))
continue;
aClass = Class.forName(props.getProperty(propName));
if (Module.class.isAssignableFrom(aClass))
{
Constructor<?> constructor = null;
try
{
constructor = aClass.getConstructor(Properties.class);
}
catch (NoSuchMethodException ignore)
{
}
/*
Check if they have a constructor that takes the properties
if not construct using the default constructor
*/
Module mod;
if (constructor != null)
mod = (Module) constructor.newInstance(props);
else
mod = (Module) aClass.newInstance();
moduleList.add(mod);
}
}
catch (Exception e)
{
logger.error("Unable to load service " + propName, e);
}
}
}
m_injector = Guice.createInjector(moduleList);
}
public static void main(String[] args) throws Exception
{
//This sends jersey java util logging to logback
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
JCommander commander = new JCommander(arguments);
try
{
commander.parse(args);
}
catch (Exception e)
{
System.out.println(e.getMessage());
commander.usage();
System.exit(0);
}
if (arguments.helpMessage || arguments.help)
{
commander.usage();
System.exit(0);
}
if (!arguments.operationCommand.equals("run"))
{
//Turn off console logging
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.getAppender("stdout").addFilter(new Filter<ILoggingEvent>()
{
@Override
public FilterReply decide(ILoggingEvent iLoggingEvent)
{
return (FilterReply.DENY);
}
});
}
File propertiesFile = null;
if (!StringUtils.isNullOrEmpty(arguments.propertiesFile))
propertiesFile = new File(arguments.propertiesFile);
final Main main = new Main(propertiesFile);
if (arguments.operationCommand.equals("export"))
{
if (!StringUtils.isNullOrEmpty(arguments.exportFile))
{
Writer ps = new OutputStreamWriter(new FileOutputStream(arguments.exportFile,
arguments.appendToExportFile), "UTF-8");
main.runExport(ps, arguments.exportMetricNames);
ps.flush();
ps.close();
}
else
{
main.runExport(new OutputStreamWriter(System.out, "UTF-8"), arguments.exportMetricNames);
System.out.flush();
}
main.stopServices();
}
else if (arguments.operationCommand.equals("import"))
{
if (!StringUtils.isNullOrEmpty(arguments.exportFile))
{
FileInputStream fin = new FileInputStream(arguments.exportFile);
main.runImport(fin);
fin.close();
}
else
{
main.runImport(System.in);
}
main.stopServices();
}
else if (arguments.operationCommand.equals("run") || arguments.operationCommand.equals("start"))
{
try
{
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
{
public void run()
{
try
{
main.stopServices();
synchronized (s_shutdownObject)
{
s_shutdownObject.notify();
}
}
catch (Exception e)
{
logger.error("Shutdown exception:", e);
}
}
}));
main.startServices();
logger.info("------------------------------------------");
logger.info(" KairosDB service started");
logger.info("------------------------------------------");
waitForShutdown();
}
catch (Exception e)
{
logger.error("Failed starting up services", e);
//main.stopServices();
System.exit(0);
}
finally
{
logger.info("--------------------------------------");
logger.info(" KairosDB service is now down!");
logger.info("--------------------------------------");
}
}
}
public Injector getInjector()
{
return (m_injector);
}
public void runExport(Writer out, List<String> metricNames) throws DatastoreException, IOException
{
RecoveryFile recoveryFile = new RecoveryFile();
try
{
KairosDatastore ds = m_injector.getInstance(KairosDatastore.class);
Iterable<String> metrics;
if (metricNames != null && metricNames.size() > 0)
metrics = metricNames;
else
metrics = ds.getMetricNames();
for (String metric : metrics)
{
if (!recoveryFile.contains(metric))
{
logger.info("Exporting: " + metric);
QueryMetric qm = new QueryMetric(1L, 0, metric);
ExportQueryCallback callback = new ExportQueryCallback(metric, out);
ds.export(qm, callback);
recoveryFile.writeMetric(metric);
}
else
logger.info("Skipping metric " + metric + " because it was already exported.");
}
}
finally
{
recoveryFile.close();
}
}
public void runImport(InputStream in) throws IOException, DatastoreException
{
KairosDatastore ds = m_injector.getInstance(KairosDatastore.class);
KairosDataPointFactory dpFactory = m_injector.getInstance(KairosDataPointFactory.class);
BufferedReader reader = new BufferedReader(new InputStreamReader(in, UTF_8));
Gson gson = new Gson();
String line;
while ((line = reader.readLine()) != null)
{
JsonMetricParser jsonMetricParser = new JsonMetricParser(ds, new StringReader(line),
gson, dpFactory);
ValidationErrors validationErrors = jsonMetricParser.parse();
for (String error : validationErrors.getErrors())
{
logger.error(error);
System.err.println(error);
}
}
}
/**
* Simple technique to prevent the main thread from existing until we are done
*/
private static void waitForShutdown()
{
try
{
synchronized (s_shutdownObject)
{
s_shutdownObject.wait();
}
}
catch (InterruptedException ignore)
{
}
}
public void startServices() throws KairosDBException
{
Map<Key<?>, Binding<?>> bindings =
m_injector.getAllBindings();
for (Key<?> key : bindings.keySet())
{
Class bindingClass = key.getTypeLiteral().getRawType();
if (KairosDBService.class.isAssignableFrom(bindingClass))
{
KairosDBService service = (KairosDBService) m_injector.getInstance(bindingClass);
logger.info("Starting service " + bindingClass);
service.start();
m_services.add(service);
}
}
}
public void stopServices() throws DatastoreException, InterruptedException
{
logger.info("Shutting down");
for (KairosDBService service : m_services)
{
String serviceName = service.getClass().getName();
logger.info("Stopping " + serviceName);
try
{
service.stop();
logger.info("Stopped " + serviceName);
}
catch (Exception e)
{
logger.error("Error stopping " + serviceName, e);
}
}
//Stop the datastore
KairosDatastore ds = m_injector.getInstance(KairosDatastore.class);
ds.close();
}
private class RecoveryFile
{
private final Set<String> metricsExported = new HashSet<String>();
private File recoveryFile;
private PrintWriter writer;
public RecoveryFile() throws IOException
{
if (!StringUtils.isNullOrEmpty(arguments.exportRecoveryFile))
{
recoveryFile = new File(arguments.exportRecoveryFile);
logger.info("Tracking exported metric names in " + recoveryFile.getAbsolutePath());
if (recoveryFile.exists())
{
logger.info("Skipping metrics found in " + recoveryFile.getAbsolutePath());
List<String> list = FileUtils.readLines(recoveryFile);
metricsExported.addAll(list);
}
writer = new PrintWriter(new FileOutputStream(recoveryFile, true));
}
}
public boolean contains(String metric)
{
return metricsExported.contains(metric);
}
public void writeMetric(String metric)
{
if (writer != null)
{
writer.println(metric);
writer.flush();
}
}
public void close()
{
if (writer != null)
writer.close();
}
}
private class ExportQueryCallback implements QueryCallback
{
private final Writer m_writer;
private JSONWriter m_jsonWriter;
private final String m_metric;
public ExportQueryCallback(String metricName, Writer out)
{
m_metric = metricName;
m_writer = out;
}
@Override
public void addDataPoint(DataPoint datapoint) throws IOException
{
try
{
m_jsonWriter.array().value(datapoint.getTimestamp());
datapoint.writeValueToJson(m_jsonWriter);
m_jsonWriter.value(datapoint.getApiDataType()).endArray();
}
catch (JSONException e)
{
throw new IOException(e);
}
}
@Override
public void startDataPointSet(String type, Map<String, String> tags) throws IOException
{
if (m_jsonWriter != null)
endDataPoints();
try
{
m_jsonWriter = new JSONWriter(m_writer);
m_jsonWriter.object();
m_jsonWriter.key("name").value(m_metric);
m_jsonWriter.key("tags").value(tags);
m_jsonWriter.key("datapoints").array();
}
catch (JSONException e)
{
throw new IOException(e);
}
}
@Override
public void endDataPoints() throws IOException
{
try
{
if (m_jsonWriter != null)
{
m_jsonWriter.endArray().endObject();
m_writer.write("\n");
m_jsonWriter = null;
}
}
catch (JSONException e)
{
throw new IOException(e);
}
}
}
@SuppressWarnings("UnusedDeclaration")
private static class Arguments
{
@Parameter(names = "-p", description = "A custom properties file")
private String propertiesFile;
@Parameter(names = "-f", description = "File to save export to or read from depending on command.")
private String exportFile;
@Parameter(names = "-n", description = "Name of metrics to export. If not specified, then all metrics are exported.")
private List<String> exportMetricNames;
@Parameter(names = "-r", description = "Full path to a recovery file. The file tracks metrics that have been exported. " +
"If export fails and is run again it uses this file to pickup where it left off.")
private String exportRecoveryFile;
@Parameter(names = "-a", description = "Appends to the export file. By default, the export file is overwritten.")
private boolean appendToExportFile;
@Parameter(names = "--help", description = "Help message.", help = true)
private boolean helpMessage;
@Parameter(names = "-h", description = "Help message.", help = true)
private boolean help;
/**
* start is identical to run except that logging data only goes to the log file
* and not to standard out as well
*/
@Parameter(names = "-c", description = "Command to run: export, import, run, start.")
private String operationCommand;
}
}
| |
/*
* $Header: /home/cvs/jakarta-tomcat-4.0/catalina/src/share/org/apache/catalina/session/PersistentManagerBase.java,v 1.9 2002/08/28 17:08:58 bobh Exp $
* $Revision: 1.9 $
* $Date: 2002/08/28 17:08:58 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.catalina.session;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.ServletContext;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Loader;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.Store;
import org.apache.catalina.util.LifecycleSupport;
/**
* Extends the <b>ManagerBase</b> class to implement most of the
* functionality required by a Manager which supports any kind of
* persistence, even if onlyfor restarts.
* <p>
* <b>IMPLEMENTATION NOTE</b>: Correct behavior of session storing and
* reloading depends upon external calls to the <code>start()</code> and
* <code>stop()</code> methods of this class at the correct times.
*
* @author Craig R. McClanahan
* @version $Revision: 1.9 $ $Date: 2002/08/28 17:08:58 $
*/
public abstract class PersistentManagerBase
extends ManagerBase
implements Lifecycle, PropertyChangeListener, Runnable {
// ----------------------------------------------------- Instance Variables
/**
* The interval (in seconds) between checks for expired sessions.
*/
private int checkInterval = 60;
/**
* The descriptive information about this implementation.
*/
private static final String info = "PersistentManagerBase/1.0";
/**
* The lifecycle event support for this component.
*/
protected LifecycleSupport lifecycle = new LifecycleSupport(this);
/**
* The maximum number of active Sessions allowed, or -1 for no limit.
*/
private int maxActiveSessions = -1;
/**
* The descriptive name of this Manager implementation (for logging).
*/
protected static String name = "PersistentManagerBase";
/**
* Has this component been started yet?
*/
private boolean started = false;
/**
* The background thread.
*/
private Thread thread = null;
/**
* The background thread completion semaphore.
*/
protected boolean threadDone = false;
/**
* Name to register for the background thread.
*/
private String threadName = "PersistentManagerBase";
/**
* Store object which will manage the Session store.
*/
private Store store = null;
/**
* Whether to save and reload sessions when the Manager <code>unload</code>
* and <code>load</code> methods are called.
*/
private boolean saveOnRestart = true;
/**
* How long a session must be idle before it should be backed up.
* -1 means sessions won't be backed up.
*/
private int maxIdleBackup = -1;
/**
* Minimum time a session must be idle before it is swapped to disk.
* This overrides maxActiveSessions, to prevent thrashing if there are lots
* of active sessions. Setting to -1 means it's ignored.
*/
private int minIdleSwap = -1;
/**
* The maximum time a session may be idle before it should be swapped
* to file just on general principle. Setting this to -1 means sessions
* should not be forced out.
*/
private int maxIdleSwap = -1;
// ------------------------------------------------------------- Properties
/**
* Return the check interval (in seconds) for this Manager.
*/
public int getCheckInterval() {
return (this.checkInterval);
}
/**
* Set the check interval (in seconds) for this Manager.
*
* @param checkInterval The new check interval
*/
public void setCheckInterval(int checkInterval) {
int oldCheckInterval = this.checkInterval;
this.checkInterval = checkInterval;
support.firePropertyChange("checkInterval",
new Integer(oldCheckInterval),
new Integer(this.checkInterval));
}
/**
* Indicates how many seconds old a session can get, after its last
* use in a request, before it should be backed up to the store. -1
* means sessions are not backed up.
*/
public int getMaxIdleBackup() {
return maxIdleBackup;
}
/**
* Sets the option to back sessions up to the Store after they
* are used in a request. Sessions remain available in memory
* after being backed up, so they are not passivated as they are
* when swapped out. The value set indicates how old a session
* may get (since its last use) before it must be backed up: -1
* means sessions are not backed up.
* <p>
* Note that this is not a hard limit: sessions are checked
* against this age limit periodically according to <b>checkInterval</b>.
* This value should be considered to indicate when a session is
* ripe for backing up.
* <p>
* So it is possible that a session may be idle for maxIdleBackup +
* checkInterval seconds, plus the time it takes to handle other
* session expiration, swapping, etc. tasks.
*
* @param backup The number of seconds after their last accessed
* time when they should be written to the Store.
*/
public void setMaxIdleBackup (int backup) {
if (backup == this.maxIdleBackup)
return;
int oldBackup = this.maxIdleBackup;
this.maxIdleBackup = backup;
support.firePropertyChange("maxIdleBackup",
new Integer(oldBackup),
new Integer(this.maxIdleBackup));
}
/**
* The time in seconds after which a session should be swapped out of
* memory to disk.
*/
public int getMaxIdleSwap() {
return maxIdleSwap;
}
/**
* Sets the time in seconds after which a session should be swapped out of
* memory to disk.
*/
public void setMaxIdleSwap(int max) {
if (max == this.maxIdleSwap)
return;
int oldMaxIdleSwap = this.maxIdleSwap;
this.maxIdleSwap = max;
support.firePropertyChange("maxIdleSwap",
new Integer(oldMaxIdleSwap),
new Integer(this.maxIdleSwap));
}
/**
* The minimum time in seconds that a session must be idle before
* it can be swapped out of memory, or -1 if it can be swapped out
* at any time.
*/
public int getMinIdleSwap() {
return minIdleSwap;
}
/**
* Sets the minimum time in seconds that a session must be idle before
* it can be swapped out of memory due to maxActiveSession. Set it to -1
* if it can be swapped out at any time.
*/
public void setMinIdleSwap(int min) {
if (this.minIdleSwap == min)
return;
int oldMinIdleSwap = this.minIdleSwap;
this.minIdleSwap = min;
support.firePropertyChange("minIdleSwap",
new Integer(oldMinIdleSwap),
new Integer(this.minIdleSwap));
}
/**
* Set the Container with which this Manager has been associated. If
* it is a Context (the usual case), listen for changes to the session
* timeout property.
*
* @param container The associated Container
*/
public void setContainer(Container container) {
// De-register from the old Container (if any)
if ((this.container != null) && (this.container instanceof Context))
((Context) this.container).removePropertyChangeListener(this);
// Default processing provided by our superclass
super.setContainer(container);
// Register with the new Container (if any)
if ((this.container != null) && (this.container instanceof Context)) {
setMaxInactiveInterval
( ((Context) this.container).getSessionTimeout()*60 );
((Context) this.container).addPropertyChangeListener(this);
}
}
/**
* Return descriptive information about this Manager implementation and
* the corresponding version number, in the format
* <code><description>/<version></code>.
*/
public String getInfo() {
return (this.info);
}
/**
* Return the maximum number of active Sessions allowed, or -1 for
* no limit.
*/
public int getMaxActiveSessions() {
return (this.maxActiveSessions);
}
/**
* Set the maximum number of actives Sessions allowed, or -1 for
* no limit.
*
* @param max The new maximum number of sessions
*/
public void setMaxActiveSessions(int max) {
int oldMaxActiveSessions = this.maxActiveSessions;
this.maxActiveSessions = max;
support.firePropertyChange("maxActiveSessions",
new Integer(oldMaxActiveSessions),
new Integer(this.maxActiveSessions));
}
/**
* Return the descriptive short name of this Manager implementation.
*/
public String getName() {
return (name);
}
/**
* Get the started status.
*/
protected boolean isStarted() {
return started;
}
/**
* Set the started flag
*/
protected void setStarted(boolean started) {
this.started = started;
}
/**
* Set the Store object which will manage persistent Session
* storage for this Manager.
*
* @param store the associated Store
*/
public void setStore(Store store) {
this.store = store;
store.setManager(this);
}
/**
* Return the Store object which manages persistent Session
* storage for this Manager.
*/
public Store getStore() {
return (this.store);
}
/**
* Indicates whether sessions are saved when the Manager is shut down
* properly. This requires the unload() method to be called.
*/
public boolean getSaveOnRestart() {
return saveOnRestart;
}
/**
* Set the option to save sessions to the Store when the Manager is
* shut down, then loaded when the Manager starts again. If set to
* false, any sessions found in the Store may still be picked up when
* the Manager is started again.
*
* @param save true if sessions should be saved on restart, false if
* they should be ignored.
*/
public void setSaveOnRestart(boolean saveOnRestart) {
if (saveOnRestart == this.saveOnRestart)
return;
boolean oldSaveOnRestart = this.saveOnRestart;
this.saveOnRestart = saveOnRestart;
support.firePropertyChange("saveOnRestart",
new Boolean(oldSaveOnRestart),
new Boolean(this.saveOnRestart));
}
// --------------------------------------------------------- Public Methods
/**
* Clear all sessions from the Store.
*/
public void clearStore() {
if (store == null)
return;
try {
store.clear();
} catch (IOException e) {
log("Exception clearing the Store: " + e);
e.printStackTrace();
}
}
/**
* Called by the background thread after active sessions have
* been checked for expiration, to allow sessions to be
* swapped out, backed up, etc.
*/
public void processPersistenceChecks() {
processMaxIdleSwaps();
processMaxActiveSwaps();
processMaxIdleBackups();
}
/**
* Return a new session object as long as the number of active
* sessions does not exceed <b>maxActiveSessions</b>. If there
* aren't too many active sessions, or if there is no limit,
* a session is created or retrieved from the recycled pool.
*
* @exception IllegalStateException if a new session cannot be
* instantiated for any reason
*/
public Session createSession() {
if ((maxActiveSessions >= 0) &&
(sessions.size() >= maxActiveSessions))
throw new IllegalStateException
(sm.getString("standardManager.createSession.ise"));
return (super.createSession());
}
/**
* Return true, if the session id is loaded in memory
* otherwise false is returned
*
* @param id The session id for the session to be searched for
*
* @exception IOException if an input/output error occurs while
* processing this request
*/
public boolean isLoaded( String id ){
try {
if ( super.findSession(id) != null )
return true;
} catch (IOException e) {
log("checking isLoaded for id, " + id + ", "+e.getMessage(), e);
}
return false;
}
/**
* Return the active Session, associated with this Manager, with the
* specified session id (if any); otherwise return <code>null</code>.
* This method checks the persistence store if persistence is enabled,
* otherwise just uses the functionality from ManagerBase.
*
* @param id The session id for the session to be returned
*
* @exception IllegalStateException if a new session cannot be
* instantiated for any reason
* @exception IOException if an input/output error occurs while
* processing this request
*/
public Session findSession(String id) throws IOException {
Session session = super.findSession(id);
if (session != null)
return (session);
// See if the Session is in the Store
session = swapIn(id);
return (session);
}
/**
* Load all sessions found in the persistence mechanism, assuming
* they are marked as valid and have not passed their expiration
* limit. If persistence is not supported, this method returns
* without doing anything.
* <p>
* Note that by default, this method is not called by the MiddleManager
* class. In order to use it, a subclass must specifically call it,
* for example in the start() and/or processPersistenceChecks() methods.
*/
public void load() {
// Initialize our internal data structures
recycled.clear();
sessions.clear();
if (store == null)
return;
String[] ids = null;
try {
ids = store.keys();
} catch (IOException e) {
log("Can't load sessions from store, " + e.getMessage(), e);
return;
}
int n = ids.length;
if (n == 0)
return;
if (debug >= 1)
log(sm.getString("persistentManager.loading", String.valueOf(n)));
for (int i = 0; i < n; i++)
try {
swapIn(ids[i]);
} catch (IOException e) {
log("Failed load session from store, " + e.getMessage(), e);
}
}
/**
* Remove this Session from the active Sessions for this Manager,
* and from the Store.
*
* @param session Session to be removed
*/
public void remove(Session session) {
super.remove (session);
if (store != null)
try {
store.remove(session.getId());
} catch (IOException e) {
log("Exception removing session " + e.getMessage());
e.printStackTrace();
}
}
/**
* Save all currently active sessions in the appropriate persistence
* mechanism, if any. If persistence is not supported, this method
* returns without doing anything.
* <p>
* Note that by default, this method is not called by the MiddleManager
* class. In order to use it, a subclass must specifically call it,
* for example in the stop() and/or processPersistenceChecks() methods.
*/
public void unload() {
if (store == null)
return;
Session sessions[] = findSessions();
int n = sessions.length;
if (n == 0)
return;
if (debug >= 1)
log(sm.getString("persistentManager.unloading",
String.valueOf(n)));
for (int i = 0; i < n; i++)
try {
swapOut(sessions[i]);
} catch (IOException e) {
; // This is logged in writeSession()
}
}
// ------------------------------------------------------ Protected Methods
/**
* Look for a session in the Store and, if found, restore
* it in the Manager's list of active sessions if appropriate.
* The session will be removed from the Store after swapping
* in, but will not be added to the active session list if it
* is invalid or past its expiration.
*/
protected Session swapIn(String id) throws IOException {
if (store == null)
return null;
Session session = null;
try {
session = store.load(id);
} catch (ClassNotFoundException e) {
log(sm.getString("persistentManager.deserializeError", id, e));
throw new IllegalStateException
(sm.getString("persistentManager.deserializeError", id, e));
}
if (session == null)
return (null);
if (!session.isValid()
|| isSessionStale(session, System.currentTimeMillis())) {
log("session swapped in is invalid or expired");
session.expire();
store.remove(id);
return (null);
}
if(debug > 2)
log(sm.getString("persistentManager.swapIn", id));
session.setManager(this);
add(session);
((StandardSession)session).activate();
return (session);
}
/**
* Remove the session from the Manager's list of active
* sessions and write it out to the Store. If the session
* is past its expiration or invalid, this method does
* nothing.
*
* @param session The Session to write out.
*/
protected void swapOut(Session session) throws IOException {
if (store == null ||
!session.isValid() ||
isSessionStale(session, System.currentTimeMillis()))
return;
((StandardSession)session).passivate();
writeSession(session);
super.remove(session);
session.recycle();
}
/**
* Write the provided session to the Store without modifying
* the copy in memory or triggering passivation events. Does
* nothing if the session is invalid or past its expiration.
*/
protected void writeSession(Session session) throws IOException {
if (store == null ||
!session.isValid() ||
isSessionStale(session, System.currentTimeMillis()))
return;
try {
store.save(session);
} catch (IOException e) {
log(sm.getString
("persistentManager.serializeError", session.getId(), e));
throw e;
}
}
// ------------------------------------------------------ Lifecycle Methods
/**
* Add a lifecycle event listener to this component.
*
* @param listener The listener to add
*/
public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
/**
* Get the lifecycle listeners associated with this lifecycle. If this
* Lifecycle has no listeners registered, a zero-length array is returned.
*/
public LifecycleListener[] findLifecycleListeners() {
return lifecycle.findLifecycleListeners();
}
/**
* Remove a lifecycle event listener from this component.
*
* @param listener The listener to remove
*/
public void removeLifecycleListener(LifecycleListener listener) {
lifecycle.removeLifecycleListener(listener);
}
/**
* Prepare for the beginning of active use of the public methods of this
* component. This method should be called after <code>configure()</code>,
* and before any of the public methods of the component are utilized.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
public void start() throws LifecycleException {
if (debug >= 1)
log("Starting");
// Validate and update our current component state
if (started)
throw new LifecycleException
(sm.getString("standardManager.alreadyStarted"));
lifecycle.fireLifecycleEvent(START_EVENT, null);
started = true;
// Force initialization of the random number generator
if (debug >= 1)
log("Force random number initialization starting");
String dummy = generateSessionId();
if (debug >= 1)
log("Force random number initialization completed");
if (store == null)
log("No Store configured, persistence disabled");
else if (store instanceof Lifecycle)
((Lifecycle)store).start();
// Start the background reaper thread
threadStart();
}
/**
* Gracefully terminate the active use of the public methods of this
* component. This method should be the last one called on a given
* instance of this component.
*
* @exception LifecycleException if this component detects a fatal error
* that needs to be reported
*/
public void stop() throws LifecycleException {
if (debug >= 1)
log("Stopping");
// Validate and update our current component state
if (!isStarted())
throw new LifecycleException
(sm.getString("standardManager.notStarted"));
lifecycle.fireLifecycleEvent(STOP_EVENT, null);
setStarted(false);
// Stop the background reaper thread
threadStop();
if (getStore() != null && saveOnRestart) {
unload();
} else {
// Expire all active sessions
Session sessions[] = findSessions();
for (int i = 0; i < sessions.length; i++) {
StandardSession session = (StandardSession) sessions[i];
if (!session.isValid())
continue;
session.expire();
}
}
if (getStore() != null && getStore() instanceof Lifecycle)
((Lifecycle)getStore()).stop();
// Require a new random number generator if we are restarted
this.random = null;
}
// ----------------------------------------- PropertyChangeListener Methods
/**
* Process property change events from our associated Context.
*
* @param event The property change event that has occurred
*/
public void propertyChange(PropertyChangeEvent event) {
// Validate the source of this event
if (!(event.getSource() instanceof Context))
return;
Context context = (Context) event.getSource();
// Process a relevant property change
if (event.getPropertyName().equals("sessionTimeout")) {
try {
setMaxInactiveInterval
( ((Integer) event.getNewValue()).intValue()*60 );
} catch (NumberFormatException e) {
log(sm.getString("standardManager.sessionTimeout",
event.getNewValue().toString()));
}
}
}
// -------------------------------------------------------- Private Methods
/**
* Indicate whether the session has been idle for longer
* than its expiration date as of the supplied time.
*
* FIXME: Probably belongs in the Session class.
*/
protected boolean isSessionStale(Session session, long timeNow) {
int maxInactiveInterval = session.getMaxInactiveInterval();
if (maxInactiveInterval >= 0) {
int timeIdle = // Truncate, do not round up
(int) ((timeNow - session.getLastAccessedTime()) / 1000L);
if (timeIdle >= maxInactiveInterval)
return true;
}
return false;
}
/**
* Invalidate all sessions that have expired.
*/
protected void processExpires() {
if (!started)
return;
long timeNow = System.currentTimeMillis();
Session sessions[] = findSessions();
for (int i = 0; i < sessions.length; i++) {
StandardSession session = (StandardSession) sessions[i];
if (!session.isValid())
continue;
if (isSessionStale(session, timeNow))
session.expire();
}
}
/**
* Swap idle sessions out to Store if they are idle too long.
*/
protected void processMaxIdleSwaps() {
if (!isStarted() || maxIdleSwap < 0)
return;
Session sessions[] = findSessions();
long timeNow = System.currentTimeMillis();
// Swap out all sessions idle longer than maxIdleSwap
// FIXME: What's preventing us from mangling a session during
// a request?
if (maxIdleSwap >= 0) {
for (int i = 0; i < sessions.length; i++) {
StandardSession session = (StandardSession) sessions[i];
if (!session.isValid())
continue;
int timeIdle = // Truncate, do not round up
(int) ((timeNow - session.getLastAccessedTime()) / 1000L);
if (timeIdle > maxIdleSwap && timeIdle > minIdleSwap) {
if (debug > 1)
log(sm.getString
("persistentManager.swapMaxIdle",
session.getId(), new Integer(timeIdle)));
try {
swapOut(session);
} catch (IOException e) {
; // This is logged in writeSession()
}
}
}
}
}
/**
* Swap idle sessions out to Store if too many are active
*/
protected void processMaxActiveSwaps() {
if (!isStarted() || getMaxActiveSessions() < 0)
return;
Session sessions[] = findSessions();
// FIXME: Smarter algorithm (LRU)
if (getMaxActiveSessions() >= sessions.length)
return;
if(debug > 0)
log(sm.getString
("persistentManager.tooManyActive",
new Integer(sessions.length)));
int toswap = sessions.length - getMaxActiveSessions();
long timeNow = System.currentTimeMillis();
for (int i = 0; i < sessions.length && toswap > 0; i++) {
int timeIdle = // Truncate, do not round up
(int) ((timeNow - sessions[i].getLastAccessedTime()) / 1000L);
if (timeIdle > minIdleSwap) {
if(debug > 1)
log(sm.getString
("persistentManager.swapTooManyActive",
sessions[i].getId(), new Integer(timeIdle)));
try {
swapOut(sessions[i]);
} catch (IOException e) {
; // This is logged in writeSession()
}
toswap--;
}
}
}
/**
* Back up idle sessions.
*/
protected void processMaxIdleBackups() {
if (!isStarted() || maxIdleBackup < 0)
return;
Session sessions[] = findSessions();
long timeNow = System.currentTimeMillis();
// Back up all sessions idle longer than maxIdleBackup
if (maxIdleBackup >= 0) {
for (int i = 0; i < sessions.length; i++) {
StandardSession session = (StandardSession) sessions[i];
if (!session.isValid())
continue;
int timeIdle = // Truncate, do not round up
(int) ((timeNow - session.getLastAccessedTime()) / 1000L);
if (timeIdle > maxIdleBackup) {
if (debug > 1)
log(sm.getString
("persistentManager.backupMaxIdle",
session.getId(), new Integer(timeIdle)));
try {
writeSession(session);
} catch (IOException e) {
; // This is logged in writeSession()
}
}
}
}
}
/**
* Sleep for the duration specified by the <code>checkInterval</code>
* property.
*/
protected void threadSleep() {
try {
Thread.sleep(checkInterval * 1000L);
} catch (InterruptedException e) {
;
}
}
/**
* Start the background thread that will periodically check for
* session timeouts.
*/
protected void threadStart() {
if (thread != null)
return;
threadDone = false;
threadName = "StandardManager[" + container.getName() + "]";
thread = new Thread(this, threadName);
thread.setDaemon(true);
thread.start();
}
/**
* Stop the background thread that is periodically checking for
* session timeouts.
*/
protected void threadStop() {
if (thread == null)
return;
threadDone = true;
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
;
}
thread = null;
}
// ------------------------------------------------------ Background Thread
/**
* The background thread that checks for session timeouts and shutdown.
*/
public void run() {
// Loop until the termination semaphore is set
while (!threadDone) {
threadSleep();
processExpires();
processPersistenceChecks();
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.impl;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
import org.apache.pulsar.client.impl.conf.ConsumerConfigurationData;
import org.apache.pulsar.client.util.TimedCompletableFuture;
import org.apache.pulsar.common.api.proto.CommandAck.AckType;
import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap;
import org.apache.pulsar.common.api.proto.ProtocolVersion;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class AcknowledgementsGroupingTrackerTest {
private ClientCnx cnx;
private ConsumerImpl<?> consumer;
private EventLoopGroup eventLoopGroup;
@BeforeClass
public void setup() throws NoSuchFieldException, IllegalAccessException {
eventLoopGroup = new NioEventLoopGroup(1);
consumer = mock(ConsumerImpl.class);
consumer.unAckedChunkedMessageIdSequenceMap = new ConcurrentOpenHashMap<>();
cnx = spy(new ClientCnxTest(new ClientConfigurationData(), new NioEventLoopGroup()));
PulsarClientImpl client = mock(PulsarClientImpl.class);
doReturn(client).when(consumer).getClient();
doReturn(cnx).when(consumer).getClientCnx();
doReturn(new ConsumerStatsRecorderImpl()).when(consumer).getStats();
doReturn(new UnAckedMessageTracker().UNACKED_MESSAGE_TRACKER_DISABLED)
.when(consumer).getUnAckedMessageTracker();
ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
when(cnx.ctx()).thenReturn(ctx);
}
@DataProvider(name = "isNeedReceipt")
public Object[][] isNeedReceipt() {
return new Object[][] { { Boolean.TRUE }, { Boolean.FALSE } };
}
@AfterClass(alwaysRun = true)
public void teardown() {
eventLoopGroup.shutdownGracefully();
}
@Test(dataProvider = "isNeedReceipt")
public void testAckTracker(boolean isNeedReceipt) throws Exception {
ConsumerConfigurationData<?> conf = new ConsumerConfigurationData<>();
conf.setAcknowledgementsGroupTimeMicros(TimeUnit.SECONDS.toMicros(10));
conf.setAckReceiptEnabled(isNeedReceipt);
AcknowledgmentsGroupingTracker tracker;
tracker = new PersistentAcknowledgmentsGroupingTracker(consumer, conf, eventLoopGroup);
MessageIdImpl msg1 = new MessageIdImpl(5, 1, 0);
MessageIdImpl msg2 = new MessageIdImpl(5, 2, 0);
MessageIdImpl msg3 = new MessageIdImpl(5, 3, 0);
MessageIdImpl msg4 = new MessageIdImpl(5, 4, 0);
MessageIdImpl msg5 = new MessageIdImpl(5, 5, 0);
MessageIdImpl msg6 = new MessageIdImpl(5, 6, 0);
assertFalse(tracker.isDuplicate(msg1));
tracker.addAcknowledgment(msg1, AckType.Individual, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg1));
assertFalse(tracker.isDuplicate(msg2));
tracker.addAcknowledgment(msg5, AckType.Cumulative, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
// Flush while disconnected. the internal tracking will not change
tracker.flush();
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
tracker.addAcknowledgment(msg6, AckType.Individual, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg6));
when(consumer.getClientCnx()).thenReturn(cnx);
tracker.flush();
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
tracker.close();
}
@Test(dataProvider = "isNeedReceipt")
public void testBatchAckTracker(boolean isNeedReceipt) throws Exception {
ConsumerConfigurationData<?> conf = new ConsumerConfigurationData<>();
conf.setAcknowledgementsGroupTimeMicros(TimeUnit.SECONDS.toMicros(10));
conf.setAckReceiptEnabled(isNeedReceipt);
AcknowledgmentsGroupingTracker tracker;
tracker = new PersistentAcknowledgmentsGroupingTracker(consumer, conf, eventLoopGroup);
MessageIdImpl msg1 = new MessageIdImpl(5, 1, 0);
MessageIdImpl msg2 = new MessageIdImpl(5, 2, 0);
MessageIdImpl msg3 = new MessageIdImpl(5, 3, 0);
MessageIdImpl msg4 = new MessageIdImpl(5, 4, 0);
MessageIdImpl msg5 = new MessageIdImpl(5, 5, 0);
MessageIdImpl msg6 = new MessageIdImpl(5, 6, 0);
assertFalse(tracker.isDuplicate(msg1));
tracker.addListAcknowledgment(Collections.singletonList(msg1), AckType.Individual, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg1));
assertFalse(tracker.isDuplicate(msg2));
tracker.addListAcknowledgment(Collections.singletonList(msg5), AckType.Cumulative, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
// Flush while disconnected. the internal tracking will not change
tracker.flush();
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
tracker.addListAcknowledgment(Collections.singletonList(msg6), AckType.Individual, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg6));
when(consumer.getClientCnx()).thenReturn(cnx);
tracker.flush();
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
tracker.close();
}
@Test(dataProvider = "isNeedReceipt")
public void testImmediateAckingTracker(boolean isNeedReceipt) throws Exception {
ConsumerConfigurationData<?> conf = new ConsumerConfigurationData<>();
conf.setAcknowledgementsGroupTimeMicros(0);
conf.setAckReceiptEnabled(isNeedReceipt);
AcknowledgmentsGroupingTracker tracker;
tracker = new PersistentAcknowledgmentsGroupingTracker(consumer, conf, eventLoopGroup);
MessageIdImpl msg1 = new MessageIdImpl(5, 1, 0);
MessageIdImpl msg2 = new MessageIdImpl(5, 2, 0);
assertFalse(tracker.isDuplicate(msg1));
when(consumer.getClientCnx()).thenReturn(null);
tracker.addAcknowledgment(msg1, AckType.Individual, Collections.emptyMap());
assertFalse(tracker.isDuplicate(msg1));
when(consumer.getClientCnx()).thenReturn(cnx);
tracker.flush();
assertFalse(tracker.isDuplicate(msg1));
tracker.addAcknowledgment(msg2, AckType.Individual, Collections.emptyMap());
// Since we were connected, the ack went out immediately
assertFalse(tracker.isDuplicate(msg2));
tracker.close();
}
@Test(dataProvider = "isNeedReceipt")
public void testImmediateBatchAckingTracker(boolean isNeedReceipt) throws Exception {
ConsumerConfigurationData<?> conf = new ConsumerConfigurationData<>();
conf.setAcknowledgementsGroupTimeMicros(0);
conf.setAckReceiptEnabled(isNeedReceipt);
AcknowledgmentsGroupingTracker tracker;
tracker = new PersistentAcknowledgmentsGroupingTracker(consumer, conf, eventLoopGroup);
MessageIdImpl msg1 = new MessageIdImpl(5, 1, 0);
MessageIdImpl msg2 = new MessageIdImpl(5, 2, 0);
assertFalse(tracker.isDuplicate(msg1));
when(consumer.getClientCnx()).thenReturn(null);
tracker.addListAcknowledgment(Collections.singletonList(msg1), AckType.Individual, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg1));
when(consumer.getClientCnx()).thenReturn(cnx);
tracker.flush();
assertFalse(tracker.isDuplicate(msg1));
tracker.addListAcknowledgment(Collections.singletonList(msg2), AckType.Individual, Collections.emptyMap());
tracker.flush();
// Since we were connected, the ack went out immediately
assertFalse(tracker.isDuplicate(msg2));
tracker.close();
}
@Test(dataProvider = "isNeedReceipt")
public void testAckTrackerMultiAck(boolean isNeedReceipt) {
ConsumerConfigurationData<?> conf = new ConsumerConfigurationData<>();
conf.setAcknowledgementsGroupTimeMicros(TimeUnit.SECONDS.toMicros(10));
conf.setAckReceiptEnabled(isNeedReceipt);
AcknowledgmentsGroupingTracker tracker;
tracker = new PersistentAcknowledgmentsGroupingTracker(consumer, conf, eventLoopGroup);
when(cnx.getRemoteEndpointProtocolVersion()).thenReturn(ProtocolVersion.v12_VALUE);
MessageIdImpl msg1 = new MessageIdImpl(5, 1, 0);
MessageIdImpl msg2 = new MessageIdImpl(5, 2, 0);
MessageIdImpl msg3 = new MessageIdImpl(5, 3, 0);
MessageIdImpl msg4 = new MessageIdImpl(5, 4, 0);
MessageIdImpl msg5 = new MessageIdImpl(5, 5, 0);
MessageIdImpl msg6 = new MessageIdImpl(5, 6, 0);
assertFalse(tracker.isDuplicate(msg1));
tracker.addAcknowledgment(msg1, AckType.Individual, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg1));
assertFalse(tracker.isDuplicate(msg2));
tracker.addAcknowledgment(msg5, AckType.Cumulative, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
// Flush while disconnected. the internal tracking will not change
tracker.flush();
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
tracker.addAcknowledgment(msg6, AckType.Individual, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg6));
when(consumer.getClientCnx()).thenReturn(cnx);
tracker.flush();
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
tracker.close();
}
@Test(dataProvider = "isNeedReceipt")
public void testBatchAckTrackerMultiAck(boolean isNeedReceipt) throws Exception {
ConsumerConfigurationData<?> conf = new ConsumerConfigurationData<>();
conf.setAcknowledgementsGroupTimeMicros(TimeUnit.SECONDS.toMicros(10));
conf.setAckReceiptEnabled(isNeedReceipt);
AcknowledgmentsGroupingTracker tracker;
tracker = new PersistentAcknowledgmentsGroupingTracker(consumer, conf, eventLoopGroup);
when(cnx.getRemoteEndpointProtocolVersion()).thenReturn(ProtocolVersion.v12_VALUE);
MessageIdImpl msg1 = new MessageIdImpl(5, 1, 0);
MessageIdImpl msg2 = new MessageIdImpl(5, 2, 0);
MessageIdImpl msg3 = new MessageIdImpl(5, 3, 0);
MessageIdImpl msg4 = new MessageIdImpl(5, 4, 0);
MessageIdImpl msg5 = new MessageIdImpl(5, 5, 0);
MessageIdImpl msg6 = new MessageIdImpl(5, 6, 0);
assertFalse(tracker.isDuplicate(msg1));
tracker.addListAcknowledgment(Collections.singletonList(msg1), AckType.Individual, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg1));
assertFalse(tracker.isDuplicate(msg2));
tracker.addListAcknowledgment(Collections.singletonList(msg5), AckType.Cumulative, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
// Flush while disconnected. the internal tracking will not change
tracker.flush();
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
tracker.addListAcknowledgment(Collections.singletonList(msg6), AckType.Individual, Collections.emptyMap());
assertTrue(tracker.isDuplicate(msg6));
when(consumer.getClientCnx()).thenReturn(cnx);
tracker.flush();
assertTrue(tracker.isDuplicate(msg1));
assertTrue(tracker.isDuplicate(msg2));
assertTrue(tracker.isDuplicate(msg3));
assertTrue(tracker.isDuplicate(msg4));
assertTrue(tracker.isDuplicate(msg5));
assertFalse(tracker.isDuplicate(msg6));
tracker.close();
}
public class ClientCnxTest extends ClientCnx {
public ClientCnxTest(ClientConfigurationData conf, EventLoopGroup eventLoopGroup) {
super(conf, eventLoopGroup);
}
@Override
public CompletableFuture<Void> newAckForReceipt(ByteBuf request, long requestId) {
return CompletableFuture.completedFuture(null);
}
@Override
public void newAckForReceiptWithFuture(ByteBuf request, long requestId,
TimedCompletableFuture<Void> future) {
}
}
}
| |
package org.ripple.bouncycastle.bcpg;
import org.ripple.bouncycastle.bcpg.sig.IssuerKeyID;
import org.ripple.bouncycastle.bcpg.sig.SignatureCreationTime;
import org.ripple.bouncycastle.util.Arrays;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Vector;
/**
* generic signature packet
*/
public class SignaturePacket
extends ContainedPacket implements PublicKeyAlgorithmTags
{
private int version;
private int signatureType;
private long creationTime;
private long keyID;
private int keyAlgorithm;
private int hashAlgorithm;
private MPInteger[] signature;
private byte[] fingerPrint;
private SignatureSubpacket[] hashedData;
private SignatureSubpacket[] unhashedData;
private byte[] signatureEncoding;
SignaturePacket(
BCPGInputStream in)
throws IOException
{
version = in.read();
if (version == 3 || version == 2)
{
int l = in.read();
signatureType = in.read();
creationTime = (((long)in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read()) * 1000;
keyID |= (long)in.read() << 56;
keyID |= (long)in.read() << 48;
keyID |= (long)in.read() << 40;
keyID |= (long)in.read() << 32;
keyID |= (long)in.read() << 24;
keyID |= (long)in.read() << 16;
keyID |= (long)in.read() << 8;
keyID |= in.read();
keyAlgorithm = in.read();
hashAlgorithm = in.read();
}
else if (version == 4)
{
signatureType = in.read();
keyAlgorithm = in.read();
hashAlgorithm = in.read();
int hashedLength = (in.read() << 8) | in.read();
byte[] hashed = new byte[hashedLength];
in.readFully(hashed);
//
// read the signature sub packet data.
//
SignatureSubpacket sub;
SignatureSubpacketInputStream sIn = new SignatureSubpacketInputStream(
new ByteArrayInputStream(hashed));
Vector v = new Vector();
while ((sub = sIn.readPacket()) != null)
{
v.addElement(sub);
}
hashedData = new SignatureSubpacket[v.size()];
for (int i = 0; i != hashedData.length; i++)
{
SignatureSubpacket p = (SignatureSubpacket)v.elementAt(i);
if (p instanceof IssuerKeyID)
{
keyID = ((IssuerKeyID)p).getKeyID();
}
else if (p instanceof SignatureCreationTime)
{
creationTime = ((SignatureCreationTime)p).getTime().getTime();
}
hashedData[i] = p;
}
int unhashedLength = (in.read() << 8) | in.read();
byte[] unhashed = new byte[unhashedLength];
in.readFully(unhashed);
sIn = new SignatureSubpacketInputStream(
new ByteArrayInputStream(unhashed));
v.removeAllElements();
while ((sub = sIn.readPacket()) != null)
{
v.addElement(sub);
}
unhashedData = new SignatureSubpacket[v.size()];
for (int i = 0; i != unhashedData.length; i++)
{
SignatureSubpacket p = (SignatureSubpacket)v.elementAt(i);
if (p instanceof IssuerKeyID)
{
keyID = ((IssuerKeyID)p).getKeyID();
}
unhashedData[i] = p;
}
}
else
{
throw new RuntimeException("unsupported version: " + version);
}
fingerPrint = new byte[2];
in.readFully(fingerPrint);
switch (keyAlgorithm)
{
case RSA_GENERAL:
case RSA_SIGN:
MPInteger v = new MPInteger(in);
signature = new MPInteger[1];
signature[0] = v;
break;
case DSA:
MPInteger r = new MPInteger(in);
MPInteger s = new MPInteger(in);
signature = new MPInteger[2];
signature[0] = r;
signature[1] = s;
break;
case ELGAMAL_ENCRYPT: // yep, this really does happen sometimes.
case ELGAMAL_GENERAL:
MPInteger p = new MPInteger(in);
MPInteger g = new MPInteger(in);
MPInteger y = new MPInteger(in);
signature = new MPInteger[3];
signature[0] = p;
signature[1] = g;
signature[2] = y;
break;
default:
if (keyAlgorithm >= PublicKeyAlgorithmTags.EXPERIMENTAL_1 && keyAlgorithm <= PublicKeyAlgorithmTags.EXPERIMENTAL_11)
{
signature = null;
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
int ch;
while ((ch = in.read()) >= 0)
{
bOut.write(ch);
}
signatureEncoding = bOut.toByteArray();
}
else
{
throw new IOException("unknown signature key algorithm: " + keyAlgorithm);
}
}
}
/**
* Generate a version 4 signature packet.
*
* @param signatureType
* @param keyAlgorithm
* @param hashAlgorithm
* @param hashedData
* @param unhashedData
* @param fingerPrint
* @param signature
*/
public SignaturePacket(
int signatureType,
long keyID,
int keyAlgorithm,
int hashAlgorithm,
SignatureSubpacket[] hashedData,
SignatureSubpacket[] unhashedData,
byte[] fingerPrint,
MPInteger[] signature)
{
this(4, signatureType, keyID, keyAlgorithm, hashAlgorithm, hashedData, unhashedData, fingerPrint, signature);
}
/**
* Generate a version 2/3 signature packet.
*
* @param signatureType
* @param keyAlgorithm
* @param hashAlgorithm
* @param fingerPrint
* @param signature
*/
public SignaturePacket(
int version,
int signatureType,
long keyID,
int keyAlgorithm,
int hashAlgorithm,
long creationTime,
byte[] fingerPrint,
MPInteger[] signature)
{
this(version, signatureType, keyID, keyAlgorithm, hashAlgorithm, null, null, fingerPrint, signature);
this.creationTime = creationTime;
}
public SignaturePacket(
int version,
int signatureType,
long keyID,
int keyAlgorithm,
int hashAlgorithm,
SignatureSubpacket[] hashedData,
SignatureSubpacket[] unhashedData,
byte[] fingerPrint,
MPInteger[] signature)
{
this.version = version;
this.signatureType = signatureType;
this.keyID = keyID;
this.keyAlgorithm = keyAlgorithm;
this.hashAlgorithm = hashAlgorithm;
this.hashedData = hashedData;
this.unhashedData = unhashedData;
this.fingerPrint = fingerPrint;
this.signature = signature;
if (hashedData != null)
{
setCreationTime();
}
}
/**
* get the version number
*/
public int getVersion()
{
return version;
}
/**
* return the signature type.
*/
public int getSignatureType()
{
return signatureType;
}
/**
* return the keyID
* @return the keyID that created the signature.
*/
public long getKeyID()
{
return keyID;
}
/**
* return the signature trailer that must be included with the data
* to reconstruct the signature
*
* @return byte[]
*/
public byte[] getSignatureTrailer()
{
byte[] trailer = null;
if (version == 3 || version == 2)
{
trailer = new byte[5];
long time = creationTime / 1000;
trailer[0] = (byte)signatureType;
trailer[1] = (byte)(time >> 24);
trailer[2] = (byte)(time >> 16);
trailer[3] = (byte)(time >> 8);
trailer[4] = (byte)(time);
}
else
{
ByteArrayOutputStream sOut = new ByteArrayOutputStream();
try
{
sOut.write((byte)this.getVersion());
sOut.write((byte)this.getSignatureType());
sOut.write((byte)this.getKeyAlgorithm());
sOut.write((byte)this.getHashAlgorithm());
ByteArrayOutputStream hOut = new ByteArrayOutputStream();
SignatureSubpacket[] hashed = this.getHashedSubPackets();
for (int i = 0; i != hashed.length; i++)
{
hashed[i].encode(hOut);
}
byte[] data = hOut.toByteArray();
sOut.write((byte)(data.length >> 8));
sOut.write((byte)data.length);
sOut.write(data);
byte[] hData = sOut.toByteArray();
sOut.write((byte)this.getVersion());
sOut.write((byte)0xff);
sOut.write((byte)(hData.length>> 24));
sOut.write((byte)(hData.length >> 16));
sOut.write((byte)(hData.length >> 8));
sOut.write((byte)(hData.length));
}
catch (IOException e)
{
throw new RuntimeException("exception generating trailer: " + e);
}
trailer = sOut.toByteArray();
}
return trailer;
}
/**
* return the encryption algorithm tag
*/
public int getKeyAlgorithm()
{
return keyAlgorithm;
}
/**
* return the hashAlgorithm tag
*/
public int getHashAlgorithm()
{
return hashAlgorithm;
}
/**
* return the signature as a set of integers - note this is normalised to be the
* ASN.1 encoding of what appears in the signature packet.
*/
public MPInteger[] getSignature()
{
return signature;
}
/**
* Return the byte encoding of the signature section.
* @return uninterpreted signature bytes.
*/
public byte[] getSignatureBytes()
{
if (signatureEncoding == null)
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
BCPGOutputStream bcOut = new BCPGOutputStream(bOut);
for (int i = 0; i != signature.length; i++)
{
try
{
bcOut.writeObject(signature[i]);
}
catch (IOException e)
{
throw new RuntimeException("internal error: " + e);
}
}
return bOut.toByteArray();
}
else
{
return Arrays.clone(signatureEncoding);
}
}
public SignatureSubpacket[] getHashedSubPackets()
{
return hashedData;
}
public SignatureSubpacket[] getUnhashedSubPackets()
{
return unhashedData;
}
/**
* Return the creation time of the signature in milli-seconds.
*
* @return the creation time in millis
*/
public long getCreationTime()
{
return creationTime;
}
public void encode(
BCPGOutputStream out)
throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
BCPGOutputStream pOut = new BCPGOutputStream(bOut);
pOut.write(version);
if (version == 3 || version == 2)
{
pOut.write(5); // the length of the next block
long time = creationTime / 1000;
pOut.write(signatureType);
pOut.write((byte)(time >> 24));
pOut.write((byte)(time >> 16));
pOut.write((byte)(time >> 8));
pOut.write((byte)time);
pOut.write((byte)(keyID >> 56));
pOut.write((byte)(keyID >> 48));
pOut.write((byte)(keyID >> 40));
pOut.write((byte)(keyID >> 32));
pOut.write((byte)(keyID >> 24));
pOut.write((byte)(keyID >> 16));
pOut.write((byte)(keyID >> 8));
pOut.write((byte)(keyID));
pOut.write(keyAlgorithm);
pOut.write(hashAlgorithm);
}
else if (version == 4)
{
pOut.write(signatureType);
pOut.write(keyAlgorithm);
pOut.write(hashAlgorithm);
ByteArrayOutputStream sOut = new ByteArrayOutputStream();
for (int i = 0; i != hashedData.length; i++)
{
hashedData[i].encode(sOut);
}
byte[] data = sOut.toByteArray();
pOut.write(data.length >> 8);
pOut.write(data.length);
pOut.write(data);
sOut.reset();
for (int i = 0; i != unhashedData.length; i++)
{
unhashedData[i].encode(sOut);
}
data = sOut.toByteArray();
pOut.write(data.length >> 8);
pOut.write(data.length);
pOut.write(data);
}
else
{
throw new IOException("unknown version: " + version);
}
pOut.write(fingerPrint);
if (signature != null)
{
for (int i = 0; i != signature.length; i++)
{
pOut.writeObject(signature[i]);
}
}
else
{
pOut.write(signatureEncoding);
}
out.writePacket(SIGNATURE, bOut.toByteArray(), true);
}
private void setCreationTime()
{
for (int i = 0; i != hashedData.length; i++)
{
if (hashedData[i] instanceof SignatureCreationTime)
{
creationTime = ((SignatureCreationTime)hashedData[i]).getTime().getTime();
break;
}
}
}
}
| |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.swift;
import static com.facebook.buck.util.environment.Platform.WINDOWS;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeThat;
import com.facebook.buck.apple.AppleNativeIntegrationTestUtils;
import com.facebook.buck.apple.FakeAppleRuleDescriptions;
import com.facebook.buck.apple.toolchain.ApplePlatform;
import com.facebook.buck.core.build.buildable.context.FakeBuildableContext;
import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.build.context.FakeBuildContext;
import com.facebook.buck.core.cell.name.CanonicalCellName;
import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.core.config.FakeBuckConfig;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.model.targetgraph.FakeTargetNodeBuilder;
import com.facebook.buck.core.model.targetgraph.TargetGraph;
import com.facebook.buck.core.model.targetgraph.TargetGraphFactory;
import com.facebook.buck.core.model.targetgraph.TestBuildRuleCreationContextFactory;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.TestBuildRuleParams;
import com.facebook.buck.core.rules.impl.FakeBuildRule;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.CxxLink;
import com.facebook.buck.cxx.FakeCxxLibrary;
import com.facebook.buck.cxx.HeaderSymlinkTreeWithHeaderMap;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.parser.exceptions.NoSuchBuildTargetException;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.FileListableLinkerInputArg;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.step.Step;
import com.facebook.buck.testutil.ProcessResult;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.environment.Platform;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public class SwiftLibraryIntegrationTest {
@Rule public final TemporaryPaths tmpDir = new TemporaryPaths();
private ActionGraphBuilder graphBuilder;
private SourcePathResolverAdapter pathResolver;
@Before
public void setUp() {
assumeThat(Platform.detect(), is(not(WINDOWS)));
graphBuilder = new TestActionGraphBuilder();
pathResolver = graphBuilder.getSourcePathResolver();
}
@Test
public void headersOfDependentTargetsAreIncluded() {
// The output path used by the buildable for the link tree.
BuildTarget symlinkTarget = BuildTargetFactory.newInstance("//:symlink");
ProjectFilesystem projectFilesystem =
new FakeProjectFilesystem(CanonicalCellName.rootCell(), tmpDir.getRoot());
Path symlinkTreeRoot =
BuildTargetPaths.getGenPath(projectFilesystem, symlinkTarget, "%s/symlink-tree-root");
// Setup the map representing the link tree.
ImmutableMap<Path, SourcePath> links = ImmutableMap.of();
HeaderSymlinkTreeWithHeaderMap symlinkTreeBuildRule =
HeaderSymlinkTreeWithHeaderMap.create(
symlinkTarget, projectFilesystem, symlinkTreeRoot, links);
graphBuilder.addToIndex(symlinkTreeBuildRule);
BuildTarget libTarget = BuildTargetFactory.newInstance("//:lib");
BuildRuleParams libParams = TestBuildRuleParams.create();
FakeCxxLibrary depRule =
new FakeCxxLibrary(
libTarget,
new FakeProjectFilesystem(),
libParams,
BuildTargetFactory.newInstance("//:header"),
symlinkTarget,
BuildTargetFactory.newInstance("//:privateheader"),
BuildTargetFactory.newInstance("//:privatesymlink"),
new FakeBuildRule("//:archive"),
new FakeBuildRule("//:shared"),
Paths.get("output/path/lib.so"),
"lib.so",
ImmutableSortedSet.of());
BuildTarget buildTarget = BuildTargetFactory.newInstance("//foo:bar#iphoneos-x86_64");
BuildRuleParams params =
TestBuildRuleParams.create().withDeclaredDeps(ImmutableSortedSet.of(depRule));
SwiftLibraryDescriptionArg args = createDummySwiftArg();
SwiftCompile buildRule =
(SwiftCompile)
FakeAppleRuleDescriptions.SWIFT_LIBRARY_DESCRIPTION.createBuildRule(
TestBuildRuleCreationContextFactory.create(graphBuilder, projectFilesystem),
buildTarget,
params,
args);
ImmutableList<String> swiftIncludeArgs = buildRule.getSwiftIncludeArgs(pathResolver);
assertThat(swiftIncludeArgs.size(), Matchers.equalTo(2));
assertThat(swiftIncludeArgs.get(0), Matchers.equalTo("-I"));
assertThat(swiftIncludeArgs.get(1), Matchers.endsWith("symlink.hmap"));
}
@Test
public void testSwiftCompileAndLinkArgs() throws NoSuchBuildTargetException {
BuildTarget buildTarget = BuildTargetFactory.newInstance("//foo:bar#iphoneos-x86_64");
BuildTarget swiftCompileTarget =
buildTarget.withAppendedFlavors(SwiftLibraryDescription.SWIFT_COMPILE_FLAVOR);
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
BuildRuleParams params = TestBuildRuleParams.create();
SwiftLibraryDescriptionArg args = createDummySwiftArg();
SwiftCompile buildRule =
(SwiftCompile)
FakeAppleRuleDescriptions.SWIFT_LIBRARY_DESCRIPTION.createBuildRule(
TestBuildRuleCreationContextFactory.create(graphBuilder, projectFilesystem),
swiftCompileTarget,
params,
args);
graphBuilder.addToIndex(buildRule);
ImmutableList<Arg> astArgs = buildRule.getAstLinkArgs();
assertThat(astArgs, Matchers.hasSize(3));
assertThat(astArgs.get(0), Matchers.equalTo(StringArg.of("-Xlinker")));
assertThat(astArgs.get(1), Matchers.equalTo(StringArg.of("-add_ast_path")));
assertThat(astArgs.get(2), Matchers.instanceOf(SourcePathArg.class));
SourcePathArg sourcePathArg = (SourcePathArg) astArgs.get(2);
assertThat(
sourcePathArg.getPath(),
Matchers.equalTo(
ExplicitBuildTargetSourcePath.of(
swiftCompileTarget,
pathResolver
.getRelativePath(buildRule.getSourcePathToOutput())
.resolve("bar.swiftmodule"))));
Arg objArg = buildRule.getFileListLinkArg().get(0);
assertThat(objArg, Matchers.instanceOf(FileListableLinkerInputArg.class));
FileListableLinkerInputArg fileListArg = (FileListableLinkerInputArg) objArg;
ExplicitBuildTargetSourcePath fileListSourcePath =
ExplicitBuildTargetSourcePath.of(
swiftCompileTarget,
pathResolver.getRelativePath(buildRule.getSourcePathToOutput()).resolve("bar.o"));
assertThat(fileListArg.getPath(), Matchers.equalTo(fileListSourcePath));
TargetGraph targetGraph =
TargetGraphFactory.newInstance(FakeTargetNodeBuilder.build(buildRule));
CxxLink linkRule =
(CxxLink)
FakeAppleRuleDescriptions.SWIFT_LIBRARY_DESCRIPTION.createBuildRule(
TestBuildRuleCreationContextFactory.create(
targetGraph, graphBuilder, projectFilesystem),
buildTarget.withAppendedFlavors(CxxDescriptionEnhancer.SHARED_FLAVOR),
params,
args);
assertThat(linkRule.getArgs(), Matchers.hasItem(objArg));
assertThat(
linkRule.getArgs(), Matchers.not(Matchers.hasItem(SourcePathArg.of(fileListSourcePath))));
}
@Test
public void testBridgingHeaderTracking() throws Exception {
assumeThat(
AppleNativeIntegrationTestUtils.isSwiftAvailable(ApplePlatform.IPHONESIMULATOR), is(true));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "bridging_header_tracking", tmpDir);
workspace.setUp();
workspace.addBuckConfigLocalOption("cxx", "untracked_headers", "error");
BuildTarget target = workspace.newBuildTarget("//:BigLib#iphonesimulator-x86_64,static");
ProcessResult result = workspace.runBuckCommand("build", target.getFullyQualifiedName());
result.assertSuccess();
}
@Test
public void testBridgingHeaderTrackingTransitive() throws Exception {
assumeThat(
AppleNativeIntegrationTestUtils.isSwiftAvailable(ApplePlatform.IPHONESIMULATOR), is(true));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "bridging_header_tracking", tmpDir);
workspace.setUp();
workspace.addBuckConfigLocalOption("cxx", "untracked_headers", "error");
BuildTarget target =
workspace.newBuildTarget("//:BigLibTransitive#iphonesimulator-x86_64,static");
ProcessResult result = workspace.runBuckCommand("build", target.getFullyQualifiedName());
result.assertSuccess();
}
@Test
public void testGlobalFlagsInRuleKey() throws Exception {
assumeThat(
AppleNativeIntegrationTestUtils.isSwiftAvailable(ApplePlatform.IPHONESIMULATOR), is(true));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "helloworld", tmpDir);
workspace.setUp();
BuildTarget target = workspace.newBuildTarget("//:hello#iphonesimulator-x86_64,swift-compile");
ProcessResult result = workspace.runBuckCommand("build", target.getFullyQualifiedName());
result.assertSuccess();
workspace
.getBuildLog()
.assertTargetBuiltLocally("//:hello#iphonesimulator-x86_64,swift-compile");
workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess();
workspace
.getBuildLog()
.assertTargetHadMatchingRuleKey("//:hello#iphonesimulator-x86_64,swift-compile");
workspace.addBuckConfigLocalOption("swift", "compiler_flags", "-D DEBUG");
workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess();
workspace
.getBuildLog()
.assertTargetBuiltLocally("//:hello#iphonesimulator-x86_64,swift-compile");
}
@Test
public void testEmitModuleDocArgsAreIncludedInCompilerCommand() {
assumeThat(
AppleNativeIntegrationTestUtils.isSwiftAvailable(ApplePlatform.IPHONESIMULATOR), is(true));
BuildTarget buildTarget = BuildTargetFactory.newInstance("//foo:bar#iphoneos-x86_64");
BuildTarget swiftCompileTarget =
buildTarget.withAppendedFlavors(SwiftLibraryDescription.SWIFT_COMPILE_FLAVOR);
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
BuckConfig buckConfig =
FakeBuckConfig.builder().setSections("[swift]", "emit_swiftdocs = True").build();
SwiftLibraryDescription swiftLibraryDescription =
FakeAppleRuleDescriptions.createSwiftLibraryDescription(buckConfig);
SwiftCompile buildRule =
(SwiftCompile)
swiftLibraryDescription.createBuildRule(
TestBuildRuleCreationContextFactory.create(graphBuilder, projectFilesystem),
swiftCompileTarget,
TestBuildRuleParams.create(),
createDummySwiftArg());
BuildContext buildContext = FakeBuildContext.withSourcePathResolver(pathResolver);
ImmutableList<Step> steps = buildRule.getBuildSteps(buildContext, new FakeBuildableContext());
SwiftCompileStep compileStep = (SwiftCompileStep) steps.get(1);
ImmutableList<String> compilerCommand =
ImmutableList.copyOf(compileStep.getDescription(null).split(" "));
String expectedSwiftdocPath =
ExplicitBuildTargetSourcePath.of(
swiftCompileTarget,
pathResolver
.getRelativePath(buildRule.getSourcePathToOutput())
.resolve("bar.swiftdoc"))
.getResolvedPath()
.toString();
assertThat(
compilerCommand,
Matchers.hasItems("-emit-module-doc", "-emit-module-doc-path", expectedSwiftdocPath));
}
private SwiftLibraryDescriptionArg createDummySwiftArg() {
return SwiftLibraryDescriptionArg.builder().setName("dummy").build();
}
}
| |
package act.data;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import act.app.App;
import act.asm.*;
import act.util.AppByteCodeEnhancer;
import act.util.SimpleBean;
import org.osgl.util.S;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Mark a **String** typed field is sensitive.
* DB plugin should sense any field with this annotation so that
* sensitive data be encrypted when stored into database and
* decrypted after retrieving from database.
*
* If the framework found fields marked with `@Sensitive` it
* will generate getter and setter for the field, if there are
* already getter and setter defined, the method will be
* overwritten.
*
* **Note** if a non String typed field marked with
* `@Sensitive` nothing will be done for that field,
* however framework will log a warn message.
*
* The logic of a sensitive getter/setter:
*
* ```java
* {@literal @}Sensitive
* private String sensitiveData;
* // generated or overwritten getter
* public String getSensitiveData(String data) {
* return Act.crypto().decrypt(data);
* }
* public void setSenstiveData(String data) {
* this.data = Act.crypto().encrypt(data);
* }
* ```
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Sensitive {
String ASM_DESC = Type.getType(Sensitive.class).getDescriptor();
class Enhancer extends AppByteCodeEnhancer<Enhancer> {
private static final String DESC_SENSITIVE = Sensitive.ASM_DESC;
private static final String DESC_STRING = Type.getType(String.class).getDescriptor();
private static final String GETTER_DESC = S.concat("()", DESC_STRING);
private static final String SETTER_DESC = S.concat("(", DESC_STRING, ")V");
private Set<String> sensitiveFieldsForGetter = new HashSet<>();
private Set<String> sensitiveFieldsForSetter = new HashSet<>();
private SimpleBean.MetaInfoManager metaInfoManager;
private SimpleBean.MetaInfo metaInfo;
private String classInternalName;
private String className;
public Enhancer() {
}
public Enhancer(ClassVisitor cv) {
super(S.F.startsWith("act.").negate(), cv);
}
@Override
public AppByteCodeEnhancer app(App app) {
metaInfoManager = app.classLoader().simpleBeanInfoManager();
return super.app(app);
}
@Override
protected Class<Enhancer> subClass() {
return Enhancer.class;
}
@Override
protected void reset() {
sensitiveFieldsForSetter.clear();
sensitiveFieldsForGetter.clear();
className = null;
classInternalName = null;
metaInfo = null;
super.reset();
}
@Override
public int priority() {
return SimpleBean.ByteCodeEnhancer.PRIORITY + 1;
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
classInternalName = name;
className = Type.getObjectType(name).getClassName();
metaInfo = metaInfoManager.get(className);
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public FieldVisitor visitField(int access, final String name, final String fieldDesc, String signature, Object value) {
FieldVisitor fv = super.visitField(access, name, fieldDesc, signature, value);
boolean isStatic = ((access & ACC_STATIC) != 0);
return isStatic || S.neq(DESC_STRING, fieldDesc) ? fv : new FieldVisitor(ASM5, fv) {
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
if (DESC_SENSITIVE.equals(desc)) {
sensitiveFieldsForGetter.add(name);
sensitiveFieldsForSetter.add(name);
if (null != metaInfo) {
metaInfo.addSensitiveField(name);
}
}
return super.visitAnnotation(desc, visible);
}
};
}
@Override
public MethodVisitor visitMethod(int access, final String methodName, final String methodDesc, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, methodName, methodDesc, signature, exceptions);
String fieldName = fieldNameFromGetterOrSetter(methodName);
final String mappedFieldName = null != metaInfo ? metaInfo.aliasOf(fieldName) : fieldName;
final boolean isSetter = null != fieldName && methodName.startsWith("s");
Set<String> backlog = isSetter ? sensitiveFieldsForSetter : sensitiveFieldsForGetter;
return null == fieldName || !(backlog.contains(mappedFieldName)) ? mv : new MethodVisitor(ASM5, mv) {
@Override
public void visitCode() {
boolean generating = generatingMethods.get();
if (!generating) {
if (isSetter) {
logger.warn(methodName + "(" + Type.getType(methodDesc).getArgumentTypes()[0].getClassName() + ") rewritten for @Sensitive field: " + mappedFieldName);
} else {
logger.warn(methodName + "() rewritten for @Sensitive field: " + mappedFieldName);
}
}
if (isSetter) {
visitSetterCode(mappedFieldName, this);
if (!generating) {
sensitiveFieldsForSetter.remove(mappedFieldName);
}
} else {
visitGetterCode(mappedFieldName, this);
if (!generating) {
sensitiveFieldsForGetter.remove(mappedFieldName);
}
}
}
};
}
private static final AtomicBoolean generatingMethods = new AtomicBoolean(false);
@Override
public void visitEnd() {
super.visitEnd();
for (final String field: sensitiveFieldsForGetter) {
generatingMethods.set(true);
try {
MethodVisitor mv = visitMethod(
ACC_PUBLIC,
getterName(field),
GETTER_DESC,
null,
null);
mv.visitCode();
} finally {
generatingMethods.set(false);
}
}
for (final String field : sensitiveFieldsForSetter) {
generatingMethods.set(true);
try {
MethodVisitor mv = visitMethod(
ACC_PUBLIC,
setterName(field),
SETTER_DESC,
null,
null);
mv.visitCode();
} finally {
generatingMethods.set(false);
}
}
}
private String fieldNameFromGetterOrSetter(String methodName) {
int len = methodName.length();
if (len > 3 && (methodName.startsWith("get") || methodName.startsWith("set"))) {
return S.lowerFirst(methodName.substring(3));
}
return null;
}
private void visitSetterCode(final String field, final MethodVisitor mv) {
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, "act/Act", "crypto", "()Lact/crypto/AppCrypto;", false);
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL, "act/crypto/AppCrypto", "encrypt", "(Ljava/lang/String;)Ljava/lang/String;", false);
mv.visitFieldInsn(PUTFIELD, classInternalName, field, DESC_STRING);
mv.visitInsn(RETURN);
mv.visitMaxs(3, 2);
mv.visitEnd();
}
private void visitGetterCode(final String field, final MethodVisitor mv) {
mv.visitMethodInsn(INVOKESTATIC, "act/Act", "crypto", "()Lact/crypto/AppCrypto;", false);
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, classInternalName, field, "Ljava/lang/String;");
mv.visitMethodInsn(INVOKEVIRTUAL, "act/crypto/AppCrypto", "decrypt", "(Ljava/lang/String;)Ljava/lang/String;", false);
mv.visitInsn(ARETURN);
mv.visitMaxs(2, 1);
mv.visitEnd();
}
private static String getterName(String fieldName) {
return S.concat("get", S.capFirst(fieldName));
}
private static String setterName(String fieldName) {
return "set" + S.capFirst(fieldName);
}
}
}
| |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.dx.cf.direct;
import com.android.dx.cf.attrib.AttSourceFile;
import com.android.dx.cf.cst.ConstantPoolParser;
import com.android.dx.cf.iface.Attribute;
import com.android.dx.cf.iface.AttributeList;
import com.android.dx.cf.iface.ClassFile;
import com.android.dx.cf.iface.FieldList;
import com.android.dx.cf.iface.MethodList;
import com.android.dx.cf.iface.ParseException;
import com.android.dx.cf.iface.ParseObserver;
import com.android.dx.cf.iface.StdAttributeList;
import com.android.dx.rop.code.AccessFlags;
import com.android.dx.rop.cst.ConstantPool;
import com.android.dx.rop.cst.CstType;
import com.android.dx.rop.cst.CstString;
import com.android.dx.rop.cst.StdConstantPool;
import com.android.dx.rop.type.StdTypeList;
import com.android.dx.rop.type.Type;
import com.android.dx.rop.type.TypeList;
import com.android.dx.util.ByteArray;
import com.android.dx.util.Hex;
/**
* Class file with info taken from a {@code byte[]} or slice thereof.
*/
public class DirectClassFile implements ClassFile {
/** the expected value of the ClassFile.magic field */
private static final int CLASS_FILE_MAGIC = 0xcafebabe;
/**
* minimum {@code .class} file major version
*
* See http://en.wikipedia.org/wiki/Java_class_file for an up-to-date
* list of version numbers. Currently known (taken from that table) are:
*
* J2SE 6.0 = 50 (0x32 hex),
* J2SE 5.0 = 49 (0x31 hex),
* JDK 1.4 = 48 (0x30 hex),
* JDK 1.3 = 47 (0x2F hex),
* JDK 1.2 = 46 (0x2E hex),
* JDK 1.1 = 45 (0x2D hex).
*
* Valid ranges are typically of the form
* "A.0 through B.C inclusive" where A <= B and C >= 0,
* which is why we don't have a CLASS_FILE_MIN_MINOR_VERSION.
*/
private static final int CLASS_FILE_MIN_MAJOR_VERSION = 45;
/**
* maximum {@code .class} file major version
*
* Note: if you change this, please change "java.class.version" in System.java.
*/
private static final int CLASS_FILE_MAX_MAJOR_VERSION = 50;
/** maximum {@code .class} file minor version */
private static final int CLASS_FILE_MAX_MINOR_VERSION = 0;
/**
* {@code non-null;} the file path for the class, excluding any base directory
* specification
*/
private final String filePath;
/** {@code non-null;} the bytes of the file */
private final ByteArray bytes;
/**
* whether to be strict about parsing; if
* {@code false}, this avoids doing checks that only exist
* for purposes of verification (such as magic number matching and
* path-package consistency checking)
*/
private final boolean strictParse;
/**
* {@code null-ok;} the constant pool; only ever {@code null}
* before the constant pool is successfully parsed
*/
private StdConstantPool pool;
/**
* the class file field {@code access_flags}; will be {@code -1}
* before the file is successfully parsed
*/
private int accessFlags;
/**
* {@code null-ok;} the class file field {@code this_class},
* interpreted as a type constant; only ever {@code null}
* before the file is successfully parsed
*/
private CstType thisClass;
/**
* {@code null-ok;} the class file field {@code super_class}, interpreted
* as a type constant if non-zero
*/
private CstType superClass;
/**
* {@code null-ok;} the class file field {@code interfaces}; only
* ever {@code null} before the file is successfully
* parsed
*/
private TypeList interfaces;
/**
* {@code null-ok;} the class file field {@code fields}; only ever
* {@code null} before the file is successfully parsed
*/
private FieldList fields;
/**
* {@code null-ok;} the class file field {@code methods}; only ever
* {@code null} before the file is successfully parsed
*/
private MethodList methods;
/**
* {@code null-ok;} the class file field {@code attributes}; only
* ever {@code null} before the file is successfully
* parsed
*/
private StdAttributeList attributes;
/** {@code null-ok;} attribute factory, if any */
private AttributeFactory attributeFactory;
/** {@code null-ok;} parse observer, if any */
private ParseObserver observer;
/**
* Returns the string form of an object or {@code "(none)"}
* (rather than {@code "null"}) for {@code null}.
*
* @param obj {@code null-ok;} the object to stringify
* @return {@code non-null;} the appropriate string form
*/
public static String stringOrNone(Object obj) {
if (obj == null) {
return "(none)";
}
return obj.toString();
}
/**
* Constructs an instance.
*
* @param bytes {@code non-null;} the bytes of the file
* @param filePath {@code non-null;} the file path for the class,
* excluding any base directory specification
* @param strictParse whether to be strict about parsing; if
* {@code false}, this avoids doing checks that only exist
* for purposes of verification (such as magic number matching and
* path-package consistency checking)
*/
public DirectClassFile(ByteArray bytes, String filePath,
boolean strictParse) {
if (bytes == null) {
throw new NullPointerException("bytes == null");
}
if (filePath == null) {
throw new NullPointerException("filePath == null");
}
this.filePath = filePath;
this.bytes = bytes;
this.strictParse = strictParse;
this.accessFlags = -1;
}
/**
* Constructs an instance.
*
* @param bytes {@code non-null;} the bytes of the file
* @param filePath {@code non-null;} the file path for the class,
* excluding any base directory specification
* @param strictParse whether to be strict about parsing; if
* {@code false}, this avoids doing checks that only exist
* for purposes of verification (such as magic number matching and
* path-package consistency checking)
*/
public DirectClassFile(byte[] bytes, String filePath,
boolean strictParse) {
this(new ByteArray(bytes), filePath, strictParse);
}
/**
* Sets the parse observer for this instance.
*
* @param observer {@code null-ok;} the observer
*/
public void setObserver(ParseObserver observer) {
this.observer = observer;
}
/**
* Sets the attribute factory to use.
*
* @param attributeFactory {@code non-null;} the attribute factory
*/
public void setAttributeFactory(AttributeFactory attributeFactory) {
if (attributeFactory == null) {
throw new NullPointerException("attributeFactory == null");
}
this.attributeFactory = attributeFactory;
}
/**
* Gets the {@link ByteArray} that this instance's data comes from.
*
* @return {@code non-null;} the bytes
*/
public ByteArray getBytes() {
return bytes;
}
/** {@inheritDoc} */
public int getMagic() {
parseToInterfacesIfNecessary();
return getMagic0();
}
/** {@inheritDoc} */
public int getMinorVersion() {
parseToInterfacesIfNecessary();
return getMinorVersion0();
}
/** {@inheritDoc} */
public int getMajorVersion() {
parseToInterfacesIfNecessary();
return getMajorVersion0();
}
/** {@inheritDoc} */
public int getAccessFlags() {
parseToInterfacesIfNecessary();
return accessFlags;
}
/** {@inheritDoc} */
public CstType getThisClass() {
parseToInterfacesIfNecessary();
return thisClass;
}
/** {@inheritDoc} */
public CstType getSuperclass() {
parseToInterfacesIfNecessary();
return superClass;
}
/** {@inheritDoc} */
public ConstantPool getConstantPool() {
parseToInterfacesIfNecessary();
return pool;
}
/** {@inheritDoc} */
public TypeList getInterfaces() {
parseToInterfacesIfNecessary();
return interfaces;
}
/** {@inheritDoc} */
public FieldList getFields() {
parseToEndIfNecessary();
return fields;
}
/** {@inheritDoc} */
public MethodList getMethods() {
parseToEndIfNecessary();
return methods;
}
/** {@inheritDoc} */
public AttributeList getAttributes() {
parseToEndIfNecessary();
return attributes;
}
/** {@inheritDoc} */
public CstString getSourceFile() {
AttributeList attribs = getAttributes();
Attribute attSf = attribs.findFirst(AttSourceFile.ATTRIBUTE_NAME);
if (attSf instanceof AttSourceFile) {
return ((AttSourceFile) attSf).getSourceFile();
}
return null;
}
/**
* Constructs and returns an instance of {@link TypeList} whose
* data comes from the bytes of this instance, interpreted as a
* list of constant pool indices for classes, which are in turn
* translated to type constants. Instance construction will fail
* if any of the (alleged) indices turn out not to refer to
* constant pool entries of type {@code Class}.
*
* @param offset offset into {@link #bytes} for the start of the
* data
* @param size number of elements in the list (not number of bytes)
* @return {@code non-null;} an appropriately-constructed class list
*/
public TypeList makeTypeList(int offset, int size) {
if (size == 0) {
return StdTypeList.EMPTY;
}
if (pool == null) {
throw new IllegalStateException("pool not yet initialized");
}
return new DcfTypeList(bytes, offset, size, pool, observer);
}
/**
* Gets the class file field {@code magic}, but without doing any
* checks or parsing first.
*
* @return the magic value
*/
public int getMagic0() {
return bytes.getInt(0);
}
/**
* Gets the class file field {@code minor_version}, but
* without doing any checks or parsing first.
*
* @return the minor version
*/
public int getMinorVersion0() {
return bytes.getUnsignedShort(4);
}
/**
* Gets the class file field {@code major_version}, but
* without doing any checks or parsing first.
*
* @return the major version
*/
public int getMajorVersion0() {
return bytes.getUnsignedShort(6);
}
/**
* Runs {@link #parse} if it has not yet been run to cover up to
* the interfaces list.
*/
private void parseToInterfacesIfNecessary() {
if (accessFlags == -1) {
parse();
}
}
/**
* Runs {@link #parse} if it has not yet been run successfully.
*/
private void parseToEndIfNecessary() {
if (attributes == null) {
parse();
}
}
/**
* Does the parsing, handing exceptions.
*/
private void parse() {
try {
parse0();
} catch (ParseException ex) {
ex.addContext("...while parsing " + filePath);
throw ex;
} catch (RuntimeException ex) {
ParseException pe = new ParseException(ex);
pe.addContext("...while parsing " + filePath);
throw pe;
}
}
/**
* Sees if the .class file header magic/version are within
* range.
*
* @param magic the value of a classfile "magic" field
* @param minorVersion the value of a classfile "minor_version" field
* @param majorVersion the value of a classfile "major_version" field
* @return true iff the parameters are valid and within range
*/
private boolean isGoodVersion(int magic, int minorVersion,
int majorVersion) {
/* Valid version ranges are typically of the form
* "A.0 through B.C inclusive" where A <= B and C >= 0,
* which is why we don't have a CLASS_FILE_MIN_MINOR_VERSION.
*/
if (magic == CLASS_FILE_MAGIC && minorVersion >= 0) {
/* Check against max first to handle the case where
* MIN_MAJOR == MAX_MAJOR.
*/
if (majorVersion == CLASS_FILE_MAX_MAJOR_VERSION) {
if (minorVersion <= CLASS_FILE_MAX_MINOR_VERSION) {
return true;
}
} else if (majorVersion < CLASS_FILE_MAX_MAJOR_VERSION &&
majorVersion >= CLASS_FILE_MIN_MAJOR_VERSION) {
return true;
}
}
return false;
}
/**
* Does the actual parsing.
*/
private void parse0() {
if (bytes.size() < 10) {
throw new ParseException("severely truncated class file");
}
if (observer != null) {
observer.parsed(bytes, 0, 0, "begin classfile");
observer.parsed(bytes, 0, 4, "magic: " + Hex.u4(getMagic0()));
observer.parsed(bytes, 4, 2,
"minor_version: " + Hex.u2(getMinorVersion0()));
observer.parsed(bytes, 6, 2,
"major_version: " + Hex.u2(getMajorVersion0()));
}
if (strictParse && false) {
/* Make sure that this looks like a valid class file with a
* version that we can handle.
*/
if (!isGoodVersion(getMagic0(), getMinorVersion0(),
getMajorVersion0())) {
throw new ParseException("bad class file magic (" +
Hex.u4(getMagic0()) +
") or version (" +
Hex.u2(getMajorVersion0()) + "." +
Hex.u2(getMinorVersion0()) + ")");
}
}
ConstantPoolParser cpParser = new ConstantPoolParser(bytes);
cpParser.setObserver(observer);
pool = cpParser.getPool();
pool.setImmutable();
int at = cpParser.getEndOffset();
int accessFlags = bytes.getUnsignedShort(at); // u2 access_flags;
int cpi = bytes.getUnsignedShort(at + 2); // u2 this_class;
thisClass = (CstType) pool.get(cpi);
cpi = bytes.getUnsignedShort(at + 4); // u2 super_class;
superClass = (CstType) pool.get0Ok(cpi);
int count = bytes.getUnsignedShort(at + 6); // u2 interfaces_count
if (observer != null) {
observer.parsed(bytes, at, 2,
"access_flags: " +
AccessFlags.classString(accessFlags));
observer.parsed(bytes, at + 2, 2, "this_class: " + thisClass);
observer.parsed(bytes, at + 4, 2, "super_class: " +
stringOrNone(superClass));
observer.parsed(bytes, at + 6, 2,
"interfaces_count: " + Hex.u2(count));
if (count != 0) {
observer.parsed(bytes, at + 8, 0, "interfaces:");
}
}
at += 8;
interfaces = makeTypeList(at, count);
at += count * 2;
if (strictParse && false) {
/*
* Make sure that the file/jar path matches the declared
* package/class name.
*/
String thisClassName = thisClass.getClassType().getClassName();
if (!(filePath.endsWith(".class") &&
filePath.startsWith(thisClassName) &&
(filePath.length() == (thisClassName.length() + 6)))) {
throw new ParseException("class name (" + thisClassName +
") does not match path (" +
filePath + ")");
}
}
/*
* Only set the instance variable accessFlags here, since
* that's what signals a successful parse of the first part of
* the file (through the interfaces list).
*/
this.accessFlags = accessFlags;
FieldListParser flParser =
new FieldListParser(this, thisClass, at, attributeFactory);
flParser.setObserver(observer);
fields = flParser.getList();
at = flParser.getEndOffset();
MethodListParser mlParser =
new MethodListParser(this, thisClass, at, attributeFactory);
mlParser.setObserver(observer);
methods = mlParser.getList();
at = mlParser.getEndOffset();
AttributeListParser alParser =
new AttributeListParser(this, AttributeFactory.CTX_CLASS, at,
attributeFactory);
alParser.setObserver(observer);
attributes = alParser.getList();
attributes.setImmutable();
at = alParser.getEndOffset();
if (at != bytes.size() && false) {
throw new ParseException("extra bytes at end of class file, " +
"at offset " + Hex.u4(at));
}
if (observer != null) {
observer.parsed(bytes, at, 0, "end classfile");
}
}
/**
* Implementation of {@link TypeList} whose data comes directly
* from the bytes of an instance of this (outer) class,
* interpreted as a list of constant pool indices for classes
* which are in turn returned as type constants. Instance
* construction will fail if any of the (alleged) indices turn out
* not to refer to constant pool entries of type
* {@code Class}.
*/
private static class DcfTypeList implements TypeList {
/** {@code non-null;} array containing the data */
private final ByteArray bytes;
/** number of elements in the list (not number of bytes) */
private final int size;
/** {@code non-null;} the constant pool */
private final StdConstantPool pool;
/**
* Constructs an instance.
*
* @param bytes {@code non-null;} original classfile's bytes
* @param offset offset into {@link #bytes} for the start of the
* data
* @param size number of elements in the list (not number of bytes)
* @param pool {@code non-null;} the constant pool to use
* @param observer {@code null-ok;} parse observer to use, if any
*/
public DcfTypeList(ByteArray bytes, int offset, int size,
StdConstantPool pool, ParseObserver observer) {
if (size < 0) {
throw new IllegalArgumentException("size < 0");
}
bytes = bytes.slice(offset, offset + size * 2);
this.bytes = bytes;
this.size = size;
this.pool = pool;
for (int i = 0; i < size; i++) {
offset = i * 2;
int idx = bytes.getUnsignedShort(offset);
CstType type;
try {
type = (CstType) pool.get(idx);
} catch (ClassCastException ex) {
// Translate the exception.
throw new RuntimeException("bogus class cpi", ex);
}
if (observer != null) {
observer.parsed(bytes, offset, 2, " " + type);
}
}
}
/** {@inheritDoc} */
public boolean isMutable() {
return false;
}
/** {@inheritDoc} */
public int size() {
return size;
}
/** {@inheritDoc} */
public int getWordCount() {
// It is the same as size because all elements are classes.
return size;
}
/** {@inheritDoc} */
public Type getType(int n) {
int idx = bytes.getUnsignedShort(n * 2);
return ((CstType) pool.get(idx)).getClassType();
}
/** {@inheritDoc} */
public TypeList withAddedType(Type type) {
throw new UnsupportedOperationException("unsupported");
}
}
}
| |
package org.vivoweb.tools;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.jena.riot.RDFFormat;
import java.io.File;
public class JenaCli {
static {
Logger.getRootLogger().setLevel(Level.OFF);
}
public static void main (String[] arg) {
Options options = parseArguments(arg);
if (options == null) {
System.err.println("Incorrect arguments supplied.");
System.err.println("");
System.err.println("Export: java -jar jena3tools.jar -e -d <home dir>");
System.err.println("Import: java -jar jena3tools.jar -i -d <home dir>");
System.exit(1);
}
if (!isValidHomeDir(options.homeDir)) {
System.err.println("Can't find a valid home dir at " + options.homeDir);
System.exit(1);
}
ApplicationStores applicationStores = new ApplicationStores(options.homeDir, options.outputFormat);
try {
File dumpDir = Utils.resolveFile(options.homeDir, "dumps");
if (dumpDir.exists()) {
if (!dumpDir.isDirectory()) {
System.err.println("Home directory contains 'dumps', which is not a directory");
System.exit(1);
}
} else {
if (!dumpDir.mkdirs()) {
System.err.println("Unable to create 'dumps' directory");
System.exit(1);
}
}
File contentDump = Utils.resolveFile(options.homeDir, "dumps/content." + options.outputString);
File configurationDump = Utils.resolveFile(options.homeDir, "dumps/configuration." +
options.outputString);
if (options.exportMode) {
if (!options.force) {
if (contentDump.exists() || configurationDump.exists()) {
System.err.println("Dumps directory contains previous export");
System.exit(1);
}
}
System.out.println("Writing Configuration");
applicationStores.writeConfiguration(configurationDump);
System.out.println("Writing Content");
applicationStores.writeContent(contentDump);
System.out.println("Export complete");
} else if (options.importMode) {
if (!applicationStores.isEmpty()) {
System.err.println("Triple store(s) contain existing values");
System.exit(1);
}
if (!applicationStores.validateFiles(configurationDump, contentDump)) {
System.err.println("Dump files not present");
System.exit(1);
}
System.out.println("Reading Configuration");
applicationStores.readConfiguration(configurationDump);
System.out.println("Reading Content");
applicationStores.readContent(contentDump);
System.out.println("Import complete");
}
System.exit(0);
} finally {
applicationStores.close();
}
}
private static Options parseArguments(String[] arg) {
Options options = new Options();
if (arg != null) {
for (int i = 0; i < arg.length; i++) {
if ("-d".equalsIgnoreCase(arg[i]) ||
"--dir".equalsIgnoreCase(arg[i])
) {
if (i < arg.length - 1) {
i++;
options.homeDir = arg[i];
}
}
if ("-o".equalsIgnoreCase(arg[i]) ||
"--output".equalsIgnoreCase(arg[i])
) {
if (i < arg.length - 1) {
i++;
options.outputString = arg[i];
}
}
if ("-e".equalsIgnoreCase(arg[i]) ||
"--export".equalsIgnoreCase(arg[i])
) {
options.exportMode = true;
}
if ("-i".equalsIgnoreCase(arg[i]) ||
"--import".equalsIgnoreCase(arg[i])
) {
options.importMode = true;
}
if ("-f".equalsIgnoreCase(arg[i]) ||
"--force".equalsIgnoreCase(arg[i])
) {
options.force = true;
}
}
}
if (options.isValid()) {
return options;
}
return null;
}
private static boolean isValidHomeDir(String homeDir) {
File homeDirFile = new File(homeDir);
if (!homeDirFile.isDirectory()) {
return false;
}
if (!homeDirFile.canRead() || !homeDirFile.canWrite()) {
return false;
}
boolean hasConfigDir = false;
boolean hasRuntimeProperties = false;
for (File child : homeDirFile.listFiles()) {
if ("config".equals(child.getName())) {
for (File configs : child.listFiles()) {
if ("applicationSetup.n3".equals(configs.getName())) {
hasConfigDir = true;
}
if ("runtime.properties".equals(configs.getName())) {
hasRuntimeProperties = true;
}
}
}
if ("runtime.properties".equals(child.getName())) {
hasRuntimeProperties = true;
}
}
if (!hasConfigDir || !hasRuntimeProperties) {
return false;
}
return true;
}
private static class Options {
public String homeDir = null;
public boolean importMode = false;
public boolean exportMode = false;
public boolean force = false;
public String outputString = "trig";
public RDFFormat outputFormat = RDFFormat.TRIG_BLOCKS;
private boolean isValid() {
if (StringUtils.isEmpty(homeDir)) {
return false;
}
if ("trig".equals(outputString)) {
outputFormat = RDFFormat.TRIG_BLOCKS;
} else if ("nt".equals(outputString)) {
outputFormat = RDFFormat.NTRIPLES;
} else if ("nq".equals(outputString)) {
outputFormat = RDFFormat.NQUADS;
} else if ("ttl".equals(outputString)) {
outputFormat = RDFFormat.TURTLE;
} else if ("rdf".equals(outputString)) {
outputFormat = RDFFormat.RDFXML;
} else if ("jsonld".equals(outputString)) {
outputFormat = RDFFormat.JSONLD;
} else {
return false;
}
if (importMode == exportMode) {
return false;
}
return true;
}
}
}
| |
/*
* Copyright 2012 Victor Cordis
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Please contact the author ( cordis.victor@gmail.com ) if you need additional
* information or have any questions.
*/
package net.sourceforge.easyml.util;
import net.sourceforge.easyml.marshalling.CompositeReader;
import net.sourceforge.easyml.marshalling.CompositeWriter;
import java.lang.reflect.Array;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* ValueType enum containing all value-type classes.
*
* @author Victor Cordis ( cordis.victor at gmail.com)
* @version 1.2.0
* @since 1.0
*/
public enum ValueType {
BOOLEAN {
@Override
public Object parseValue(String value) {
return Boolean.parseBoolean(value);
}
@Override
public boolean getWriteArrayItem(CompositeWriter writer, Object array, int itemIdx, boolean skipDefs) {
final boolean item = Array.getBoolean(array, itemIdx);
if (skipDefs && item == false) {
return false;
}
writer.writeBoolean(item);
return true;
}
@Override
public boolean isDefaultArrayItem(Object array, int itemIdx) {
return Array.getBoolean(array, itemIdx) == false;
}
@Override
public boolean setReadArrayItem(CompositeReader reader, Object array, int itemIdx) {
final boolean item = reader.readBoolean();
if (item == false) {
return false;
}
Array.setBoolean(array, itemIdx, item);
return true;
}
},
BOOLEAN_WRAPPER {
@Override
public Object parseValue(String value) {
return Boolean.parseBoolean(value);
}
},
BYTE {
@Override
public Object parseValue(String value) {
return Byte.parseByte(value);
}
@Override
public boolean getWriteArrayItem(CompositeWriter writer, Object array, int itemIdx, boolean skipDefs) {
final byte item = Array.getByte(array, itemIdx);
if (skipDefs && item == 0) {
return false;
}
writer.writeByte(item);
return true;
}
@Override
public boolean isDefaultArrayItem(Object array, int itemIdx) {
return Array.getByte(array, itemIdx) == 0;
}
@Override
public boolean setReadArrayItem(CompositeReader reader, Object array, int itemIdx) {
final byte item = reader.readByte();
if (item == 0) {
return false;
}
Array.setByte(array, itemIdx, item);
return true;
}
},
BYTE_WRAPPER {
@Override
public Object parseValue(String value) {
return Byte.parseByte(value);
}
},
SHORT {
@Override
public Object parseValue(String value) {
return Short.parseShort(value);
}
@Override
public boolean getWriteArrayItem(CompositeWriter writer, Object array, int itemIdx, boolean skipDefs) {
final short item = Array.getShort(array, itemIdx);
if (skipDefs && item == 0) {
return false;
}
writer.writeShort(item);
return true;
}
@Override
public boolean isDefaultArrayItem(Object array, int itemIdx) {
return Array.getShort(array, itemIdx) == 0;
}
@Override
public boolean setReadArrayItem(CompositeReader reader, Object array, int itemIdx) {
final short item = reader.readShort();
if (item == 0) {
return false;
}
Array.setShort(array, itemIdx, item);
return true;
}
},
SHORT_WRAPPER {
@Override
public Object parseValue(String value) {
return Short.parseShort(value);
}
},
INT {
@Override
public Object parseValue(String value) {
return Integer.parseInt(value);
}
@Override
public boolean getWriteArrayItem(CompositeWriter writer, Object array, int itemIdx, boolean skipDefs) {
final int item = Array.getInt(array, itemIdx);
if (skipDefs && item == 0) {
return false;
}
writer.writeInt(item);
return true;
}
@Override
public boolean isDefaultArrayItem(Object array, int itemIdx) {
return Array.getInt(array, itemIdx) == 0;
}
@Override
public boolean setReadArrayItem(CompositeReader reader, Object array, int itemIdx) {
final int item = reader.readInt();
if (item == 0) {
return false;
}
Array.setInt(array, itemIdx, item);
return true;
}
},
INT_WRAPPER {
@Override
public Object parseValue(String value) {
return Integer.parseInt(value);
}
},
LONG {
@Override
public Object parseValue(String value) {
return Long.parseLong(value);
}
@Override
public boolean getWriteArrayItem(CompositeWriter writer, Object array, int itemIdx, boolean skipDefs) {
final long item = Array.getLong(array, itemIdx);
if (skipDefs && item == 0) {
return false;
}
writer.writeLong(item);
return true;
}
@Override
public boolean isDefaultArrayItem(Object array, int itemIdx) {
return Array.getLong(array, itemIdx) == 0;
}
@Override
public boolean setReadArrayItem(CompositeReader reader, Object array, int itemIdx) {
final long item = reader.readLong();
if (item == 0) {
return false;
}
Array.setLong(array, itemIdx, item);
return true;
}
},
LONG_WRAPPER {
@Override
public Object parseValue(String value) {
return Long.parseLong(value);
}
},
FLOAT {
@Override
public Object parseValue(String value) {
return Float.parseFloat(value);
}
@Override
public boolean getWriteArrayItem(CompositeWriter writer, Object array, int itemIdx, boolean skipDefs) {
final float item = Array.getFloat(array, itemIdx);
if (skipDefs && item == 0f) {
return false;
}
writer.writeFloat(item);
return true;
}
@Override
public boolean isDefaultArrayItem(Object array, int itemIdx) {
return Array.getFloat(array, itemIdx) == 0f;
}
@Override
public boolean setReadArrayItem(CompositeReader reader, Object array, int itemIdx) {
final float item = reader.readFloat();
if (item == 0f) {
return false;
}
Array.setFloat(array, itemIdx, item);
return true;
}
},
FLOAT_WRAPPER {
@Override
public Object parseValue(String value) {
return Float.parseFloat(value);
}
},
DOUBLE {
@Override
public Object parseValue(String value) {
return Double.parseDouble(value);
}
@Override
public boolean getWriteArrayItem(CompositeWriter writer, Object array, int itemIdx, boolean skipDefs) {
final double item = Array.getDouble(array, itemIdx);
if (skipDefs && item == 0.0) {
return false;
}
writer.writeDouble(item);
return true;
}
@Override
public boolean isDefaultArrayItem(Object array, int itemIdx) {
return Array.getDouble(array, itemIdx) == 0.0;
}
@Override
public boolean setReadArrayItem(CompositeReader reader, Object array, int itemIdx) {
final double item = reader.readDouble();
if (item == 0.0) {
return false;
}
Array.setDouble(array, itemIdx, item);
return true;
}
},
DOUBLE_WRAPPER {
@Override
public Object parseValue(String value) {
return Double.parseDouble(value);
}
},
CHAR {
@Override
public Object parseValue(String value) {
if (value.length() != 1) {
throw new IllegalArgumentException("value: length not 1: " + value);
}
return value.charAt(0);
}
@Override
public boolean getWriteArrayItem(CompositeWriter writer, Object array, int itemIdx, boolean skipDefs) {
final char item = Array.getChar(array, itemIdx);
if (skipDefs && item == 0) {
return false;
}
writer.writeChar(item);
return true;
}
@Override
public boolean isDefaultArrayItem(Object array, int itemIdx) {
return Array.getChar(array, itemIdx) == 0;
}
@Override
public boolean setReadArrayItem(CompositeReader reader, Object array, int itemIdx) {
final char item = reader.readChar();
if (item == 0) {
return false;
}
Array.setChar(array, itemIdx, item);
return true;
}
},
CHAR_WRAPPER {
@Override
public Object parseValue(String value) {
if (value.length() != 1) {
throw new IllegalArgumentException("value: length not 1: " + value);
}
return value.charAt(0);
}
},
STRING {
@Override
public Object parseValue(String value) {
return value;
}
};
private static final Map<Class, ValueType> types = new IdentityHashMap<>();
static {
types.put(boolean.class, BOOLEAN);
types.put(Boolean.class, BOOLEAN_WRAPPER);
types.put(byte.class, BYTE);
types.put(Byte.class, BYTE_WRAPPER);
types.put(short.class, SHORT);
types.put(Short.class, SHORT_WRAPPER);
types.put(int.class, INT);
types.put(Integer.class, INT_WRAPPER);
types.put(long.class, LONG);
types.put(Long.class, LONG_WRAPPER);
types.put(float.class, FLOAT);
types.put(Float.class, FLOAT_WRAPPER);
types.put(double.class, DOUBLE);
types.put(Double.class, DOUBLE_WRAPPER);
types.put(char.class, CHAR);
types.put(Character.class, CHAR_WRAPPER);
types.put(String.class, STRING);
}
/**
* Returns <code>true</code> if the given type class represents a value
* type.
*
* @param type to test
* @return true if value type, false otherwise
*/
public static boolean is(Class type) {
return types.containsKey(type);
}
/**
* Returns the value type constant corresponding to the given type class. If
* the given class does not represent a value-type then <code>null</code> is
* returned.
*
* @param type to get constant for
* @return the constant, if any, or null
*/
public static ValueType of(Class type) {
return types.get(type);
}
/**
* Parses the given string representation and returns the value.
*
* @param value to parse
* @return the value
*/
public abstract Object parseValue(String value);
/**
* Reflection method used to check if the item at itemIdx of the given array
* has a default value.
*
* @param array container
* @param itemIdx index of item
* @return true if default, false otherwise
*/
public boolean isDefaultArrayItem(Object array, int itemIdx) {
return Array.get(array, itemIdx) == null;
}
/**
* Reflection method used to get and write an array value, if not
* <code>skipDefs && valueIsDefault</code>, to prevent auto-boxing.
*
* @param writer to write with
* @param array the array
* @param itemIdx the array item index
* @param skipDefs true if skip defaults
* @return true if written, false if skipDefs and default
*/
public boolean getWriteArrayItem(CompositeWriter writer, Object array, int itemIdx, boolean skipDefs) {
final Object item = Array.get(array, itemIdx);
if (skipDefs && item == null) {
return false;
}
writer.write(item);
return true;
}
/**
* Reflection method used to read and set an array value, to prevent
* auto-boxing. The value is not set at the array indexIdem if it is the
* array-type default value.
*
* @param reader to read with
* @param array the array
* @param itemIdx the array item index
* @return true if set, false otherwise
*/
public boolean setReadArrayItem(CompositeReader reader, Object array, int itemIdx) {
final Object item = reader.read();
if (item == null) {
return false;
}
Array.set(array, itemIdx, item);
return true;
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.admin.cluster.node.info;
import org.elasticsearch.Build;
import org.elasticsearch.Version;
import org.elasticsearch.action.support.nodes.BaseNodeResponse;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.http.HttpInfo;
import org.elasticsearch.monitor.jvm.JvmInfo;
import org.elasticsearch.monitor.os.OsInfo;
import org.elasticsearch.monitor.process.ProcessInfo;
import org.elasticsearch.threadpool.ThreadPoolInfo;
import org.elasticsearch.transport.TransportInfo;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.unmodifiableMap;
/**
* Node information (static, does not change over time).
*/
public class NodeInfo extends BaseNodeResponse {
@Nullable
private Map<String, String> serviceAttributes;
private Version version;
private Build build;
@Nullable
private Settings settings;
@Nullable
private OsInfo os;
@Nullable
private ProcessInfo process;
@Nullable
private JvmInfo jvm;
@Nullable
private ThreadPoolInfo threadPool;
@Nullable
private TransportInfo transport;
@Nullable
private HttpInfo http;
@Nullable
private PluginsAndModules plugins;
NodeInfo() {
}
public NodeInfo(Version version, Build build, DiscoveryNode node, @Nullable Map<String, String> serviceAttributes, @Nullable Settings settings,
@Nullable OsInfo os, @Nullable ProcessInfo process, @Nullable JvmInfo jvm, @Nullable ThreadPoolInfo threadPool,
@Nullable TransportInfo transport, @Nullable HttpInfo http, @Nullable PluginsAndModules plugins) {
super(node);
this.version = version;
this.build = build;
this.serviceAttributes = serviceAttributes;
this.settings = settings;
this.os = os;
this.process = process;
this.jvm = jvm;
this.threadPool = threadPool;
this.transport = transport;
this.http = http;
this.plugins = plugins;
}
/**
* System's hostname. <code>null</code> in case of UnknownHostException
*/
@Nullable
public String getHostname() {
return getNode().getHostName();
}
/**
* The current ES version
*/
public Version getVersion() {
return version;
}
/**
* The build version of the node.
*/
public Build getBuild() {
return this.build;
}
/**
* The service attributes of the node.
*/
@Nullable
public Map<String, String> getServiceAttributes() {
return this.serviceAttributes;
}
/**
* The settings of the node.
*/
@Nullable
public Settings getSettings() {
return this.settings;
}
/**
* Operating System level information.
*/
@Nullable
public OsInfo getOs() {
return this.os;
}
/**
* Process level information.
*/
@Nullable
public ProcessInfo getProcess() {
return process;
}
/**
* JVM level information.
*/
@Nullable
public JvmInfo getJvm() {
return jvm;
}
@Nullable
public ThreadPoolInfo getThreadPool() {
return this.threadPool;
}
@Nullable
public TransportInfo getTransport() {
return transport;
}
@Nullable
public HttpInfo getHttp() {
return http;
}
@Nullable
public PluginsAndModules getPlugins() {
return this.plugins;
}
public static NodeInfo readNodeInfo(StreamInput in) throws IOException {
NodeInfo nodeInfo = new NodeInfo();
nodeInfo.readFrom(in);
return nodeInfo;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
version = Version.readVersion(in);
build = Build.readBuild(in);
if (in.readBoolean()) {
Map<String, String> builder = new HashMap<>();
int size = in.readVInt();
for (int i = 0; i < size; i++) {
builder.put(in.readString(), in.readString());
}
serviceAttributes = unmodifiableMap(builder);
}
if (in.readBoolean()) {
settings = Settings.readSettingsFromStream(in);
}
if (in.readBoolean()) {
os = OsInfo.readOsInfo(in);
}
if (in.readBoolean()) {
process = ProcessInfo.readProcessInfo(in);
}
if (in.readBoolean()) {
jvm = JvmInfo.readJvmInfo(in);
}
if (in.readBoolean()) {
threadPool = ThreadPoolInfo.readThreadPoolInfo(in);
}
if (in.readBoolean()) {
transport = TransportInfo.readTransportInfo(in);
}
if (in.readBoolean()) {
http = HttpInfo.readHttpInfo(in);
}
if (in.readBoolean()) {
plugins = new PluginsAndModules();
plugins.readFrom(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(version.id);
Build.writeBuild(build, out);
if (getServiceAttributes() == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
out.writeVInt(serviceAttributes.size());
for (Map.Entry<String, String> entry : serviceAttributes.entrySet()) {
out.writeString(entry.getKey());
out.writeString(entry.getValue());
}
}
if (settings == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
Settings.writeSettingsToStream(settings, out);
}
if (os == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
os.writeTo(out);
}
if (process == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
process.writeTo(out);
}
if (jvm == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
jvm.writeTo(out);
}
if (threadPool == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
threadPool.writeTo(out);
}
if (transport == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
transport.writeTo(out);
}
if (http == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
http.writeTo(out);
}
if (plugins == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
plugins.writeTo(out);
}
}
}
| |
/*
* Copyright 2019 Oath Holdings Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.athenz.zts.cert;
import com.yahoo.athenz.auth.util.Crypto;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.cert.X509Certificate;
import java.util.*;
import static org.testng.Assert.*;
public class X509RoleCertRequestTest {
@Test
public void testValidateSpiffeRoleCert() throws IOException {
Path path = Paths.get("src/test/resources/spiffe_role.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
Set<String> roles = new HashSet<>();
roles.add("api");
Set<String> orgValues = new HashSet<>();
orgValues.add("Athenz");
assertTrue(certReq.validate(roles, "coretech", "sports.api", null, orgValues));
}
@Test
public void testValidateRoleIPAddressNoIPs() throws IOException {
Path path = Paths.get("src/test/resources/spiffe_role.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
assertTrue(certReq.validateIPAddress(null, "10.10.11.12"));
}
@Test
public void testValidateRoleIPAddressNoCert() throws IOException {
Path path = Paths.get("src/test/resources/role_single_ip.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
assertTrue(certReq.validateIPAddress(null, "10.11.12.13"));
assertFalse(certReq.validateIPAddress(null, "10.10.11.12"));
}
@Test
public void testValidateRoleIPAddressCertNoIPs() throws IOException {
Path path = Paths.get("src/test/resources/role_single_ip.csr");
String csr = new String(Files.readAllBytes(path));
path = Paths.get("src/test/resources/athenz.instanceid.pem");
String pem = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(pem);
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
assertTrue(certReq.validateIPAddress(cert, "10.11.12.13"));
assertFalse(certReq.validateIPAddress(cert, "10.10.11.12"));
}
@Test
public void testValidateRoleIPAddressCertIPs() throws IOException {
Path path = Paths.get("src/test/resources/role_single_ip.csr");
String csr = new String(Files.readAllBytes(path));
path = Paths.get("src/test/resources/svc_single_ip.pem");
String pem = new String(Files.readAllBytes(path));
X509Certificate cert1 = Crypto.loadX509Certificate(pem);
path = Paths.get("src/test/resources/svc_multiple_ip.pem");
pem = new String(Files.readAllBytes(path));
X509Certificate cert2 = Crypto.loadX509Certificate(pem);
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
assertTrue(certReq.validateIPAddress(cert1, "10.11.12.13"));
assertTrue(certReq.validateIPAddress(cert2, "10.11.12.13"));
}
@Test
public void testValidateRoleIPAddressCertMultipleIPs() throws IOException {
Path path = Paths.get("src/test/resources/role_multiple_ip.csr");
String csr = new String(Files.readAllBytes(path));
path = Paths.get("src/test/resources/svc_single_ip.pem");
String pem = new String(Files.readAllBytes(path));
X509Certificate cert1 = Crypto.loadX509Certificate(pem);
path = Paths.get("src/test/resources/svc_multiple_ip.pem");
pem = new String(Files.readAllBytes(path));
X509Certificate cert2 = Crypto.loadX509Certificate(pem);
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
assertFalse(certReq.validateIPAddress(cert1, "10.11.12.13"));
assertTrue(certReq.validateIPAddress(cert2, "10.11.12.13"));
}
@Test
public void testGetRequestedRoleListNoURI() throws IOException {
Path path = Paths.get("src/test/resources/role_multiple_ip.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
assertNull(certReq.getRequestedRoleList());
}
@Test
public void testGetRequestedRoleListNoRolesURI() throws IOException {
Path path = Paths.get("src/test/resources/spiffe_role.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
assertNull(certReq.getRequestedRoleList());
}
@Test
public void testGetRequestedRoleListInvalidRole() throws IOException {
Path path = Paths.get("src/test/resources/athenz_role_uri_invalid.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
assertNull(certReq.getRequestedRoleList());
}
@Test
public void testGetRequestedRoleList() throws IOException {
Path path = Paths.get("src/test/resources/athenz_role_uri.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
Map<String, String[]> roles = certReq.getRequestedRoleList();
assertEquals(roles.size(), 2);
String[] list1 = roles.get("sports");
assertEquals(list1.length, 1);
assertEquals(list1[0], "readers");
String[] list2 = roles.get("weather");
assertEquals(list2.length, 2);
assertEquals(list2[0], "readers");
assertEquals(list2[1], "writers");
}
@Test
public void testRoleCertValidate() throws IOException {
Path path = Paths.get("src/test/resources/athenz_role_uri.csr");
String csr = new String(Files.readAllBytes(path));
Set<String> orgValues = new HashSet<>();
orgValues.add("Athenz");
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
assertTrue(certReq.validate("athenz.production", "proxy.service", orgValues));
assertTrue(certReq.validate("athenz.production", "proxy.service", null));
assertFalse(certReq.validate("athenz.api", "proxy.service", orgValues));
assertFalse(certReq.validate("athenz.production", "proxy.api", orgValues));
Set<String> orgValues2 = new HashSet<>();
orgValues2.add("sports");
assertFalse(certReq.validate("athenz.production", "proxy.service", orgValues2));
}
@Test
public void testValidateMissingProxyUserUri() throws IOException {
Path path = Paths.get("src/test/resources/spiffe_role.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
Set<String> roles = new HashSet<>();
roles.add("api");
Set<String> orgValues = new HashSet<>();
orgValues.add("Athenz");
assertFalse(certReq.validate(roles, "coretech", "sports.api", "proxy.user", orgValues));
}
@Test
public void testValidateNoProxyUserUri() throws IOException {
Path path = Paths.get("src/test/resources/role_single_ip.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
Set<String> roles = new HashSet<>();
roles.add("writers");
Set<String> orgValues = new HashSet<>();
orgValues.add("Athenz");
assertFalse(certReq.validate(roles, "athenz", "athenz.production", "proxy.user", orgValues));
}
@Test
public void testValidateMultipleProxyUserUri() throws IOException {
Path path = Paths.get("src/test/resources/multiple_proxy_role.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
Set<String> roles = new HashSet<>();
roles.add("api");
Set<String> orgValues = new HashSet<>();
orgValues.add("Athenz");
assertFalse(certReq.validate(roles, "coretech", "sports.api", "proxy.user", orgValues));
}
@Test
public void testValidateProxyUserUri() throws IOException {
Path path = Paths.get("src/test/resources/proxy_role.csr");
String csr = new String(Files.readAllBytes(path));
X509RoleCertRequest certReq = new X509RoleCertRequest(csr);
Set<String> roles = new HashSet<>();
roles.add("api");
Set<String> orgValues = new HashSet<>();
orgValues.add("Athenz");
// valid proxy user
assertTrue(certReq.validate(roles, "coretech", "sports.api", "proxy.user", orgValues));
// mismatch proxy user
assertFalse(certReq.validate(roles, "coretech", "sports.api", "proxy2.user", orgValues));
}
}
| |
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.ruleunit.integrationtests;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.internal.utils.KieHelper;
import org.drools.ruleunit.DataSource;
import org.drools.ruleunit.RuleUnit;
import org.drools.ruleunit.RuleUnitExecutor;
import static org.drools.core.util.ClassUtils.getCanonicalSimpleName;
import static org.junit.Assert.assertEquals;
public class RuleUnitCoordinationTest {
@Test
public void testCoordination() throws Exception {
String drl1 =
"package org.drools.ruleunit.integrationtests\n" +
"unit " + getCanonicalSimpleName( MasterModelUnit.class ) + ";\n" +
"import " + MasterModel.class.getCanonicalName() + "\n" +
"import " + ApplicableModel.class.getCanonicalName() + "\n" +
"import " + ApplyMathModel.class.getCanonicalName() + "\n" +
"import " + ApplyStringModel.class.getCanonicalName() + "\n" +
"import " + ScheduledModelApplicationUnit.class.getCanonicalName() + "\n" +
"\n" +
"rule FindModelToApply \n" +
"when\n" +
" $mm: MasterModel( subModels != null ) from models\n" +
" $am: ApplicableModel( applied == false, $idx: index ) from $mm.subModels\n" +
//" not ApplicableModel( applied == false, index < $idx ) from $mm.subModels\n" +
"then\n" +
" applicableModels.insert($am);\n" +
" drools.run(new ScheduledModelApplicationUnit(models,applicableModels));\n" +
"end\n" +
"";
String drl2 =
"package org.drools.ruleunit.integrationtests\n" +
"unit " + getCanonicalSimpleName( ScheduledModelApplicationUnit.class ) + ";\n" +
"import " + MasterModel.class.getCanonicalName() + "\n" +
"import " + ApplicableModel.class.getCanonicalName() + "\n" +
"import " + ApplyMathModel.class.getCanonicalName() + "\n" +
"import " + ApplyStringModel.class.getCanonicalName() + "\n" +
"\n" +
"rule Apply_ApplyMathModel_Addition \n" +
"when\n" +
" $amm: ApplyMathModel( applied == false, inputValue1 != null, "+
" inputValue2 != null, operation == \"add\" ) from applicableModels\n" +
" $v1: Integer() from $amm.inputValue1 \n" +
" $v2: Integer() from $amm.inputValue2 \n" +
"then\n" +
" modify($amm) { \n" +
" setResult($v1.intValue() + $v2.intValue()), \n" +
" setApplied(true) \n" +
" };\n" +
" System.out.println(\"Result = \"+$amm.getResult());\n" +
"end\n" +
"\n" +
"rule Apply_ApplyStringModel_Concat \n" +
"when\n" +
" $asm: ApplyStringModel( applied == false, inputString1 != null, " +
" inputString2 != null, operation == \"concat\" ) from applicableModels \n" +
" $v1: String() from $asm.inputString1 \n" +
" $v2: String() from $asm.inputString2 \n" +
"then\n" +
" String result = $v1+\" \"+$v2; \n" +
" modify($asm) {\n" +
" setResult(result),\n" +
" setApplied(true)\n" +
" };\n" +
" System.out.println(\"Result = \"+$asm.getResult());\n" +
"end\n" +
"";
MasterModel master = new MasterModel("TestMaster");
ApplyMathModel mathModel = new ApplyMathModel(1, "Math1", "add", 10, 10);
ApplyStringModel stringModel = new ApplyStringModel(2, "String1", "concat", "hello", "world");
master.addSubModel(mathModel);
master.addSubModel(stringModel);
KieBase kbase = new KieHelper().addContent( drl1, ResourceType.DRL )
.addContent(drl2, ResourceType.DRL)
.build();
RuleUnitExecutor executor = RuleUnitExecutor.create().bind( kbase );
DataSource<MasterModel> masterModels = executor.newDataSource("models");
DataSource<ApplicableModel> applicableModels = executor.newDataSource("applicableModel");
FactHandle masterFH = masterModels.insert( master );
RuleUnit unit = new MasterModelUnit(masterModels,applicableModels);
// int x = 1;
// while (x > 0) {
// x = executor.run( unit );
// System.out.println( x );
// // I'm reinserting the master model to reinforce its evaluation, as I said in our call this is necessary because
// // the second level froms are made on plain lists which are not normally re-evaluated by from nodes (regardless of rule units).
// // In theory also the update should be more correct and enough to reinforce this re-evaluation, but for some reason
// // in this case is not working. I suspect we have a bug in our NotNode related to this specific case, but I'm still
// // evaluating it. For now the insert should be good enough to allow you to make some progress on this.
// // masterModels.update( masterFH, master, "subModels" );
// masterModels.insert( master );
// }
executor.run( unit );
assertEquals(20, (int)mathModel.getResult());
assertEquals("hello world", stringModel.getResult());
}
public static class BasicModel {
private int index;
private String name;
private String operation;
public BasicModel(int index, String name, String operation) {
this.index = index;
this.name = name;
this.operation = operation;
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public String getOperation() {
return operation;
}
}
public static class MasterModel extends BasicModel {
private List<ApplicableModel> subModels;
public MasterModel(String name) {
super(0,name,"master");
subModels = new ArrayList<>();
}
public List<ApplicableModel> getSubModels() {
return subModels;
}
public boolean addSubModel(ApplicableModel subModel) {
return subModels.add(subModel);
}
}
public abstract static class ApplicableModel extends BasicModel {
private boolean applied;
public ApplicableModel(int index, String name, String operation) {
super(index,name,operation);
this.applied = false;
}
public ApplicableModel(int index, String name, String operation, boolean applied) {
super(index,name,operation);
this.applied = applied;
}
public boolean isApplied() {
return applied;
}
public void setApplied(boolean applied) {
this.applied = applied;
}
public abstract Object getResult();
}
public static class ApplyMathModel extends ApplicableModel {
private Integer inputValue1;
private Integer inputValue2;
private Integer result;
public ApplyMathModel(int index, String name, String operation, Integer inputValue1, Integer inputValue2) {
super(index, name, operation);
this.inputValue1 = inputValue1;
this.inputValue2 = inputValue2;
}
public Integer getInputValue1() {
return inputValue1;
}
public void setInputValue1(Integer inputValue1) {
this.inputValue1 = inputValue1;
}
public Integer getInputValue2() {
return inputValue2;
}
public void setInputValue2(Integer inputValue2) {
this.inputValue2 = inputValue2;
}
public Integer getResult() {
return result;
}
public void setResult(Integer result) {
this.result = result;
}
}
public static class ApplyStringModel extends ApplicableModel {
private String inputString1;
private String inputString2;
private String result;
public ApplyStringModel(int index, String name, String operation, String inputString1, String inputString2) {
super(index,name,operation);
this.inputString1 = inputString1;
this.inputString2 = inputString2;
}
public String getInputString1() {
return inputString1;
}
public void setInputString1(String inputString1) {
this.inputString1 = inputString1;
}
public String getInputString2() {
return inputString2;
}
public void setInputString2(String inputString2) {
this.inputString2 = inputString2;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
public static class MasterModelUnit implements RuleUnit {
private DataSource<MasterModel> models;
private DataSource<ApplicableModel> applicableModels;
public MasterModelUnit(DataSource<MasterModel> models, DataSource<ApplicableModel> applicableModels) {
this.models = models;
this.applicableModels = applicableModels;
}
public DataSource<MasterModel> getModels() {
return models;
}
public DataSource<ApplicableModel> getApplicableModels() {
return applicableModels;
}
}
public static class ScheduledModelApplicationUnit implements RuleUnit {
private DataSource<MasterModel> models;
private DataSource<ApplicableModel> applicableModels;
public ScheduledModelApplicationUnit(DataSource<MasterModel> models, DataSource<ApplicableModel> applicableModels) {
this.models = models;
this.applicableModels = applicableModels;
}
public DataSource<MasterModel> getModels() {
return models;
}
public DataSource<ApplicableModel> getApplicableModels() {
return applicableModels;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.endpoint.dsl;
import javax.annotation.Generated;
import org.apache.camel.ExchangePattern;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
import org.apache.camel.spi.ExceptionHandler;
/**
* The jgroups component provides exchange of messages between Camel and JGroups
* clusters.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface JGroupsEndpointBuilderFactory {
/**
* Builder for endpoint consumers for the JGroups component.
*/
public interface JGroupsEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default AdvancedJGroupsEndpointConsumerBuilder advanced() {
return (AdvancedJGroupsEndpointConsumerBuilder) this;
}
/**
* Specifies configuration properties of the JChannel used by the
* endpoint.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default JGroupsEndpointConsumerBuilder channelProperties(
String channelProperties) {
setProperty("channelProperties", channelProperties);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Group: consumer
*/
default JGroupsEndpointConsumerBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
setProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: consumer
*/
default JGroupsEndpointConsumerBuilder bridgeErrorHandler(
String bridgeErrorHandler) {
setProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* If set to true, the consumer endpoint will receive org.jgroups.View
* messages as well (not only org.jgroups.Message instances). By default
* only regular messages are consumed by the endpoint.
*
* The option is a: <code>boolean</code> type.
*
* Group: consumer
*/
default JGroupsEndpointConsumerBuilder enableViewMessages(
boolean enableViewMessages) {
setProperty("enableViewMessages", enableViewMessages);
return this;
}
/**
* If set to true, the consumer endpoint will receive org.jgroups.View
* messages as well (not only org.jgroups.Message instances). By default
* only regular messages are consumed by the endpoint.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: consumer
*/
default JGroupsEndpointConsumerBuilder enableViewMessages(
String enableViewMessages) {
setProperty("enableViewMessages", enableViewMessages);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the JGroups component.
*/
public interface AdvancedJGroupsEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default JGroupsEndpointConsumerBuilder basic() {
return (JGroupsEndpointConsumerBuilder) this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*/
default AdvancedJGroupsEndpointConsumerBuilder exceptionHandler(
ExceptionHandler exceptionHandler) {
setProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedJGroupsEndpointConsumerBuilder exceptionHandler(
String exceptionHandler) {
setProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedJGroupsEndpointConsumerBuilder exchangePattern(
ExchangePattern exchangePattern) {
setProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedJGroupsEndpointConsumerBuilder exchangePattern(
String exchangePattern) {
setProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointConsumerBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
setProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointConsumerBuilder basicPropertyBinding(
String basicPropertyBinding) {
setProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointConsumerBuilder synchronous(
boolean synchronous) {
setProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointConsumerBuilder synchronous(
String synchronous) {
setProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint producers for the JGroups component.
*/
public interface JGroupsEndpointProducerBuilder
extends
EndpointProducerBuilder {
default AdvancedJGroupsEndpointProducerBuilder advanced() {
return (AdvancedJGroupsEndpointProducerBuilder) this;
}
/**
* Specifies configuration properties of the JChannel used by the
* endpoint.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default JGroupsEndpointProducerBuilder channelProperties(
String channelProperties) {
setProperty("channelProperties", channelProperties);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Group: producer
*/
default JGroupsEndpointProducerBuilder lazyStartProducer(
boolean lazyStartProducer) {
setProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: producer
*/
default JGroupsEndpointProducerBuilder lazyStartProducer(
String lazyStartProducer) {
setProperty("lazyStartProducer", lazyStartProducer);
return this;
}
}
/**
* Advanced builder for endpoint producers for the JGroups component.
*/
public interface AdvancedJGroupsEndpointProducerBuilder
extends
EndpointProducerBuilder {
default JGroupsEndpointProducerBuilder basic() {
return (JGroupsEndpointProducerBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointProducerBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
setProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointProducerBuilder basicPropertyBinding(
String basicPropertyBinding) {
setProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointProducerBuilder synchronous(
boolean synchronous) {
setProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointProducerBuilder synchronous(
String synchronous) {
setProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint for the JGroups component.
*/
public interface JGroupsEndpointBuilder
extends
JGroupsEndpointConsumerBuilder, JGroupsEndpointProducerBuilder {
default AdvancedJGroupsEndpointBuilder advanced() {
return (AdvancedJGroupsEndpointBuilder) this;
}
/**
* Specifies configuration properties of the JChannel used by the
* endpoint.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*/
default JGroupsEndpointBuilder channelProperties(
String channelProperties) {
setProperty("channelProperties", channelProperties);
return this;
}
}
/**
* Advanced builder for endpoint for the JGroups component.
*/
public interface AdvancedJGroupsEndpointBuilder
extends
AdvancedJGroupsEndpointConsumerBuilder, AdvancedJGroupsEndpointProducerBuilder {
default JGroupsEndpointBuilder basic() {
return (JGroupsEndpointBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
setProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointBuilder basicPropertyBinding(
String basicPropertyBinding) {
setProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointBuilder synchronous(boolean synchronous) {
setProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Group: advanced
*/
default AdvancedJGroupsEndpointBuilder synchronous(String synchronous) {
setProperty("synchronous", synchronous);
return this;
}
}
/**
* JGroups (camel-jgroups)
* The jgroups component provides exchange of messages between Camel and
* JGroups clusters.
*
* Category: clustering,messaging
* Available as of version: 2.13
* Maven coordinates: org.apache.camel:camel-jgroups
*
* Syntax: <code>jgroups:clusterName</code>
*
* Path parameter: clusterName (required)
* The name of the JGroups cluster the component should connect to.
*/
default JGroupsEndpointBuilder jGroups(String path) {
class JGroupsEndpointBuilderImpl extends AbstractEndpointBuilder implements JGroupsEndpointBuilder, AdvancedJGroupsEndpointBuilder {
public JGroupsEndpointBuilderImpl(String path) {
super("jgroups", path);
}
}
return new JGroupsEndpointBuilderImpl(path);
}
}
| |
package com.etk.network.server;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.LinkedList;
import com.etk.parser.SELECTMain;
import com.etk.parser.SelectObject;
import com.etk.parser.SelectQueryToObject;
class SessionHandler implements Runnable {
private Socket server_;
private String line_, input_;
SessionHandler(Socket server) {
this.server_ = server;
}
private byte[] nullTerminateString(String string) {
byte[] in = string.getBytes();
byte[] out = new byte[in.length + 1];
for (int i = 0; i < in.length; i++) {
out[i] = in[i];
}
out[in.length] = 0;
return out;
}
private void sendServerVersionMessage(DataOutputStream dataOutputStream)
throws IOException {
String param = "server_version";
String paramV = "9";
byte[] nameB = nullTerminateString(param); // PEACE OF SHIT NEEDS TO BE
// NULTERMINATED EVEN THOUGH DOCS
// DONT MENTION IT
byte[] valB = nullTerminateString(paramV);
dataOutputStream.writeByte('S');
dataOutputStream.writeInt(4 + nameB.length + valB.length);
dataOutputStream.write(nameB);
dataOutputStream.write(valB);
}
private void sendAuthenticationOkMessage(DataOutputStream dataOutputStream)
throws IOException {
dataOutputStream.writeByte('R');
dataOutputStream.writeInt(8);
dataOutputStream.writeInt(0);
}
private void sendReadyForQueryMessage(DataOutputStream dataOutputStream)
throws IOException {
dataOutputStream.writeByte('Z');
dataOutputStream.writeInt(5);
dataOutputStream.writeByte('I');
}
private void sendTerminateMessage(DataOutputStream dataOutputStream)
throws IOException {
dataOutputStream.writeByte('X');
dataOutputStream.writeInt(4);
}
private void sendCommandCompleteMessage(DataOutputStream dataOutputStream)
throws IOException {
dataOutputStream.writeByte('C');
String tmp = "SELECT 1";
dataOutputStream.writeInt(4 + tmp.getBytes().length);
dataOutputStream.write(tmp.getBytes());
}
private void sendParseCompleteMessage(DataOutputStream dataOutputStream)
throws IOException {
dataOutputStream.writeByte('1');
dataOutputStream.writeInt(4);
}
private void sendBindCompleteMessage(DataOutputStream dataOutputStream)
throws IOException {
dataOutputStream.writeByte('2');
dataOutputStream.writeInt(4);
}
private void sendEmptyQueryResponseMessage(DataOutputStream dataOutputStream)
throws IOException {
dataOutputStream.writeByte('I');
dataOutputStream.writeInt(4);
}
private void sendRowDescription(DataOutputStream dataOutputStream,
String[] columns) throws IOException {
short fieldsNo = (short) columns.length;
LinkedList<byte[]> bNameList = new LinkedList<byte[]>();
int identificator = 0;
short identificatorAtr = 0;
int typeInd = 0;
short typeLen = -2;
int typeMod = -1;
short formatCode = 0;
for (int i = 0; i < columns.length; i++) {
String name = columns[i];
byte[] bName = nullTerminateString(name);
bNameList.add(bName);
}
int totalSize = 8;
for (int i = 0; i < columns.length; i++) {
totalSize = totalSize + bNameList.get(i).length;
}
totalSize = totalSize + 14 * columns.length;
dataOutputStream.writeByte('T');
dataOutputStream.writeInt(totalSize);
dataOutputStream.writeShort(fieldsNo);
for (int i = 0; i < columns.length; i++) {
dataOutputStream.writeBytes(new String(bNameList.get(i)));
dataOutputStream.writeInt(identificator);
dataOutputStream.writeShort(identificatorAtr);
dataOutputStream.writeInt(typeInd);
dataOutputStream.writeShort(typeLen);
dataOutputStream.writeInt(typeMod);
dataOutputStream.writeShort(formatCode);
}
}
private void sendDataRow(DataOutputStream dataOutputStream, String[] values)
throws IOException {
int tLen = 0;
short num = (short) values.length;
LinkedList<Integer> lenColList = new LinkedList<Integer>();
LinkedList<byte[]> bvalList = new LinkedList<byte[]>();
for (int i = 0; i < values.length; i++) {
String val = values[i];
lenColList.add(nullTerminateString(val).length);
bvalList.add(nullTerminateString(val));
tLen = tLen + nullTerminateString(val).length;
}
tLen = tLen + 6 + 4 * values.length;
dataOutputStream.writeByte('D');
dataOutputStream.writeInt(tLen);
dataOutputStream.writeShort(num);
for (int i = 0; i < values.length; i++) {
dataOutputStream.writeInt(lenColList.get(i));
dataOutputStream.writeBytes(new String(
nullTerminateString(values[i])));
}
}
/* Data row incorrect, needs to be finished */
public void run() {
input_ = "";
try {
DataInputStream dataInputStream = new DataInputStream(
server_.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(
server_.getOutputStream());
MsgParser msgParser = new MsgParser();
int msgLen = dataInputStream.readInt();
short protocolMajorVersion = dataInputStream.readShort();
short protocolMinorVersion = dataInputStream.readShort();
byte[] authParamsB = new byte[msgLen - 8]; // msglen - version and
// len
dataInputStream.read(authParamsB);
// String authParams = msgParser.parseMsg(authParamsB);
System.out.println("Client connected!");
// System.out.println("Msg len: " + msgLen);
System.out.println("Protocol: V" + protocolMajorVersion + "."
+ protocolMinorVersion);
// System.out.println("Auth params: " + authParams);
sendAuthenticationOkMessage(dataOutputStream);
/*
* os.writeByte('K'); os.writeInt(12); os.writeInt(2);
* os.writeInt(3);
*/
this.sendServerVersionMessage(dataOutputStream);
this.sendReadyForQueryMessage(dataOutputStream);
dataOutputStream.flush();
/*
* I think now the client wants the result of the query
*/
// if (dataInputStream.available() > 0) {
byte type = dataInputStream.readByte();
int msgLength = dataInputStream.readInt();
System.out.println("Message Type: " + (char) type);
System.out.println("Lenght: " + msgLength);
byte[] buf = new byte[dataInputStream.available() - 4];
dataInputStream.read(buf);
String inputString = msgParser.parseMsg(buf);
System.out.println(inputString);
InputStream is = new ByteArrayInputStream(
inputString.getBytes("UTF-8"));
SelectQueryToObject transform = new SelectQueryToObject(is);
SelectObject selectObject = transform.getSelectObject();
System.out.println("Parser found tables: "
+ selectObject.getTableNames().toString()
+ "\nParser found columns: "
+ selectObject.getColumnNames().toString());
// InputStream is = new
// ByteArrayInputStream(inputString.getBytes("UTF-8"));
// SELECTMain.parse(is);
/*
* this is in case the server receive an empty query string and
* seems to work sendEmptyQueryResponseMessage(dataOutputStream);
* sendReadyForQueryMessage(dataOutputStream);
* dataOutputStream.flush();
*/
String[] columns = { "name", "surname" };
sendRowDescription(dataOutputStream, columns);
String[] values = { "david", "riobo" };
sendDataRow(dataOutputStream, values);
dataOutputStream.flush();
sendCommandCompleteMessage(dataOutputStream);
sendReadyForQueryMessage(dataOutputStream);
dataOutputStream.flush();
// reply to the client msg, delete exit
// }
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendData(DataOutputStream dataOutputStream) throws IOException {
/*
* RowDescription (B) Byte1('T') Identifies the message as a row
* description. Int32 Length of message contents in bytes, including
* self. Int16 Specifies the number of fields in a row (may be zero).
* Then, for each field, there is the following: String The field name.
* Int32 If the field can be identified as a column of a specific table,
* the object ID of the table; otherwise zero. Int16 If the field can be
* identified as a column of a specific table, the attribute number of
* the column; otherwise zero. Int32 The object ID of the field's data
* type. Int16 The data type size (see pg_type.typlen). Note that
* negative values denote variable-width types. Int32 The type modifier
* (see pg_attribute.atttypmod). The meaning of the modifier is
* type-specific. Int16 The format code being used for the field.
* Currently will be zero (text) or one (binary). In a RowDescription
* returned from the statement variant of Describe, the format code is
* not yet known and will always be zero.
*
* SSLRequest (F)
*/
short fieldsNo = 4;
String name = "name";
byte[] bName = nullTerminateString(name);
int identificator = 0;
short identificatorAtr = 0;
int typeInd = 0;
short typeLen = -2;
int typeMod = -1;
short formatCode = 0;
String name2 = "surname";
byte[] bName2 = nullTerminateString(name2);
int identificator2 = 0;
short identificatorAtr2 = 0;
int typeInd2 = 0;
short typeLen2 = -2;
int typeMod2 = -1;
short formatCode2 = 0;
String name3 = "date";
byte[] bName3 = nullTerminateString(name3);
int identificator3 = 0;
short identificatorAtr3 = 0;
int typeInd3 = 0;
short typeLen3 = -2;
int typeMod3 = -1;
short formatCode3 = 0;
String name4 = "number";
byte[] bName4 = nullTerminateString(name4);
int identificator4 = 0;
short identificatorAtr4 = 0;
int typeInd4 = 0;
short typeLen4 = -2;
int typeMod4 = -1;
short formatCode4 = 0;
int totalSize = bName.length + 4 + 2 + 4 + 2 + 4 + 2 + 4
+ bName3.length + 4 + 2 + 4 + 2 + 2 + bName4.length + 4 + 2 + 4
+ 2 + 2;
dataOutputStream.writeByte('T');
dataOutputStream.writeInt(totalSize);
dataOutputStream.writeShort(fieldsNo);
dataOutputStream.writeBytes(new String(bName));
dataOutputStream.writeInt(identificator);
dataOutputStream.writeShort(identificatorAtr);
dataOutputStream.writeInt(typeInd);
dataOutputStream.writeShort(typeLen);
dataOutputStream.writeInt(typeMod);
dataOutputStream.writeShort(formatCode);
dataOutputStream.writeBytes(new String(bName2));
dataOutputStream.writeInt(identificator2);
dataOutputStream.writeShort(identificatorAtr2);
dataOutputStream.writeInt(typeInd2);
dataOutputStream.writeShort(typeLen2);
dataOutputStream.writeInt(typeMod2);
dataOutputStream.writeShort(formatCode2);
dataOutputStream.writeBytes(new String(bName3));
dataOutputStream.writeInt(identificator3);
dataOutputStream.writeShort(identificatorAtr3);
dataOutputStream.writeInt(typeInd3);
dataOutputStream.writeShort(typeLen3);
dataOutputStream.writeInt(typeMod3);
dataOutputStream.writeShort(formatCode3);
dataOutputStream.writeBytes(new String(bName4));
dataOutputStream.writeInt(identificator4);
dataOutputStream.writeShort(identificatorAtr4);
dataOutputStream.writeInt(typeInd4);
dataOutputStream.writeShort(typeLen4);
dataOutputStream.writeInt(typeMod4);
dataOutputStream.writeShort(formatCode4);
/*
* Byte1('D') Identifies the message as a data row.
*
* Int32 Length of message contents in bytes, including self.
*
* Int16 The number of column values that follow (possibly zero).
*
* Next, the following pair of fields appear for each column:
*
* Int32 The length of the column value, in bytes (this count does not
* include itself). Can be zero. As a special case, -1 indicates a NULL
* column value. No value bytes follow in the NULL case.
*
* Byten The value of the column, in the format indicated by the
* associated format code. n is the above lengt
*/
for (int i = 0; i < 2; i++) {
int tLen = 0;
short num = 4;
String val = "david";
int lenCol = nullTerminateString(val).length;
byte[] bval = nullTerminateString(val);
String val2 = "riobo";
int lenCol2 = nullTerminateString(val2).length;
byte[] bval2 = nullTerminateString(val2);
String val3 = "1992-01-17";
int lenCol3 = nullTerminateString(val3).length;
byte[] bval3 = nullTerminateString(val3);
String val4 = "-87,61";
int lenCol4 = nullTerminateString(val4).length;
byte[] bval4 = nullTerminateString(val4);
tLen = 4 + 2 + 4 + bval.length + 4 + bval2.length + 4
+ bval3.length + 4 + bval4.length;
dataOutputStream.writeByte('D');
dataOutputStream.writeInt(tLen);
dataOutputStream.writeShort(num);
dataOutputStream.writeInt(lenCol);
dataOutputStream.writeBytes(new String(nullTerminateString(val)));
dataOutputStream.writeInt(lenCol2);
dataOutputStream.writeBytes(new String(nullTerminateString(val2)));
// Returns Bad value for type date : 1992-01-17
dataOutputStream.writeInt(lenCol3);
dataOutputStream.writeBytes(new String(nullTerminateString(val3)));
// Returns Bad value for type date too
dataOutputStream.writeInt(lenCol4);
dataOutputStream.writeBytes(new String(nullTerminateString(val4)));
}
dataOutputStream.flush();
}
private class MsgParser {
public short parseShort(byte[] bytes) {
byte[] typeBytes = new byte[2];
typeBytes[0] = 0;
typeBytes[1] = bytes[0];
return ByteBuffer.wrap(typeBytes).getShort();
}
public int parseInt(byte[] bytes) {
byte[] lenBytes = Arrays.copyOf(bytes, 4);
int len = ByteBuffer.wrap(lenBytes).getInt();
return len;
}
public String parseMsg(byte[] bytes)
throws UnsupportedEncodingException {
String msgString = new String(bytes, "UTF-8");
return msgString;
}
}
}
| |
package com.jdon.util.jdom;
/*--
Copyright (C) 2000 Brett McLaughlin & Jason Hunter.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the disclaimer that follows
these conditions in the documentation and/or other materials
provided with the distribution.
3. The name "JDOM" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact license@jdom.org.
4. Products derived from this software may not be called "JDOM", nor
may "JDOM" appear in their name, without prior written permission
from the JDOM Project Management (pm@jdom.org).
In addition, we request (but do not require) that you include in the
end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
"This product includes software developed by the
JDOM Project (http://www.jdom.org/)."
Alternatively, the acknowledgment may be graphical using the logos
available at http://www.jdom.org/images/logos.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
This software consists of voluntary contributions made by many
individuals on behalf of the JDOM Project and was originally
created by Brett McLaughlin <brett@jdom.org> and
Jason Hunter <jhunter@jdom.org>. For more information on the
JDOM Project, please see <http://www.jdom.org/>.
*/
import java.io.IOException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.XMLFilterImpl;
/**
* Adds convenience methods and lexical event filtering to base
* SAX2 Filter implementation.
*
* <i>Code and comments adapted from XMLWriter-0.2, written
* by David Megginson and released into the public domain,
* without warranty.</i>
*
* <p>The convenience methods are provided so that clients do not have to
* create empty attribute lists or provide empty strings as parameters;
* for example, the method invocation</p>
*
* <pre>
* w.startElement("foo");
* </pre>
*
* <p>is equivalent to the regular SAX2 ContentHandler method</p>
*
* <pre>
* w.startElement("", "foo", "", new AttributesImpl());
* </pre>
*
* <p>Except that it is more efficient because it does not allocate
* a new empty attribute list each time.</p>
*
* <p>In fact, there is an even simpler convenience method,
* <var>dataElement</var>, designed for writing elements that
* contain only character data.</p>
*
* <pre>
* w.dataElement("greeting", "Hello, world!");
* </pre>
*
* <p>is equivalent to</p>
*
* <pre>
* w.startElement("greeting");
* w.characters("Hello, world!");
* w.endElement("greeting");
* </pre>
*
* @see org.xml.sax.helpers.XMLFilterImpl
*/
public class XMLFilterBase extends XMLFilterImpl implements LexicalHandler
{
////////////////////////////////////////////////////////////////////
// Constructors.
////////////////////////////////////////////////////////////////////
/**
* Construct an XML filter with no parent.
*
* <p>This filter will have no parent: you must assign a parent
* before you start a parse or do any configuration with
* setFeature or setProperty.</p>
*
* @see org.xml.sax.XMLReader#setFeature
* @see org.xml.sax.XMLReader#setProperty
*/
public XMLFilterBase()
{
}
/**
* Create an XML filter with the specified parent.
*
* <p>Use the XMLReader provided as the source of events.</p>
*
* @param xmlreader The parent in the filter chain.
*/
public XMLFilterBase(XMLReader parent)
{
super(parent);
}
////////////////////////////////////////////////////////////////////
// Convenience methods.
////////////////////////////////////////////////////////////////////
/**
* Start a new element without a qname or attributes.
*
* <p>This method will provide a default empty attribute
* list and an empty string for the qualified name. It invokes
* {@link #startElement(String, String, String, Attributes)}
* directly.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement
*/
public void startElement (String uri, String localName)
throws SAXException
{
startElement(uri, localName, "", EMPTY_ATTS);
}
/**
* Start a new element without a Namespace URI or qname.
*
* <p>This method will provide an empty string for the
* Namespace URI, and empty string for the qualified name.
* It invokes
* {@link #startElement(String, String, String, Attributes)}
* directly.</p>
*
* @param localName The element's local name.
* @param atts The element's attribute list.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement
*/
public void startElement (String localName, Attributes atts)
throws SAXException
{
startElement("", localName, "", atts);
}
/**
* Start a new element without a Namespace URI, qname, or attributes.
*
* <p>This method will provide an empty string for the
* Namespace URI, and empty string for the qualified name,
* and a default empty attribute list. It invokes
* {@link #startElement(String, String, String, Attributes)}
* directly.</p>
*
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement
*/
public void startElement (String localName)
throws SAXException
{
startElement("", localName, "", EMPTY_ATTS);
}
/**
* End an element without a qname.
*
* <p>This method will supply an empty string for the qName.
* It invokes {@link #endElement(String, String, String)}
* directly.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#endElement
*/
public void endElement (String uri, String localName)
throws SAXException
{
endElement(uri, localName, "");
}
/**
* End an element without a Namespace URI or qname.
*
* <p>This method will supply an empty string for the qName
* and an empty string for the Namespace URI.
* It invokes {@link #endElement(String, String, String)}
* directly.</p>
*
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#endElement
*/
public void endElement (String localName)
throws SAXException
{
endElement("", localName, "");
}
/**
* Add an empty element.
*
* Both a {@link #startElement startElement} and an
* {@link #endElement endElement} event will be passed on down
* the filter chain.
*
* @param uri The element's Namespace URI, or the empty string
* if the element has no Namespace or if Namespace
* processing is not being performed.
* @param localName The element's local name (without prefix). This
* parameter must be provided.
* @param qName The element's qualified name (with prefix), or
* the empty string if none is available. This parameter
* is strictly advisory: the writer may or may not use
* the prefix attached.
* @param atts The element's attribute list.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement
* @see org.xml.sax.ContentHandler#endElement
*/
public void emptyElement (String uri, String localName,
String qName, Attributes atts)
throws SAXException
{
startElement(uri, localName, qName, atts);
endElement(uri, localName, qName);
}
/**
* Add an empty element without a qname or attributes.
*
* <p>This method will supply an empty string for the qname
* and an empty attribute list. It invokes
* {@link #emptyElement(String, String, String, Attributes)}
* directly.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see #emptyElement(String, String, String, Attributes)
*/
public void emptyElement (String uri, String localName)
throws SAXException
{
emptyElement(uri, localName, "", EMPTY_ATTS);
}
/**
* Add an empty element without a Namespace URI or qname.
*
* <p>This method will provide an empty string for the
* Namespace URI, and empty string for the qualified name.
* It invokes
* {@link #emptyElement(String, String, String, Attributes)}
* directly.</p>
*
* @param localName The element's local name.
* @param atts The element's attribute list.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement
*/
public void emptyElement (String localName, Attributes atts)
throws SAXException
{
emptyElement("", localName, "", atts);
}
/**
* Add an empty element without a Namespace URI, qname or attributes.
*
* <p>This method will supply an empty string for the qname,
* and empty string for the Namespace URI, and an empty
* attribute list. It invokes
* {@link #emptyElement(String, String, String, Attributes)}
* directly.</p>
*
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see #emptyElement(String, String, String, Attributes)
*/
public void emptyElement (String localName)
throws SAXException
{
emptyElement("", localName, "", EMPTY_ATTS);
}
/**
* Add an element with character data content.
*
* <p>This is a convenience method to add a complete element
* with character data content, including the start tag
* and end tag.</p>
*
* <p>This method invokes
* {@link @see org.xml.sax.ContentHandler#startElement},
* followed by
* {@link #characters(String)}, followed by
* {@link @see org.xml.sax.ContentHandler#endElement}.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @param qName The element's default qualified name.
* @param atts The element's attributes.
* @param content The character data content.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement
* @see #characters(String)
* @see org.xml.sax.ContentHandler#endElement
*/
public void dataElement (String uri, String localName,
String qName, Attributes atts,
String content)
throws SAXException
{
startElement(uri, localName, qName, atts);
characters(content);
endElement(uri, localName, qName);
}
/**
* Add an element with character data content but no qname or attributes.
*
* <p>This is a convenience method to add a complete element
* with character data content, including the start tag
* and end tag. This method provides an empty string
* for the qname and an empty attribute list. It invokes
* {@link #dataElement(String, String, String, Attributes, String)}}
* directly.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @param content The character data content.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement
* @see #characters(String)
* @see org.xml.sax.ContentHandler#endElement
*/
public void dataElement (String uri, String localName, String content)
throws SAXException
{
dataElement(uri, localName, "", EMPTY_ATTS, content);
}
/**
* Add an element with character data content but no Namespace URI or qname.
*
* <p>This is a convenience method to add a complete element
* with character data content, including the start tag
* and end tag. The method provides an empty string for the
* Namespace URI, and empty string for the qualified name. It invokes
* {@link #dataElement(String, String, String, Attributes, String)}}
* directly.</p>
*
* @param localName The element's local name.
* @param atts The element's attributes.
* @param content The character data content.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement
* @see #characters(String)
* @see org.xml.sax.ContentHandler#endElement
*/
public void dataElement (String localName, Attributes atts, String content)
throws SAXException
{
dataElement("", localName, "", atts, content);
}
/**
* Add an element with character data content but no attributes
* or Namespace URI.
*
* <p>This is a convenience method to add a complete element
* with character data content, including the start tag
* and end tag. The method provides an empty string for the
* Namespace URI, and empty string for the qualified name,
* and an empty attribute list. It invokes
* {@link #dataElement(String, String, String, Attributes, String)}}
* directly.</p>
*
* @param localName The element's local name.
* @param content The character data content.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement
* @see #characters(String)
* @see org.xml.sax.ContentHandler#endElement
*/
public void dataElement (String localName, String content)
throws SAXException
{
dataElement("", localName, "", EMPTY_ATTS, content);
}
/**
* Add a string of character data, with XML escaping.
*
* <p>This is a convenience method that takes an XML
* String, converts it to a character array, then invokes
* {@link @see org.xml.sax.ContentHandler#characters}.</p>
*
* @param data The character data.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see @see org.xml.sax.ContentHandler#characters
*/
public void characters (String data)
throws SAXException
{
char ch[] = data.toCharArray();
characters(ch, 0, ch.length);
}
////////////////////////////////////////////////////////////////////
// Override org.xml.sax.helpers.XMLFilterImpl methods.
////////////////////////////////////////////////////////////////////
/**
* Set the value of a property.
*
* <p>This will always fail if the parent is null.</p>
*
* @param name The property name.
* @param state The requested property value.
* @exception org.xml.sax.SAXNotRecognizedException When the
* XMLReader does not recognize the property name.
* @exception org.xml.sax.SAXNotSupportedException When the
* XMLReader recognizes the property name but
* cannot set the requested value.
* @see org.xml.sax.XMLReader#setProperty
*/
public void setProperty (String name, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException
{
for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
setLexicalHandler((LexicalHandler) value);
return;
}
}
super.setProperty(name, value);
}
/**
* Look up the value of a property.
*
* @param name The property name.
* @return The current value of the property.
* @exception org.xml.sax.SAXNotRecognizedException When the
* XMLReader does not recognize the feature name.
* @exception org.xml.sax.SAXNotSupportedException When the
* XMLReader recognizes the property name but
* cannot determine its value at this time.
* @see org.xml.sax.XMLReader#setFeature
*/
public Object getProperty (String name)
throws SAXNotRecognizedException, SAXNotSupportedException
{
for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
return getLexicalHandler();
}
}
return super.getProperty(name);
}
/**
* Parse a document.
*
* @param input The input source for the document entity.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @exception java.io.IOException An IO exception from the parser,
* possibly from a byte stream or character stream
* supplied by the application.
* @see org.xml.sax.XMLReader#parse(org.xml.sax.InputSource)
*/
public void parse (InputSource input)
throws SAXException, IOException
{
installLexicalHandler();
super.parse(input);
}
////////////////////////////////////////////////////////////////////
// Registration of org.xml.sax.ext.LexicalHandler.
////////////////////////////////////////////////////////////////////
/**
* Set the lexical handler.
*
* @param handler The new lexical handler.
* @exception java.lang.NullPointerException If the handler
* is null.
*/
public void setLexicalHandler (LexicalHandler handler)
{
if (handler == null) {
throw new NullPointerException("Null lexical handler");
} else {
lexicalHandler = handler;
}
}
/**
* Get the current lexical handler.
*
* @return The current lexical handler, or null if none was set.
*/
public LexicalHandler getLexicalHandler ()
{
return lexicalHandler;
}
////////////////////////////////////////////////////////////////////
// Implementation of org.xml.sax.ext.LexicalHandler.
////////////////////////////////////////////////////////////////////
/**
* Filter a start DTD event.
*
* @param name The document type name.
* @param publicId The declared public identifier for the
* external DTD subset, or null if none was declared.
* @param systemId The declared system identifier for the
* external DTD subset, or null if none was declared.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ext.LexicalHandler#startDTD
*/
public void startDTD(String name, String publicId, String systemId)
throws SAXException {
if (lexicalHandler != null) {
lexicalHandler.startDTD(name, publicId, systemId);
}
}
/**
* Filter a end DTD event.
*
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ext.LexicalHandler#endDTD
*/
public void endDTD()
throws SAXException {
if (lexicalHandler != null) {
lexicalHandler.endDTD();
}
}
/*
* Filter a start entity event.
*
* @param name The name of the entity. If it is a parameter
* entity, the name will begin with '%', and if it is the
* external DTD subset, it will be "[dtd]".
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ext.LexicalHandler#startEntity
*/
public void startEntity(String name)
throws SAXException {
if (lexicalHandler != null) {
lexicalHandler.startEntity(name);
}
}
/*
* Filter a end entity event.
*
* @param name The name of the entity that is ending.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ext.LexicalHandler#endEntity
*/
public void endEntity(String name)
throws SAXException {
if (lexicalHandler != null) {
lexicalHandler.endEntity(name);
}
}
/*
* Filter a start CDATA event.
*
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ext.LexicalHandler#startCDATA
*/
public void startCDATA()
throws SAXException {
if (lexicalHandler != null) {
lexicalHandler.startCDATA();
}
}
/*
* Filter a end CDATA event.
*
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ext.LexicalHandler#endCDATA
*/
public void endCDATA()
throws SAXException {
if (lexicalHandler != null) {
lexicalHandler.endCDATA();
}
}
/*
* Filter a comment event.
*
* @param ch An array holding the characters in the comment.
* @param start The starting position in the array.
* @param length The number of characters to use from the array.
* @exception org.xml.sax.SAXException If a filter
* further down the chain raises an exception.
* @see org.xml.sax.ext.LexicalHandler#comment
*/
public void comment(char[] ch, int start, int length)
throws SAXException {
if (lexicalHandler != null) {
lexicalHandler.comment(ch, start, length);
}
}
////////////////////////////////////////////////////////////////////
// Internal methods.
////////////////////////////////////////////////////////////////////
/**
* Installs lexical handler before a parse.
*
* <p>Before every parse, check whether the parent is
* non-null, and re-register the filter for the lexical
* events.</p>
*/
private void installLexicalHandler ()
{
XMLReader parent = getParent();
if (parent == null) {
throw new NullPointerException("No parent for filter");
}
// try to register for lexical events
for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
try {
parent.setProperty(LEXICAL_HANDLER_NAMES[i], this);
break;
}
catch (SAXNotRecognizedException ex) {
// ignore
}
catch (SAXNotSupportedException ex) {
// ignore
}
}
}
////////////////////////////////////////////////////////////////////
// Internal state.
////////////////////////////////////////////////////////////////////
private LexicalHandler lexicalHandler = null;
////////////////////////////////////////////////////////////////////
// Constants.
////////////////////////////////////////////////////////////////////
protected static final Attributes EMPTY_ATTS = new AttributesImpl();
protected static final String[] LEXICAL_HANDLER_NAMES = {
"http://xml.org/sax/properties/lexical-handler",
"http://xml.org/sax/handlers/LexicalHandler"
};
}
// end of XMLFilterBase.java
| |
package com.plainrequest.request;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.plainrequest.interfaces.OnInterceptRequest;
import com.plainrequest.interfaces.OnPlainRequest;
import com.plainrequest.model.Settings;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
/**
* Classe da Request customizada
*
* @author Giovani Moura
*/
class RequestCustom<T> extends Request<T> {
private final String TAG = "PLAINREQUEST";
private Settings settings;
private RequestParams requestParams;
private Type superClass;
private OnPlainRequest onPlainRequest;
private int statusCode;
private OnInterceptRequest onInterceptRequest;
private final String PROTOCOL_CHARSET = "UTF-8";
public RequestCustom(Settings settings, Type superClass, OnPlainRequest onPlainRequest, OnInterceptRequest onInterceptRequest) {
super(settings.method, settings.url, null);
this.settings = settings;
this.requestParams = new RequestParams(settings.params, settings.contentTypeEnum, PROTOCOL_CHARSET);
this.superClass = superClass;
this.onPlainRequest = onPlainRequest;
this.onInterceptRequest = onInterceptRequest;
this.setShouldCache(settings.cacheEnable);
// Define o timeout da request
setRetryPolicy(new DefaultRetryPolicy((settings.timeOutSeconds * 1000), 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleyLog.setTag(TAG);
}
@Override
protected void deliverResponse(T response) {
this.onPlainRequest.onSuccess(response, statusCode);
}
@Override
public void deliverError(VolleyError error) {
statusCode = error.networkResponse != null ? error.networkResponse.statusCode : 0;
String msgError = null;
if (error instanceof NetworkError) {
msgError = "Failed to connect to server";
} else if (error instanceof TimeoutError) {
msgError = "Timeout for connection exceeded";
} else {
if (error.networkResponse != null && error.networkResponse.data != null && !error.networkResponse.data.equals("")) {
try {
msgError = new String(error.networkResponse.data, PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
msgError = error.getMessage();
}
}
this.onPlainRequest.onError(error, msgError, statusCode);
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", getContentType());
if (onInterceptRequest != null) {
onInterceptRequest.interceptHeader(headers);
}
if (!settings.mapHeaders.isEmpty()) {
for (Map.Entry<String, String> entry : settings.mapHeaders.entrySet()) {
headers.put(entry.getKey(), entry.getValue());
}
}
return headers;
}
@Override
public String getUrl() {
return (super.getMethod() != Method.GET || requestParams.isNull()) ? super.getUrl() : getUrlGet();
}
/**
* Retorna a url concatenada com os parametros na request do tipo GET e que possue parametros
*
* @return
*/
private String getUrlGet() {
try {
return super.getUrl() + "?" + requestParams.getParamsQuery(); // concatena a url com os parametros
} catch (Exception e) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", new Object[]{requestParams.getParamsObj(), PROTOCOL_CHARSET});
return null;
} finally {
requestParams = null;
}
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestParams.isNull() ? null : requestParams.getParamsBody().getBytes(PROTOCOL_CHARSET);
} catch (Exception e) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", new Object[]{requestParams.getParamsObj(), PROTOCOL_CHARSET});
return null;
} finally {
requestParams = null;
}
}
@Override
public String getBodyContentType() {
return getContentType();
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
this.statusCode = response.statusCode;
return getResponse(response);
} catch (UnsupportedEncodingException e1) {
return Response.error(new ParseError(e1));
} catch (JSONException e2) {
return Response.error(new ParseError(e2));
}
}
/**
* Retorna o Response conforme seu tipo
*
* @param response
* @return
* @throws UnsupportedEncodingException
* @throws JSONException
*/
private Response getResponse(NetworkResponse response) throws UnsupportedEncodingException, JSONException {
T result;
byte[] data = response.data;
if (isResponseCompressed(response)) {
data = gzipToByte(data);
}
if (superClass.equals(JSONObject.class)) {
result = (T) new JSONObject(convertData(data));
} else if (superClass.equals(JSONArray.class)) {
result = (T) new JSONArray(convertData(data));
} else {
result = (T) convertData(data);
}
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
private String convertData(byte[] data) {
String strResult;
try {
strResult = new String(data, PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException var4) {
strResult = new String(data);
}
return strResult;
}
// private String getStrResult(byte[] data) throws UnsupportedEncodingException {
// return new String(data, PROTOCOL_CHARSET);
// }
private boolean isResponseCompressed(NetworkResponse response) {
return response.headers.containsKey("Content-Encoding") && response.headers.get("Content-Encoding").equalsIgnoreCase("gzip");
}
private byte[] gzipToByte(byte[] data) throws UnsupportedEncodingException {
byte[] bytes;
try {
GZIPInputStream gStream = new GZIPInputStream(new ByteArrayInputStream(data));
bytes = IOUtils.toByteArray(gStream);
} catch (IOException e) {
VolleyLog.wtf("Unsupported Encoding GZIP");
throw new UnsupportedEncodingException(e.getMessage());
}
return bytes;
}
private String getContentType() {
return String.format(this.settings.contentTypeEnum.getValue() + "; charset=%s", new Object[]{PROTOCOL_CHARSET});
}
}
| |
package com.stephentuso.welcome.ui;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import com.stephentuso.welcome.R;
import com.stephentuso.welcome.ui.view.WelcomeScreenBackgroundView;
import com.stephentuso.welcome.ui.view.WelcomeScreenViewPagerIndicator;
import com.stephentuso.welcome.util.SharedPreferencesHelper;
import com.stephentuso.welcome.util.WelcomeScreenConfiguration;
import com.stephentuso.welcome.util.WelcomeUtils;
public abstract class WelcomeActivity extends AppCompatActivity {
public static final String WELCOME_SCREEN_KEY = "welcome_screen_key";
ViewPager mViewPager;
WelcomeFragmentPagerAdapter mAdapter;
WelcomeScreenConfiguration mConfiguration;
WelcomeScreenItemList mItems = new WelcomeScreenItemList();
@Override
protected void onCreate(Bundle savedInstanceState) {
mConfiguration = configuration();
//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
super.setTheme(mConfiguration.getThemeResId());
/* Passing null for savedInstanceState fixes issue with fragments in list not matching
the displayed ones after the screen was rotated. (Parallax animations would stop working)
TODO: Look into this more
*/
super.onCreate(null);
setContentView(R.layout.activity_welcome);
mAdapter = new WelcomeFragmentPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(mAdapter);
if (mConfiguration.getShowActionBarBackButton()) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
actionBar.setDisplayHomeAsUpEnabled(true);
}
SkipButton skip = new SkipButton(findViewById(R.id.button_skip), mConfiguration.getCanSkip());
skip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
completeWelcomeScreen();
}
});
PreviousButton prev = new PreviousButton(findViewById(R.id.button_prev));
prev.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
scrollToPreviousPage();
}
});
NextButton next = new NextButton(findViewById(R.id.button_next));
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
scrollToNextPage();
}
});
DoneButton done = new DoneButton(findViewById(R.id.button_done));
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
completeWelcomeScreen();
}
});
WelcomeScreenViewPagerIndicator indicator = (WelcomeScreenViewPagerIndicator) findViewById(R.id.pager_indicator);
WelcomeScreenBackgroundView background = (WelcomeScreenBackgroundView) findViewById(R.id.background_view);
WelcomeScreenHider hider = new WelcomeScreenHider(findViewById(R.id.root));
hider.setOnViewHiddenListener(new WelcomeScreenHider.OnViewHiddenListener() {
@Override
public void onViewHidden() {
completeWelcomeScreen();
}
});
mItems = new WelcomeScreenItemList(background, indicator, skip, prev, next, done, hider, mConfiguration.getPages());
mViewPager.addOnPageChangeListener(mItems);
mViewPager.setCurrentItem(mConfiguration.firstPageIndex());
mItems.setup(mConfiguration);
mItems.onPageSelected(mViewPager.getCurrentItem());
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mViewPager != null) {
mViewPager.clearOnPageChangeListeners();
}
}
private boolean scrollToNextPage() {
if (!canScrollToNextPage())
return false;
mViewPager.setCurrentItem(getNextPageIndex());
return true;
}
private boolean scrollToPreviousPage() {
if (!canScrollToPreviousPage())
return false;
mViewPager.setCurrentItem(getPreviousPageIndex());
return true;
}
private int getNextPageIndex() {
return mViewPager.getCurrentItem() + (mConfiguration.isRtl() ? -1 : 1);
}
private int getPreviousPageIndex() {
return mViewPager.getCurrentItem() + (mConfiguration.isRtl() ? 1 : -1);
}
private boolean canScrollToNextPage() {
return mConfiguration.isRtl() ? getNextPageIndex() >= mConfiguration.lastViewablePageIndex() : getNextPageIndex() <= mConfiguration.lastViewablePageIndex();
}
private boolean canScrollToPreviousPage() {
return mConfiguration.isRtl() ? getPreviousPageIndex() <= mConfiguration.firstPageIndex() : getPreviousPageIndex() >= mConfiguration.firstPageIndex();
}
/**
* Closes the activity and saves it as completed.
* A subsequent call to WelcomeScreenHelper.show() would not show this again,
* unless the key is changed.
*/
protected void completeWelcomeScreen() {
SharedPreferencesHelper.storeWelcomeCompleted(this, getKey());
setWelcomeScreenResult(RESULT_OK);
super.finish();
if (mConfiguration.getExitAnimation() != WelcomeScreenConfiguration.NO_ANIMATION_SET)
overridePendingTransition(R.anim.none, mConfiguration.getExitAnimation());
}
/**
* Closes the activity, doesn't save as completed.
* A subsequent call to WelcomeScreenHelper.show() would show this again.
*/
protected void cancelWelcomeScreen() {
setWelcomeScreenResult(RESULT_CANCELED);
super.finish();
}
@Override
public void onBackPressed() {
boolean scrolledBack = false;
if (mConfiguration.getBackButtonNavigatesPages()) {
scrolledBack = scrollToPreviousPage();
}
if (!scrolledBack) {
if (mConfiguration.getCanSkip() && mConfiguration.getBackButtonSkips()) {
completeWelcomeScreen();
} else {
cancelWelcomeScreen();
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mConfiguration.getShowActionBarBackButton() && item.getItemId() == android.R.id.home) {
cancelWelcomeScreen();
return true;
}
return super.onOptionsItemSelected(item);
}
private void setWelcomeScreenResult(int resultCode) {
Intent intent = this.getIntent();
intent.putExtra(WELCOME_SCREEN_KEY, getKey());
this.setResult(resultCode, intent);
}
private String getKey() {
return WelcomeUtils.getKey(this.getClass());
}
protected abstract WelcomeScreenConfiguration configuration();
private class WelcomeFragmentPagerAdapter extends FragmentPagerAdapter {
public WelcomeFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mConfiguration.createFragment(position);
}
@Override
public int getCount() {
return mConfiguration.pageCount();
}
}
}
| |
package com.theisleoffavalon.mcmanager.permission;
import java.security.InvalidParameterException;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* A base implementation of the {@link IPermission} interface. This is the class
* that should be extended for all permission implementation classes.
*
* @author Cadyyan
*
*/
public abstract class BasePermission implements IPermission
{
/**
* The parent permission node.
*/
protected IPermission parent;
/**
* A string representation of the action. This is a set of strings that are
* delimited by the PERMISSION_NODE_DELIMITER character.
*/
protected String action;
/**
* The full action string of the node.
*/
protected String fullAction;
/**
* Is the permission allowed.
*/
protected boolean isAllowed;
/**
* The child permission nodes.
*/
protected Map<String, BasePermission> childPermissions;
/**
* Creates a permission object for the given action.
*
* @param action - the action string describing the action
* @param isAllowed - whether the action is allowed or not
*/
public BasePermission(String action, boolean isAllowed)
{
validateActionString(action);
this.parent = null;
this.fullAction = action;
this.action = action;
this.isAllowed = isAllowed;
this.childPermissions = new LinkedHashMap<String, BasePermission>();
}
/*
* (non-Javadoc)
* @see com.theisleoffavalon.mcmanager.permission.IPermission#getAction()
*/
@Override
public String getAction()
{
return fullAction;
}
/*
* (non-Javadoc)
* @see com.theisleoffavalon.mcmanager.permission.IPermission#isAllowed()
*/
@Override
public boolean isAllowed()
{
return isAllowed;
}
/*
* (non-Javadoc)
* @see com.theisleoffavalon.mcmanager.permission.IPermission#setAllowed(boolean)
*/
@Override
public void setAllowed(boolean isAllowed)
{
this.isAllowed = isAllowed;
}
/*
* (non-Javadoc)
* @see com.theisleoffavalon.mcmanager.permission.IPermission#isTopLevel()
*/
@Override
public boolean isTopLevel()
{
return parent == null;
}
/*
* (non-Javadoc)
* @see com.theisleoffavalon.mcmanager.permission.IPermission#addPermission(com.theisleoffavalon.mcmanager.permission.IPermission)
*/
@Override
public void addPermission(IPermission permission)
{
if(permission == null)
throw new NullPointerException("Cannot add a null permission.");
if(permission.getAction().equals(action))
{
isAllowed = permission.isAllowed();
return;
}
String actionStrings[] = permission.getAction().split(IPermission.PERMISSION_NODE_DELIMITER);
int index = 0;
String path = "";
String actionNode;
BasePermission perm = this;
do
{
actionNode = actionStrings[index++];
path = (path.isEmpty() ? "" : IPermission.PERMISSION_NODE_DELIMITER) + path;
if(perm.childPermissions.containsKey(actionNode))
perm = perm.childPermissions.get(actionNode);
else
{
BasePermission generic = new GenericPermission(path, perm.isAllowed());
perm.childPermissions.put(actionNode, generic);
perm = generic;
}
}
while(index < actionStrings.length - 1);
actionNode = actionStrings[index];
perm.childPermissions.put(actionNode, (BasePermission)permission);
}
/*
* (non-Javadoc)
* @see com.theisleoffavalon.mcmanager.permission.IPermission#getPermission(java.lang.String)
*/
@Override
public IPermission getPermission(String action)
{
validateActionString(action);
String actionStrings[] = action.split(IPermission.PERMISSION_NODE_DELIMITER);
return getPermission(actionStrings, 0);
}
/**
* Gets the permission for a given action. If the requested
* permission does not exist a default is given from the nearest wildcard/parent.
*
* @param actionNodes - the action
* @param current - the current location in the node list (default 0)
* @return the permission
*/
protected IPermission getPermission(String actionNodes[], int current)
{
if(current == actionNodes.length)
return this;
String action = actionNodes[current];
if(actionNodes.length - current == 1 && actionNodes[current].equals(IPermission.PERMISSION_WILDCARD))
return this;
BasePermission next = childPermissions.get(action);
return next.getPermission(actionNodes, current + 1);
}
/*
* (non-Javadoc)
* @see com.theisleoffavalon.mcmanager.permission.IPermission#getAllPermissions()
*/
@Override
public Set<IPermission> getAllPermissions()
{
Set<IPermission> perms = new LinkedHashSet<IPermission>();
getAllPermissions(perms);
return perms;
}
/**
* Returns the set of all child permission nodes.
*
* @param perms - the set to add the permissions to
*/
protected void getAllPermissions(Set<IPermission> perms)
{
perms.add(this);
for(BasePermission perm : childPermissions.values())
perm.getAllPermissions(perms);
}
/*
* (non-Javadoc)
* @see com.theisleoffavalon.mcmanager.permission.IPermission#removePermission(java.lang.String)
*/
@Override
public void removePermission(String action)
{
validateActionString(action);
String actionStrings[] = action.split(IPermission.PERMISSION_NODE_DELIMITER);
int index = 0;
}
/*
* (non-Javadoc)
* @see com.theisleoffavalon.mcmanager.permission.IPermission#removeAllPermissions()
*/
@Override
public void removeAllPermissions()
{
throw new RuntimeException("Unimplemented");
}
/**
* Checks that the given action string is valid.
*
* @param action - the action string
*/
protected void validateActionString(String action)
{
if(action == null)
throw new NullPointerException("The action string for a permission cannot be null.");
if(action.isEmpty())
throw new InvalidParameterException("The action string cannot be empty.");
// TODO: perform a regex check
}
}
| |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.11.09 at 02:07:25 PM AEDT
//
package au.com.scds.chats.fixture.jaxb.generated;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Names complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Names">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="regions">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="region" type="{http://scds.com.au/chats/fixture/jaxb/generated}Region" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="activityTypes">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="activityType" type="{http://scds.com.au/chats/fixture/jaxb/generated}ActivityType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="transportTypes">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="transportType" type="{http://scds.com.au/chats/fixture/jaxb/generated}TransportType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="periodicities">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="periodicity" type="{http://scds.com.au/chats/fixture/jaxb/generated}Periodicity" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="contactTypes">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="contactType" type="{http://scds.com.au/chats/fixture/jaxb/generated}ContactType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="sexes">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="sex" type="{http://scds.com.au/chats/fixture/jaxb/generated}Sex" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="statuses">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="status" type="{http://scds.com.au/chats/fixture/jaxb/generated}Status" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="volunteerRoles">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="volunteerRole" type="{http://scds.com.au/chats/fixture/jaxb/generated}VolunteerRole" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="salutations">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="salutation" type="{http://scds.com.au/chats/fixture/jaxb/generated}Salutation" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Names", propOrder = {
"regions",
"activityTypes",
"transportTypes",
"periodicities",
"contactTypes",
"sexes",
"statuses",
"volunteerRoles",
"salutations"
})
public class Names {
@XmlElement(required = true)
protected Names.Regions regions;
@XmlElement(required = true)
protected Names.ActivityTypes activityTypes;
@XmlElement(required = true)
protected Names.TransportTypes transportTypes;
@XmlElement(required = true)
protected Names.Periodicities periodicities;
@XmlElement(required = true)
protected Names.ContactTypes contactTypes;
@XmlElement(required = true)
protected Names.Sexes sexes;
@XmlElement(required = true)
protected Names.Statuses statuses;
@XmlElement(required = true)
protected Names.VolunteerRoles volunteerRoles;
@XmlElement(required = true)
protected Names.Salutations salutations;
/**
* Gets the value of the regions property.
*
* @return
* possible object is
* {@link Names.Regions }
*
*/
public Names.Regions getRegions() {
return regions;
}
/**
* Sets the value of the regions property.
*
* @param value
* allowed object is
* {@link Names.Regions }
*
*/
public void setRegions(Names.Regions value) {
this.regions = value;
}
/**
* Gets the value of the activityTypes property.
*
* @return
* possible object is
* {@link Names.ActivityTypes }
*
*/
public Names.ActivityTypes getActivityTypes() {
return activityTypes;
}
/**
* Sets the value of the activityTypes property.
*
* @param value
* allowed object is
* {@link Names.ActivityTypes }
*
*/
public void setActivityTypes(Names.ActivityTypes value) {
this.activityTypes = value;
}
/**
* Gets the value of the transportTypes property.
*
* @return
* possible object is
* {@link Names.TransportTypes }
*
*/
public Names.TransportTypes getTransportTypes() {
return transportTypes;
}
/**
* Sets the value of the transportTypes property.
*
* @param value
* allowed object is
* {@link Names.TransportTypes }
*
*/
public void setTransportTypes(Names.TransportTypes value) {
this.transportTypes = value;
}
/**
* Gets the value of the periodicities property.
*
* @return
* possible object is
* {@link Names.Periodicities }
*
*/
public Names.Periodicities getPeriodicities() {
return periodicities;
}
/**
* Sets the value of the periodicities property.
*
* @param value
* allowed object is
* {@link Names.Periodicities }
*
*/
public void setPeriodicities(Names.Periodicities value) {
this.periodicities = value;
}
/**
* Gets the value of the contactTypes property.
*
* @return
* possible object is
* {@link Names.ContactTypes }
*
*/
public Names.ContactTypes getContactTypes() {
return contactTypes;
}
/**
* Sets the value of the contactTypes property.
*
* @param value
* allowed object is
* {@link Names.ContactTypes }
*
*/
public void setContactTypes(Names.ContactTypes value) {
this.contactTypes = value;
}
/**
* Gets the value of the sexes property.
*
* @return
* possible object is
* {@link Names.Sexes }
*
*/
public Names.Sexes getSexes() {
return sexes;
}
/**
* Sets the value of the sexes property.
*
* @param value
* allowed object is
* {@link Names.Sexes }
*
*/
public void setSexes(Names.Sexes value) {
this.sexes = value;
}
/**
* Gets the value of the statuses property.
*
* @return
* possible object is
* {@link Names.Statuses }
*
*/
public Names.Statuses getStatuses() {
return statuses;
}
/**
* Sets the value of the statuses property.
*
* @param value
* allowed object is
* {@link Names.Statuses }
*
*/
public void setStatuses(Names.Statuses value) {
this.statuses = value;
}
/**
* Gets the value of the volunteerRoles property.
*
* @return
* possible object is
* {@link Names.VolunteerRoles }
*
*/
public Names.VolunteerRoles getVolunteerRoles() {
return volunteerRoles;
}
/**
* Sets the value of the volunteerRoles property.
*
* @param value
* allowed object is
* {@link Names.VolunteerRoles }
*
*/
public void setVolunteerRoles(Names.VolunteerRoles value) {
this.volunteerRoles = value;
}
/**
* Gets the value of the salutations property.
*
* @return
* possible object is
* {@link Names.Salutations }
*
*/
public Names.Salutations getSalutations() {
return salutations;
}
/**
* Sets the value of the salutations property.
*
* @param value
* allowed object is
* {@link Names.Salutations }
*
*/
public void setSalutations(Names.Salutations value) {
this.salutations = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="activityType" type="{http://scds.com.au/chats/fixture/jaxb/generated}ActivityType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"activityType"
})
public static class ActivityTypes {
@XmlElement(required = true)
protected List<String> activityType;
/**
* Gets the value of the activityType property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the activityType property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getActivityType().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getActivityType() {
if (activityType == null) {
activityType = new ArrayList<String>();
}
return this.activityType;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="contactType" type="{http://scds.com.au/chats/fixture/jaxb/generated}ContactType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"contactType"
})
public static class ContactTypes {
@XmlElement(required = true)
protected List<String> contactType;
/**
* Gets the value of the contactType property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the contactType property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContactType().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getContactType() {
if (contactType == null) {
contactType = new ArrayList<String>();
}
return this.contactType;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="periodicity" type="{http://scds.com.au/chats/fixture/jaxb/generated}Periodicity" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"periodicity"
})
public static class Periodicities {
@XmlElement(required = true)
@XmlSchemaType(name = "string")
protected List<Periodicity> periodicity;
/**
* Gets the value of the periodicity property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the periodicity property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPeriodicity().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Periodicity }
*
*
*/
public List<Periodicity> getPeriodicity() {
if (periodicity == null) {
periodicity = new ArrayList<Periodicity>();
}
return this.periodicity;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="region" type="{http://scds.com.au/chats/fixture/jaxb/generated}Region" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"region"
})
public static class Regions {
@XmlElement(required = true)
protected List<String> region;
/**
* Gets the value of the region property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the region property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRegion().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getRegion() {
if (region == null) {
region = new ArrayList<String>();
}
return this.region;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="salutation" type="{http://scds.com.au/chats/fixture/jaxb/generated}Salutation" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"salutation"
})
public static class Salutations {
@XmlElement(required = true)
protected List<Salutation> salutation;
/**
* Gets the value of the salutation property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the salutation property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSalutation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Salutation }
*
*
*/
public List<Salutation> getSalutation() {
if (salutation == null) {
salutation = new ArrayList<Salutation>();
}
return this.salutation;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="sex" type="{http://scds.com.au/chats/fixture/jaxb/generated}Sex" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"sex"
})
public static class Sexes {
@XmlElement(required = true)
@XmlSchemaType(name = "string")
protected List<Sex> sex;
/**
* Gets the value of the sex property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the sex property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSex().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Sex }
*
*
*/
public List<Sex> getSex() {
if (sex == null) {
sex = new ArrayList<Sex>();
}
return this.sex;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="status" type="{http://scds.com.au/chats/fixture/jaxb/generated}Status" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"status"
})
public static class Statuses {
@XmlElement(required = true)
@XmlSchemaType(name = "string")
protected List<Status> status;
/**
* Gets the value of the status property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the status property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getStatus().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Status }
*
*
*/
public List<Status> getStatus() {
if (status == null) {
status = new ArrayList<Status>();
}
return this.status;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="transportType" type="{http://scds.com.au/chats/fixture/jaxb/generated}TransportType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"transportType"
})
public static class TransportTypes {
@XmlElement(required = true)
protected List<String> transportType;
/**
* Gets the value of the transportType property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the transportType property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTransportType().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getTransportType() {
if (transportType == null) {
transportType = new ArrayList<String>();
}
return this.transportType;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="volunteerRole" type="{http://scds.com.au/chats/fixture/jaxb/generated}VolunteerRole" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"volunteerRole"
})
public static class VolunteerRoles {
@XmlElement(required = true)
protected List<String> volunteerRole;
/**
* Gets the value of the volunteerRole property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the volunteerRole property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getVolunteerRole().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getVolunteerRole() {
if (volunteerRole == null) {
volunteerRole = new ArrayList<String>();
}
return this.volunteerRole;
}
}
}
| |
package org.rabix.bindings.protocol.draft2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.rabix.bindings.BindingException;
import org.rabix.bindings.ProtocolCommandLineBuilder;
import org.rabix.bindings.model.Job;
import org.rabix.bindings.protocol.draft2.bean.Draft2CommandLineTool;
import org.rabix.bindings.protocol.draft2.bean.Draft2InputPort;
import org.rabix.bindings.protocol.draft2.bean.Draft2Job;
import org.rabix.bindings.protocol.draft2.expression.Draft2ExpressionException;
import org.rabix.bindings.protocol.draft2.expression.helper.Draft2ExpressionBeanHelper;
import org.rabix.bindings.protocol.draft2.helper.Draft2BindingHelper;
import org.rabix.bindings.protocol.draft2.helper.Draft2FileValueHelper;
import org.rabix.bindings.protocol.draft2.helper.Draft2JobHelper;
import org.rabix.bindings.protocol.draft2.helper.Draft2SchemaHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
public class Draft2CommandLineBuilder implements ProtocolCommandLineBuilder {
public static final String PART_SEPARATOR = "\u0020";
private final static Logger logger = LoggerFactory.getLogger(Draft2CommandLineBuilder.class);
@Override
public String buildCommandLine(Job job) throws BindingException {
Draft2Job draft2Job = Draft2JobHelper.getDraft2Job(job);
if (draft2Job.getApp().isExpressionTool()) {
return null;
}
return buildCommandLine(draft2Job);
}
@Override
public List<String> buildCommandLineParts(Job job) throws BindingException {
Draft2Job draft2Job = Draft2JobHelper.getDraft2Job(job);
if (!draft2Job.getApp().isCommandLineTool()) {
return null;
}
return Lists.transform(buildCommandLineParts(draft2Job), new Function<Object, String>() {
public String apply(Object obj) {
return obj.toString();
}
});
}
/**
* Builds command line string with both STDIN and STDOUT
*/
public String buildCommandLine(Draft2Job job) throws BindingException {
Draft2CommandLineTool commandLineTool = (Draft2CommandLineTool) job.getApp();
List<Object> commandLineParts = buildCommandLineParts(job);
StringBuilder builder = new StringBuilder();
for (Object commandLinePart : commandLineParts) {
builder.append(commandLinePart).append(PART_SEPARATOR);
}
String stdin = null;
try {
stdin = commandLineTool.getStdin(job);
} catch (Draft2ExpressionException e) {
logger.error("Failed to extract standard input.", e);
throw new BindingException("Failed to extract standard input.", e);
}
if (!StringUtils.isEmpty(stdin)) {
builder.append(PART_SEPARATOR).append("<").append(PART_SEPARATOR).append(stdin);
}
String stdout = null;
try {
stdout = commandLineTool.getStdout(job);
} catch (Draft2ExpressionException e) {
logger.error("Failed to extract standard output.", e);
throw new BindingException("Failed to extract standard outputs.", e);
}
if (!StringUtils.isEmpty(stdout)) {
builder.append(PART_SEPARATOR).append(">").append(PART_SEPARATOR).append(stdout);
}
String commandLine = normalizeCommandLine(builder.toString());
logger.info("Command line built. CommandLine = {}", commandLine);
return commandLine;
}
/**
* Normalize command line (remove multiple spaces, etc.)
*/
private String normalizeCommandLine(String commandLine) {
return commandLine.trim().replaceAll(PART_SEPARATOR + "+", PART_SEPARATOR);
}
/**
* Build command line arguments
*/
public List<Object> buildCommandLineParts(Draft2Job job) throws BindingException {
logger.info("Building command line parts...");
Draft2CommandLineTool commandLineTool = (Draft2CommandLineTool) job.getApp();
List<Draft2InputPort> inputPorts = commandLineTool.getInputs();
List<Object> result = new LinkedList<>();
try {
List<Object> baseCmds = commandLineTool.getBaseCmd(job);
result.addAll(baseCmds);
List<Draft2CommandLinePart> commandLineParts = new LinkedList<>();
if (commandLineTool.hasArguments()) {
for (int i = 0; i < commandLineTool.getArguments().size(); i++) {
Object argBinding = commandLineTool.getArguments().get(i);
if (argBinding instanceof String) {
Draft2CommandLinePart commandLinePart = new Draft2CommandLinePart.Builder(0, false).part(argBinding).keyValue("").build();
commandLinePart.setArgsArrayOrder(i);
commandLineParts.add(commandLinePart);
continue;
}
Object argValue = commandLineTool.getArgument(job, argBinding);
Map<String, Object> emptySchema = new HashMap<>();
Draft2CommandLinePart commandLinePart = buildCommandLinePart(job, null, argBinding, argValue, emptySchema, null);
if (commandLinePart != null) {
commandLinePart.setArgsArrayOrder(i);
commandLineParts.add(commandLinePart);
}
}
}
for (Draft2InputPort inputPort : inputPorts) {
String key = inputPort.getId();
Object schema = inputPort.getSchema();
Draft2CommandLinePart part = buildCommandLinePart(job, inputPort, inputPort.getInputBinding(), job.getInputs().get(Draft2SchemaHelper.normalizeId(key)), schema, key);
if (part != null) {
commandLineParts.add(part);
}
}
Collections.sort(commandLineParts, new Draft2CommandLinePart.CommandLinePartComparator());
for (Draft2CommandLinePart part : commandLineParts) {
List<Object> flattenedObjects = part.flatten();
for (Object obj : flattenedObjects) {
result.add(obj);
}
}
} catch (Draft2ExpressionException e) {
logger.error("Failed to build command line.", e);
throw new BindingException("Failed to build command line.", e);
}
return result;
}
@SuppressWarnings("unchecked")
private Draft2CommandLinePart buildCommandLinePart(Draft2Job job, Draft2InputPort inputPort, Object inputBinding, Object value, Object schema, String key) throws BindingException {
logger.debug("Building command line part for value {} and schema {}", value, schema);
Draft2CommandLineTool commandLineTool = (Draft2CommandLineTool) job.getApp();
if (inputBinding == null) {
return null;
}
int position = Draft2BindingHelper.getPosition(inputBinding);
String separator = Draft2BindingHelper.getSeparator(inputBinding);
String prefix = Draft2BindingHelper.getPrefix(inputBinding);
String itemSeparator = Draft2BindingHelper.getItemSeparator(inputBinding);
String keyValue = inputPort != null ? inputPort.getId() : "";
Object valueFrom = Draft2BindingHelper.getValueFrom(inputBinding);
if (valueFrom != null) {
if (Draft2ExpressionBeanHelper.isExpression(valueFrom)) {
try {
value = Draft2ExpressionBeanHelper.evaluate(job, value, valueFrom);
} catch (Draft2ExpressionException e) {
throw new BindingException(e);
}
} else {
value = valueFrom;
}
}
boolean isFile = Draft2SchemaHelper.isFileFromValue(value);
if (isFile) {
value = Draft2FileValueHelper.getPath(value);
}
if (value == null) {
return null;
}
if (value instanceof Boolean) {
if (((Boolean) value)) {
if (prefix == null) {
throw new BindingException("Missing prefix for " + inputPort.getId() + " input.");
}
return new Draft2CommandLinePart.Builder(position, isFile).part(prefix).keyValue(keyValue).build();
} else {
return null;
}
}
if (value instanceof Map<?, ?>) {
Draft2CommandLinePart.Builder commandLinePartBuilder = new Draft2CommandLinePart.Builder(position, isFile);
commandLinePartBuilder.keyValue(keyValue);
for (Entry<String, Object> entry : ((Map<String, Object>) value).entrySet()) {
String fieldKey = entry.getKey();
Object fieldValue = entry.getValue();
Object field = Draft2SchemaHelper.getField(fieldKey, Draft2SchemaHelper.getSchemaForRecordField(job.getApp().getSchemaDefs(), schema));
if (field == null) {
logger.info("Field {} not found in schema {}", fieldKey, schema);
continue;
}
Object fieldBinding = Draft2SchemaHelper.getInputBinding(field);
Object fieldType = Draft2SchemaHelper.getType(field);
Object fieldSchema = Draft2SchemaHelper.findSchema(commandLineTool.getSchemaDefs(), fieldType);
Draft2CommandLinePart fieldCommandLinePart = buildCommandLinePart(job, inputPort, fieldBinding, fieldValue, fieldSchema, fieldKey);
if (fieldCommandLinePart != null) {
fieldCommandLinePart.setKeyValue(fieldKey);
commandLinePartBuilder.part(fieldCommandLinePart);
}
}
return commandLinePartBuilder.build().sort();
}
if (value instanceof List<?>) {
Draft2CommandLinePart.Builder commandLinePartBuilder = new Draft2CommandLinePart.Builder(position, isFile);
commandLinePartBuilder.keyValue(keyValue);
for (Object item : ((List<?>) value)) {
Object arrayItemSchema = Draft2SchemaHelper.getSchemaForArrayItem(commandLineTool.getSchemaDefs(), schema);
Object arrayItemInputBinding = new HashMap<>();
if (schema != null && Draft2SchemaHelper.getInputBinding(schema) != null) {
arrayItemInputBinding = (Map<String, Object>) Draft2SchemaHelper.getInputBinding(schema);
}
Draft2CommandLinePart subpart = buildCommandLinePart(job, inputPort, arrayItemInputBinding, item, arrayItemSchema, key);
if (subpart != null) {
commandLinePartBuilder.part(subpart);
}
}
Draft2CommandLinePart commandLinePart = commandLinePartBuilder.build();
List<Object> flattenedValues = commandLinePart.flatten();
if (itemSeparator != null) {
String joinedItems = Joiner.on(itemSeparator).join(flattenedValues);
if (prefix == null) {
return new Draft2CommandLinePart.Builder(position, isFile).part(joinedItems).build();
}
if (StringUtils.isWhitespace(separator)) {
return new Draft2CommandLinePart.Builder(position, isFile).keyValue(keyValue).part(prefix).part(joinedItems).build();
} else {
return new Draft2CommandLinePart.Builder(position, isFile).keyValue(keyValue).part(prefix + separator + joinedItems).build();
}
}
if (prefix == null) {
return new Draft2CommandLinePart.Builder(position, isFile).keyValue(keyValue).parts(flattenedValues).build();
}
List<Object> prefixedValues = new ArrayList<>();
for (Object arrayItem : flattenedValues) {
prefixedValues.add(prefix + separator + arrayItem);
}
return new Draft2CommandLinePart.Builder(position, isFile).keyValue(keyValue).parts(prefixedValues).build();
}
if (prefix == null) {
return new Draft2CommandLinePart.Builder(position, isFile).keyValue(keyValue).part(value).build();
}
if (Draft2BindingHelper.DEFAULT_SEPARATOR.equals(separator)) {
return new Draft2CommandLinePart.Builder(position, isFile).keyValue(keyValue).part(prefix).part(value).build();
}
return new Draft2CommandLinePart.Builder(position, isFile).keyValue(keyValue).part(prefix + separator + value).build();
}
}
| |
/* Copyright (c) 2001-2010, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb.jdbc;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import org.hsqldb.HsqlException;
import org.hsqldb.SessionInterface;
import org.hsqldb.error.ErrorCode;
import org.hsqldb.types.BlobDataID;
/**
* A wrapper for HSQLDB BlobData objects.
*
* Instances of this class are returnd by calls to ResultSet methods.
*
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 2.0
* @since 1.9.0
*/
public class JDBCBlobClient implements Blob {
/**
* Returns the number of bytes in the <code>BLOB</code> value designated
* by this <code>Blob</code> object.
*
* @return length of the <code>BLOB</code> in bytes
* @throws SQLException if there is an error accessing the length of the
* <code>BLOB</code>
*/
public synchronized long length() throws SQLException {
try {
return blob.length(session);
} catch (HsqlException e) {
throw Util.sqlException(e);
}
}
/**
* Retrieves all or part of the <code>BLOB</code> value that this
* <code>Blob</code> object represents, as an array of bytes.
*
* @param pos the ordinal position of the first byte in the
* <code>BLOB</code> value to be extracted; the first byte is at
* position 1
* @param length the number of consecutive bytes to be copied
* @return a byte array containing up to <code>length</code> consecutive
* bytes from the <code>BLOB</code> value designated by this
* <code>Blob</code> object, starting with the byte at position
* <code>pos</code>
* @throws SQLException if there is an error accessing the
* <code>BLOB</code> value
*/
public synchronized byte[] getBytes(long pos,
int length) throws SQLException {
if (!isInLimits(Long.MAX_VALUE, pos - 1, length)) {
throw Util.outOfRangeArgument();
}
try {
return blob.getBytes(session, pos - 1, length);
} catch (HsqlException e) {
throw Util.sqlException(e);
}
}
/**
* Retrieves the <code>BLOB</code> value designated by this
* <code>Blob</code> instance as a stream.
*
* @return a stream containing the <code>BLOB</code> data
* @throws SQLException if there is an error accessing the
* <code>BLOB</code> value
*/
public synchronized InputStream getBinaryStream() throws SQLException {
return new BlobInputStream(this, 0, length(),
session.getStreamBlockSize());
}
/**
* Retrieves the byte position at which the specified byte array
* <code>pattern</code> begins within the <code>BLOB</code> value that
* this <code>Blob</code> object represents.
*
* @param pattern the byte array for which to search
* @param start the position at which to begin searching; the first
* position is 1
* @return the position at which the pattern appears, else -1
* @throws SQLException if there is an error accessing the
* <code>BLOB</code>
*/
public synchronized long position(byte[] pattern,
long start) throws SQLException {
if (!isInLimits(Long.MAX_VALUE, start, 0)) {
throw Util.outOfRangeArgument();
}
try {
return blob.position(session, pattern, start - 1);
} catch (HsqlException e) {
throw Util.sqlException(e);
}
}
/**
* Retrieves the byte position in the <code>BLOB</code> value designated
* by this <code>Blob</code> object at which <code>pattern</code> begins.
*
* @param pattern the <code>Blob</code> object designating the
* <code>BLOB</code> value for which to search
* @param start the position in the <code>BLOB</code> value at which to
* begin searching; the first position is 1
* @return the position at which the pattern begins, else -1
* @throws SQLException if there is an error accessing the
* <code>BLOB</code> value
*/
public synchronized long position(Blob pattern,
long start) throws SQLException {
if (!isInLimits(Integer.MAX_VALUE, 0, pattern.length())) {
throw Util.outOfRangeArgument();
}
byte[] bytePattern = pattern.getBytes(1, (int) pattern.length());
return position(bytePattern, start);
}
/**
* Writes the given array of bytes to the <code>BLOB</code> value that
* this <code>Blob</code> object represents, starting at position
* <code>pos</code>, and returns the number of bytes written.
*
* @param pos the position in the <code>BLOB</code> object at which to
* start writing
* @param bytes the array of bytes to be written to the
* <code>BLOB</code> value that this <code>Blob</code> object
* represents
* @return the number of bytes written
* @throws SQLException if there is an error accessing the
* <code>BLOB</code> value
*/
public synchronized int setBytes(long pos,
byte[] bytes) throws SQLException {
throw Util.notSupported();
/*
if (!isInLimits(Long.MAX_VALUE, pos - 1, bytes.length)) {
throw Util.outOfRangeArgument();
}
try {
return blob.setBytes(session, pos - 1, bytes);
} catch (HsqlException e) {
throw Util.sqlException(e);
}
*/
}
/**
* Writes all or part of the given <code>byte</code> array to the
* <code>BLOB</code> value that this <code>Blob</code> object represents
* and returns the number of bytes written.
*
* @param pos the position in the <code>BLOB</code> object at which to
* start writing
* @param bytes the array of bytes to be written to this
* <code>BLOB</code> object
* @param offset the offset into the array <code>bytes</code> at which
* to start reading the bytes to be set
* @param len the number of bytes to be written to the <code>BLOB</code>
* value from the array of bytes <code>bytes</code>
* @return the number of bytes written
* @throws SQLException if there is an error accessing the
* <code>BLOB</code> value
*/
public synchronized int setBytes(long pos, byte[] bytes, int offset,
int len) throws SQLException {
throw Util.notSupported();
/*
if (!isInLimits(bytes.length, offset, len)) {
throw Util.outOfRangeArgument();
}
if (offset != 0 || len != bytes.length) {
byte[] newBytes = new byte[len];
System.arraycopy(bytes, (int) offset, newBytes, 0, len);
bytes = newBytes;
}
return setBytes(pos, bytes);
*/
}
/**
* Retrieves a stream that can be used to write to the <code>BLOB</code>
* value that this <code>Blob</code> object represents.
*
* @param pos the position in the <code>BLOB</code> value at which to
* start writing
* @return a <code>java.io.OutputStream</code> object to which data can
* be written
* @throws SQLException if there is an error accessing the
* <code>BLOB</code> value
*/
public synchronized OutputStream setBinaryStream(long pos)
throws SQLException {
throw Util.notSupported();
}
/**
* Truncates the <code>BLOB</code> value that this <code>Blob</code>
* object represents to be <code>len</code> bytes in length.
*
* @param len the length, in bytes, to which the <code>BLOB</code> value
* that this <code>Blob</code> object represents should be truncated
* @throws SQLException if there is an error accessing the
* <code>BLOB</code> value
*/
public synchronized void truncate(long len) throws SQLException {
try {
blob.truncate(session, len);
} catch (HsqlException e) {
throw Util.sqlException(e);
}
}
/**
* This method frees the <code>Blob</code> object and releases the resources that
* it holds. The object is invalid once the <code>free</code>
* method is called.
* <p>
* After <code>free</code> has been called, any attempt to invoke a
* method other than <code>free</code> will result in a <code>SQLException</code>
* being thrown. If <code>free</code> is called multiple times, the subsequent
* calls to <code>free</code> are treated as a no-op.
* <p>
*
* @throws SQLException if an error occurs releasing
* the Blob's resources
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since JDK 1.6, HSQLDB 2.0
*/
public synchronized void free() throws SQLException {
isClosed = true;
}
/**
* Returns an <code>InputStream</code> object that contains a partial <code>Blob</code> value,
* starting with the byte specified by pos, which is length bytes in length.
*
* @param pos the offset to the first byte of the partial value to be retrieved.
* The first byte in the <code>Blob</code> is at position 1
* @param length the length in bytes of the partial value to be retrieved
* @return <code>InputStream</code> through which the partial <code>Blob</code> value can be read.
* @throws SQLException if pos is less than 1 or if pos is greater than the number of bytes
* in the <code>Blob</code> or if pos + length is greater than the number of bytes
* in the <code>Blob</code>
*
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since JDK 1.6, HSQLDB 2.0
*/
public synchronized InputStream getBinaryStream(long pos,
long length) throws SQLException {
if (!isInLimits(Long.MAX_VALUE, pos - 1, length)) {
throw Util.outOfRangeArgument();
}
return new BlobInputStream(this, pos - 1, length,
session.getStreamBlockSize());
}
//--
BlobDataID blob;
SessionInterface session;
boolean isClosed;
JDBCBlobClient(SessionInterface session, BlobDataID blob) {
this.session = session;
this.blob = blob;
}
public boolean isClosed() {
return isClosed;
}
private void checkClosed() throws SQLException {
if (isClosed) {
throw Util.sqlException(ErrorCode.X_07501);
}
}
static boolean isInLimits(long fullLength, long pos, long len) {
return pos >= 0 && len >= 0 && pos + len <= fullLength;
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.orc.metadata.statistics;
import com.google.common.collect.ImmutableList;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import static com.facebook.presto.orc.metadata.statistics.ColumnStatistics.mergeColumnStatistics;
import static java.lang.Math.min;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
public abstract class AbstractStatisticsBuilderTest<B extends StatisticsBuilder, T>
{
public enum StatisticsType
{
NONE, BOOLEAN, INTEGER, DOUBLE, STRING, DATE, DECIMAL
}
private final StatisticsType statisticsType;
private final Supplier<B> statisticsBuilderSupplier;
private final BiConsumer<B, T> adder;
public AbstractStatisticsBuilderTest(StatisticsType statisticsType, Supplier<B> statisticsBuilderSupplier, BiConsumer<B, T> adder)
{
this.statisticsType = statisticsType;
this.statisticsBuilderSupplier = statisticsBuilderSupplier;
this.adder = adder;
}
@Test
public void testNoValue()
{
B statisticsBuilder = statisticsBuilderSupplier.get();
AggregateColumnStatistics aggregateColumnStatistics = new AggregateColumnStatistics();
assertNoColumnStatistics(statisticsBuilder.buildColumnStatistics(), 0);
aggregateColumnStatistics.add(statisticsBuilder.buildColumnStatistics());
assertNoColumnStatistics(aggregateColumnStatistics.getMergedColumnStatistics(Optional.empty()), 0);
assertNoColumnStatistics(statisticsBuilder.buildColumnStatistics(), 0);
aggregateColumnStatistics.add(statisticsBuilder.buildColumnStatistics());
assertNoColumnStatistics(aggregateColumnStatistics.getMergedColumnStatistics(Optional.empty()), 0);
assertNoColumnStatistics(statisticsBuilder.buildColumnStatistics(), 0);
aggregateColumnStatistics.add(statisticsBuilder.buildColumnStatistics());
assertNoColumnStatistics(aggregateColumnStatistics.getMergedColumnStatistics(Optional.empty()), 0);
}
public void assertMinAverageValueBytes(long expectedAverageValueBytes, List<T> values)
{
// test add value
B statisticsBuilder = statisticsBuilderSupplier.get();
for (T value : values) {
adder.accept(statisticsBuilder, value);
}
assertEquals(statisticsBuilder.buildColumnStatistics().getMinAverageValueSizeInBytes(), expectedAverageValueBytes);
// test merge
statisticsBuilder = statisticsBuilderSupplier.get();
for (int i = 0; i < values.size() / 2; i++) {
adder.accept(statisticsBuilder, values.get(i));
}
ColumnStatistics firstStats = statisticsBuilder.buildColumnStatistics();
statisticsBuilder = statisticsBuilderSupplier.get();
for (int i = values.size() / 2; i < values.size(); i++) {
adder.accept(statisticsBuilder, values.get(i));
}
ColumnStatistics secondStats = statisticsBuilder.buildColumnStatistics();
assertEquals(mergeColumnStatistics(ImmutableList.of(firstStats, secondStats)).getMinAverageValueSizeInBytes(), expectedAverageValueBytes);
}
public void assertMinMaxValues(T expectedMin, T expectedMax)
{
// just min
assertValues(expectedMin, expectedMin, ImmutableList.of(expectedMin));
// just max
assertValues(expectedMax, expectedMax, ImmutableList.of(expectedMax));
// both
assertValues(expectedMin, expectedMax, ImmutableList.of(expectedMin, expectedMax));
}
public void assertValues(T expectedMin, T expectedMax, List<T> values)
{
assertValuesInternal(expectedMin, expectedMax, values);
assertValuesInternal(expectedMin, expectedMax, ImmutableList.copyOf(values).reverse());
List<T> randomOrder = new ArrayList<>(values);
Collections.shuffle(randomOrder, new Random(42));
assertValuesInternal(expectedMin, expectedMax, randomOrder);
}
private void assertValuesInternal(T expectedMin, T expectedMax, List<T> values)
{
B statisticsBuilder = statisticsBuilderSupplier.get();
AggregateColumnStatistics aggregateColumnStatistics = new AggregateColumnStatistics();
aggregateColumnStatistics.add(statisticsBuilder.buildColumnStatistics());
assertColumnStatistics(statisticsBuilder.buildColumnStatistics(), 0, null, null, aggregateColumnStatistics);
for (int loop = 0; loop < 4; loop++) {
for (T value : values) {
adder.accept(statisticsBuilder, value);
aggregateColumnStatistics.add(statisticsBuilder.buildColumnStatistics());
}
assertColumnStatistics(statisticsBuilder.buildColumnStatistics(), values.size() * (loop + 1), expectedMin, expectedMax, aggregateColumnStatistics);
}
}
public static void assertNoColumnStatistics(ColumnStatistics columnStatistics, int expectedNumberOfValues)
{
assertEquals(columnStatistics.getNumberOfValues(), expectedNumberOfValues);
assertNull(columnStatistics.getBooleanStatistics());
assertNull(columnStatistics.getIntegerStatistics());
assertNull(columnStatistics.getDoubleStatistics());
assertNull(columnStatistics.getStringStatistics());
assertNull(columnStatistics.getDateStatistics());
assertNull(columnStatistics.getDecimalStatistics());
assertNull(columnStatistics.getBloomFilter());
}
private void assertColumnStatistics(
ColumnStatistics columnStatistics,
int expectedNumberOfValues,
T expectedMin,
T expectedMax,
AggregateColumnStatistics aggregateColumnStatistics)
{
assertColumnStatistics(columnStatistics, expectedNumberOfValues, expectedMin, expectedMax);
// merge in forward order
int totalCount = aggregateColumnStatistics.getTotalCount();
assertColumnStatistics(aggregateColumnStatistics.getMergedColumnStatistics(Optional.empty()), totalCount, expectedMin, expectedMax);
assertColumnStatistics(aggregateColumnStatistics.getMergedColumnStatisticsPairwise(Optional.empty()), totalCount, expectedMin, expectedMax);
// merge in a random order
for (int i = 0; i < 10; i++) {
assertColumnStatistics(aggregateColumnStatistics.getMergedColumnStatistics(Optional.of(ThreadLocalRandom.current())), totalCount, expectedMin, expectedMax);
assertColumnStatistics(aggregateColumnStatistics.getMergedColumnStatisticsPairwise(Optional.of(ThreadLocalRandom.current())), totalCount, expectedMin, expectedMax);
}
List<ColumnStatistics> statisticsList = aggregateColumnStatistics.getStatisticsList();
assertNoColumnStatistics(mergeColumnStatistics(insertEmptyColumnStatisticsAt(statisticsList, 0, 10)), totalCount + 10);
assertNoColumnStatistics(mergeColumnStatistics(insertEmptyColumnStatisticsAt(statisticsList, statisticsList.size(), 10)), totalCount + 10);
assertNoColumnStatistics(mergeColumnStatistics(insertEmptyColumnStatisticsAt(statisticsList, statisticsList.size() / 2, 10)), totalCount + 10);
}
static List<ColumnStatistics> insertEmptyColumnStatisticsAt(List<ColumnStatistics> statisticsList, int index, long numberOfValues)
{
List<ColumnStatistics> newStatisticsList = new ArrayList<>(statisticsList);
newStatisticsList.add(index, new ColumnStatistics(numberOfValues, 0, null, null, null, null, null, null, null, null));
return newStatisticsList;
}
public void assertColumnStatistics(ColumnStatistics columnStatistics, int expectedNumberOfValues, T expectedMin, T expectedMax)
{
assertEquals(columnStatistics.getNumberOfValues(), expectedNumberOfValues);
if (statisticsType == StatisticsType.BOOLEAN && expectedNumberOfValues > 0) {
assertNotNull(columnStatistics.getBooleanStatistics());
}
else {
assertNull(columnStatistics.getBooleanStatistics());
}
if (statisticsType == StatisticsType.INTEGER && expectedNumberOfValues > 0) {
assertRangeStatistics(columnStatistics.getIntegerStatistics(), expectedMin, expectedMax);
}
else {
assertNull(columnStatistics.getIntegerStatistics());
}
if (statisticsType == StatisticsType.DOUBLE && expectedNumberOfValues > 0) {
assertRangeStatistics(columnStatistics.getDoubleStatistics(), expectedMin, expectedMax);
}
else {
assertNull(columnStatistics.getDoubleStatistics());
}
if (statisticsType == StatisticsType.STRING && expectedNumberOfValues > 0) {
assertRangeStatistics(columnStatistics.getStringStatistics(), expectedMin, expectedMax);
}
else {
assertNull(columnStatistics.getStringStatistics());
}
if (statisticsType == StatisticsType.DATE && expectedNumberOfValues > 0) {
assertRangeStatistics(columnStatistics.getDateStatistics(), expectedMin, expectedMax);
}
else {
assertNull(columnStatistics.getDateStatistics());
}
if (statisticsType == StatisticsType.DECIMAL && expectedNumberOfValues > 0) {
assertRangeStatistics(columnStatistics.getDecimalStatistics(), expectedMin, expectedMax);
}
else {
assertNull(columnStatistics.getDecimalStatistics());
}
assertNull(columnStatistics.getBloomFilter());
}
void assertRangeStatistics(RangeStatistics<?> rangeStatistics, T expectedMin, T expectedMax)
{
assertNotNull(rangeStatistics);
assertEquals(rangeStatistics.getMin(), expectedMin);
assertEquals(rangeStatistics.getMax(), expectedMax);
}
public static class AggregateColumnStatistics
{
private int totalCount;
private final ImmutableList.Builder<ColumnStatistics> statisticsList = ImmutableList.builder();
public void add(ColumnStatistics columnStatistics)
{
totalCount += columnStatistics.getNumberOfValues();
statisticsList.add(columnStatistics);
}
public int getTotalCount()
{
return totalCount;
}
public List<ColumnStatistics> getStatisticsList()
{
return statisticsList.build();
}
public ColumnStatistics getMergedColumnStatistics(Optional<Random> random)
{
List<ColumnStatistics> statistics = new ArrayList<>(statisticsList.build());
random.ifPresent(rand -> Collections.shuffle(statistics, rand));
return mergeColumnStatistics(ImmutableList.copyOf(statistics));
}
public ColumnStatistics getMergedColumnStatisticsPairwise(Optional<Random> random)
{
List<ColumnStatistics> statistics = new ArrayList<>(statisticsList.build());
random.ifPresent(rand -> Collections.shuffle(statistics, rand));
return getMergedColumnStatisticsPairwise(ImmutableList.copyOf(statistics));
}
private static ColumnStatistics getMergedColumnStatisticsPairwise(List<ColumnStatistics> statistics)
{
while (statistics.size() > 1) {
ImmutableList.Builder<ColumnStatistics> mergedStatistics = ImmutableList.builder();
for (int i = 0; i < statistics.size(); i += 2) {
mergedStatistics.add(mergeColumnStatistics(statistics.subList(i, min(i + 2, statistics.size()))));
}
statistics = mergedStatistics.build();
}
return statistics.get(0);
}
}
}
| |
// Generated from ../src/cl/kaiser/odata/OdataFilter.g4 by ANTLR 4.5.3
package cl.kaiser.odata.gen;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.misc.*;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class OdataFilterLexer extends Lexer {
static { RuntimeMetaData.checkVersion("4.5.3", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9,
T__9=10, T__10=11, T__11=12, T__12=13, T__13=14, T__14=15, T__15=16, T__16=17,
T__17=18, T__18=19, T__19=20, T__20=21, Number=22, Variable=23, IdentName=24,
CharacterLiteral=25, StringLiteral=26, FloatingPointLiteral=27, WS=28;
public static String[] modeNames = {
"DEFAULT_MODE"
};
public static final String[] ruleNames = {
"T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8",
"T__9", "T__10", "T__11", "T__12", "T__13", "T__14", "T__15", "T__16",
"T__17", "T__18", "T__19", "T__20", "Number", "Variable", "IdentName",
"CharacterLiteral", "StringLiteral", "FloatingPointLiteral", "Digit",
"Letter", "EscapeSequence", "OctalEscape", "UnicodeEscape", "HexDigit",
"Exponent", "FloatTypeSuffix", "WS"
};
private static final String[] _LITERAL_NAMES = {
null, "'('", "')'", "'or'", "'and'", "'eq'", "'ne'", "'ge'", "'gt'", "'le'",
"'lt'", "'eq null'", "'ne null'", "'eq '''", "'ne '''", "'startswith'",
"','", "'endswith'", "'substringof'", "'datetime'", "'tolower'", "'toupper'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, "Number",
"Variable", "IdentName", "CharacterLiteral", "StringLiteral", "FloatingPointLiteral",
"WS"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
public OdataFilterLexer(CharStream input) {
super(input);
_interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
@Override
public String getGrammarFileName() { return "OdataFilter.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
public ATN getATN() { return _ATN; }
public static final String _serializedATN =
"\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\2\36\u015c\b\1\4\2"+
"\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4"+
"\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22"+
"\t\22\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31"+
"\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\4 \t"+
" \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%\3\2\3\2\3\3\3\3\3\4\3\4\3\4\3\5\3\5"+
"\3\5\3\5\3\6\3\6\3\6\3\7\3\7\3\7\3\b\3\b\3\b\3\t\3\t\3\t\3\n\3\n\3\n\3"+
"\13\3\13\3\13\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r"+
"\3\r\3\r\3\16\3\16\3\16\3\16\3\16\3\16\3\17\3\17\3\17\3\17\3\17\3\17\3"+
"\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\21\3\21\3\22\3"+
"\22\3\22\3\22\3\22\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\23\3\23\3"+
"\23\3\23\3\23\3\23\3\23\3\23\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3"+
"\24\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\26\3\26\3\26\3\26\3\26\3"+
"\26\3\26\3\26\3\27\5\27\u00c1\n\27\3\27\6\27\u00c4\n\27\r\27\16\27\u00c5"+
"\3\30\6\30\u00c9\n\30\r\30\16\30\u00ca\3\30\7\30\u00ce\n\30\f\30\16\30"+
"\u00d1\13\30\3\31\3\31\6\31\u00d5\n\31\r\31\16\31\u00d6\3\31\3\31\3\31"+
"\7\31\u00dc\n\31\f\31\16\31\u00df\13\31\3\32\3\32\3\32\7\32\u00e4\n\32"+
"\f\32\16\32\u00e7\13\32\3\32\3\32\3\33\3\33\3\33\7\33\u00ee\n\33\f\33"+
"\16\33\u00f1\13\33\3\33\3\33\3\34\5\34\u00f6\n\34\3\34\6\34\u00f9\n\34"+
"\r\34\16\34\u00fa\3\34\3\34\7\34\u00ff\n\34\f\34\16\34\u0102\13\34\3\34"+
"\5\34\u0105\n\34\3\34\5\34\u0108\n\34\3\34\5\34\u010b\n\34\3\34\3\34\6"+
"\34\u010f\n\34\r\34\16\34\u0110\3\34\5\34\u0114\n\34\3\34\5\34\u0117\n"+
"\34\3\34\5\34\u011a\n\34\3\34\6\34\u011d\n\34\r\34\16\34\u011e\3\34\3"+
"\34\5\34\u0123\n\34\3\34\5\34\u0126\n\34\3\34\6\34\u0129\n\34\r\34\16"+
"\34\u012a\3\34\5\34\u012e\n\34\3\35\3\35\3\36\3\36\3\37\3\37\3\37\3\37"+
"\5\37\u0138\n\37\3 \3 \3 \3 \3 \3 \3 \3 \3 \5 \u0143\n \3!\3!\3!\3!\3"+
"!\3!\3!\3\"\3\"\3#\3#\5#\u0150\n#\3#\6#\u0153\n#\r#\16#\u0154\3$\3$\3"+
"%\3%\3%\3%\2\2&\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31"+
"\16\33\17\35\20\37\21!\22#\23%\24\'\25)\26+\27-\30/\31\61\32\63\33\65"+
"\34\67\359\2;\2=\2?\2A\2C\2E\2G\2I\36\3\2\f\4\2//aa\4\2))^^\4\2$$^^\4"+
"\2C\\c|\n\2$$))^^ddhhppttvv\5\2\62;CHch\4\2GGgg\4\2--//\6\2FFHHffhh\5"+
"\2\13\f\16\17\"\"\u0177\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2"+
"\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25"+
"\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2"+
"\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2"+
"\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2\65\3\2\2\2\2\67\3"+
"\2\2\2\2I\3\2\2\2\3K\3\2\2\2\5M\3\2\2\2\7O\3\2\2\2\tR\3\2\2\2\13V\3\2"+
"\2\2\rY\3\2\2\2\17\\\3\2\2\2\21_\3\2\2\2\23b\3\2\2\2\25e\3\2\2\2\27h\3"+
"\2\2\2\31p\3\2\2\2\33x\3\2\2\2\35~\3\2\2\2\37\u0084\3\2\2\2!\u008f\3\2"+
"\2\2#\u0091\3\2\2\2%\u009a\3\2\2\2\'\u00a6\3\2\2\2)\u00af\3\2\2\2+\u00b7"+
"\3\2\2\2-\u00c0\3\2\2\2/\u00c8\3\2\2\2\61\u00d4\3\2\2\2\63\u00e0\3\2\2"+
"\2\65\u00ea\3\2\2\2\67\u012d\3\2\2\29\u012f\3\2\2\2;\u0131\3\2\2\2=\u0137"+
"\3\2\2\2?\u0142\3\2\2\2A\u0144\3\2\2\2C\u014b\3\2\2\2E\u014d\3\2\2\2G"+
"\u0156\3\2\2\2I\u0158\3\2\2\2KL\7*\2\2L\4\3\2\2\2MN\7+\2\2N\6\3\2\2\2"+
"OP\7q\2\2PQ\7t\2\2Q\b\3\2\2\2RS\7c\2\2ST\7p\2\2TU\7f\2\2U\n\3\2\2\2VW"+
"\7g\2\2WX\7s\2\2X\f\3\2\2\2YZ\7p\2\2Z[\7g\2\2[\16\3\2\2\2\\]\7i\2\2]^"+
"\7g\2\2^\20\3\2\2\2_`\7i\2\2`a\7v\2\2a\22\3\2\2\2bc\7n\2\2cd\7g\2\2d\24"+
"\3\2\2\2ef\7n\2\2fg\7v\2\2g\26\3\2\2\2hi\7g\2\2ij\7s\2\2jk\7\"\2\2kl\7"+
"p\2\2lm\7w\2\2mn\7n\2\2no\7n\2\2o\30\3\2\2\2pq\7p\2\2qr\7g\2\2rs\7\"\2"+
"\2st\7p\2\2tu\7w\2\2uv\7n\2\2vw\7n\2\2w\32\3\2\2\2xy\7g\2\2yz\7s\2\2z"+
"{\7\"\2\2{|\7)\2\2|}\7)\2\2}\34\3\2\2\2~\177\7p\2\2\177\u0080\7g\2\2\u0080"+
"\u0081\7\"\2\2\u0081\u0082\7)\2\2\u0082\u0083\7)\2\2\u0083\36\3\2\2\2"+
"\u0084\u0085\7u\2\2\u0085\u0086\7v\2\2\u0086\u0087\7c\2\2\u0087\u0088"+
"\7t\2\2\u0088\u0089\7v\2\2\u0089\u008a\7u\2\2\u008a\u008b\7y\2\2\u008b"+
"\u008c\7k\2\2\u008c\u008d\7v\2\2\u008d\u008e\7j\2\2\u008e \3\2\2\2\u008f"+
"\u0090\7.\2\2\u0090\"\3\2\2\2\u0091\u0092\7g\2\2\u0092\u0093\7p\2\2\u0093"+
"\u0094\7f\2\2\u0094\u0095\7u\2\2\u0095\u0096\7y\2\2\u0096\u0097\7k\2\2"+
"\u0097\u0098\7v\2\2\u0098\u0099\7j\2\2\u0099$\3\2\2\2\u009a\u009b\7u\2"+
"\2\u009b\u009c\7w\2\2\u009c\u009d\7d\2\2\u009d\u009e\7u\2\2\u009e\u009f"+
"\7v\2\2\u009f\u00a0\7t\2\2\u00a0\u00a1\7k\2\2\u00a1\u00a2\7p\2\2\u00a2"+
"\u00a3\7i\2\2\u00a3\u00a4\7q\2\2\u00a4\u00a5\7h\2\2\u00a5&\3\2\2\2\u00a6"+
"\u00a7\7f\2\2\u00a7\u00a8\7c\2\2\u00a8\u00a9\7v\2\2\u00a9\u00aa\7g\2\2"+
"\u00aa\u00ab\7v\2\2\u00ab\u00ac\7k\2\2\u00ac\u00ad\7o\2\2\u00ad\u00ae"+
"\7g\2\2\u00ae(\3\2\2\2\u00af\u00b0\7v\2\2\u00b0\u00b1\7q\2\2\u00b1\u00b2"+
"\7n\2\2\u00b2\u00b3\7q\2\2\u00b3\u00b4\7y\2\2\u00b4\u00b5\7g\2\2\u00b5"+
"\u00b6\7t\2\2\u00b6*\3\2\2\2\u00b7\u00b8\7v\2\2\u00b8\u00b9\7q\2\2\u00b9"+
"\u00ba\7w\2\2\u00ba\u00bb\7r\2\2\u00bb\u00bc\7r\2\2\u00bc\u00bd\7g\2\2"+
"\u00bd\u00be\7t\2\2\u00be,\3\2\2\2\u00bf\u00c1\7/\2\2\u00c0\u00bf\3\2"+
"\2\2\u00c0\u00c1\3\2\2\2\u00c1\u00c3\3\2\2\2\u00c2\u00c4\59\35\2\u00c3"+
"\u00c2\3\2\2\2\u00c4\u00c5\3\2\2\2\u00c5\u00c3\3\2\2\2\u00c5\u00c6\3\2"+
"\2\2\u00c6.\3\2\2\2\u00c7\u00c9\5;\36\2\u00c8\u00c7\3\2\2\2\u00c9\u00ca"+
"\3\2\2\2\u00ca\u00c8\3\2\2\2\u00ca\u00cb\3\2\2\2\u00cb\u00cf\3\2\2\2\u00cc"+
"\u00ce\59\35\2\u00cd\u00cc\3\2\2\2\u00ce\u00d1\3\2\2\2\u00cf\u00cd\3\2"+
"\2\2\u00cf\u00d0\3\2\2\2\u00d0\60\3\2\2\2\u00d1\u00cf\3\2\2\2\u00d2\u00d5"+
"\5;\36\2\u00d3\u00d5\7a\2\2\u00d4\u00d2\3\2\2\2\u00d4\u00d3\3\2\2\2\u00d5"+
"\u00d6\3\2\2\2\u00d6\u00d4\3\2\2\2\u00d6\u00d7\3\2\2\2\u00d7\u00dd\3\2"+
"\2\2\u00d8\u00dc\5;\36\2\u00d9\u00dc\59\35\2\u00da\u00dc\t\2\2\2\u00db"+
"\u00d8\3\2\2\2\u00db\u00d9\3\2\2\2\u00db\u00da\3\2\2\2\u00dc\u00df\3\2"+
"\2\2\u00dd\u00db\3\2\2\2\u00dd\u00de\3\2\2\2\u00de\62\3\2\2\2\u00df\u00dd"+
"\3\2\2\2\u00e0\u00e5\7)\2\2\u00e1\u00e4\5=\37\2\u00e2\u00e4\n\3\2\2\u00e3"+
"\u00e1\3\2\2\2\u00e3\u00e2\3\2\2\2\u00e4\u00e7\3\2\2\2\u00e5\u00e3\3\2"+
"\2\2\u00e5\u00e6\3\2\2\2\u00e6\u00e8\3\2\2\2\u00e7\u00e5\3\2\2\2\u00e8"+
"\u00e9\7)\2\2\u00e9\64\3\2\2\2\u00ea\u00ef\7$\2\2\u00eb\u00ee\5=\37\2"+
"\u00ec\u00ee\n\4\2\2\u00ed\u00eb\3\2\2\2\u00ed\u00ec\3\2\2\2\u00ee\u00f1"+
"\3\2\2\2\u00ef\u00ed\3\2\2\2\u00ef\u00f0\3\2\2\2\u00f0\u00f2\3\2\2\2\u00f1"+
"\u00ef\3\2\2\2\u00f2\u00f3\7$\2\2\u00f3\66\3\2\2\2\u00f4\u00f6\7/\2\2"+
"\u00f5\u00f4\3\2\2\2\u00f5\u00f6\3\2\2\2\u00f6\u00f8\3\2\2\2\u00f7\u00f9"+
"\4\62;\2\u00f8\u00f7\3\2\2\2\u00f9\u00fa\3\2\2\2\u00fa\u00f8\3\2\2\2\u00fa"+
"\u00fb\3\2\2\2\u00fb\u00fc\3\2\2\2\u00fc\u0100\7\60\2\2\u00fd\u00ff\4"+
"\62;\2\u00fe\u00fd\3\2\2\2\u00ff\u0102\3\2\2\2\u0100\u00fe\3\2\2\2\u0100"+
"\u0101\3\2\2\2\u0101\u0104\3\2\2\2\u0102\u0100\3\2\2\2\u0103\u0105\5E"+
"#\2\u0104\u0103\3\2\2\2\u0104\u0105\3\2\2\2\u0105\u0107\3\2\2\2\u0106"+
"\u0108\5G$\2\u0107\u0106\3\2\2\2\u0107\u0108\3\2\2\2\u0108\u012e\3\2\2"+
"\2\u0109\u010b\7/\2\2\u010a\u0109\3\2\2\2\u010a\u010b\3\2\2\2\u010b\u010c"+
"\3\2\2\2\u010c\u010e\7\60\2\2\u010d\u010f\4\62;\2\u010e\u010d\3\2\2\2"+
"\u010f\u0110\3\2\2\2\u0110\u010e\3\2\2\2\u0110\u0111\3\2\2\2\u0111\u0113"+
"\3\2\2\2\u0112\u0114\5E#\2\u0113\u0112\3\2\2\2\u0113\u0114\3\2\2\2\u0114"+
"\u0116\3\2\2\2\u0115\u0117\5G$\2\u0116\u0115\3\2\2\2\u0116\u0117\3\2\2"+
"\2\u0117\u012e\3\2\2\2\u0118\u011a\7/\2\2\u0119\u0118\3\2\2\2\u0119\u011a"+
"\3\2\2\2\u011a\u011c\3\2\2\2\u011b\u011d\4\62;\2\u011c\u011b\3\2\2\2\u011d"+
"\u011e\3\2\2\2\u011e\u011c\3\2\2\2\u011e\u011f\3\2\2\2\u011f\u0120\3\2"+
"\2\2\u0120\u0122\5E#\2\u0121\u0123\5G$\2\u0122\u0121\3\2\2\2\u0122\u0123"+
"\3\2\2\2\u0123\u012e\3\2\2\2\u0124\u0126\7/\2\2\u0125\u0124\3\2\2\2\u0125"+
"\u0126\3\2\2\2\u0126\u0128\3\2\2\2\u0127\u0129\4\62;\2\u0128\u0127\3\2"+
"\2\2\u0129\u012a\3\2\2\2\u012a\u0128\3\2\2\2\u012a\u012b\3\2\2\2\u012b"+
"\u012c\3\2\2\2\u012c\u012e\5G$\2\u012d\u00f5\3\2\2\2\u012d\u010a\3\2\2"+
"\2\u012d\u0119\3\2\2\2\u012d\u0125\3\2\2\2\u012e8\3\2\2\2\u012f\u0130"+
"\4\62;\2\u0130:\3\2\2\2\u0131\u0132\t\5\2\2\u0132<\3\2\2\2\u0133\u0134"+
"\7^\2\2\u0134\u0138\t\6\2\2\u0135\u0138\5A!\2\u0136\u0138\5? \2\u0137"+
"\u0133\3\2\2\2\u0137\u0135\3\2\2\2\u0137\u0136\3\2\2\2\u0138>\3\2\2\2"+
"\u0139\u013a\7^\2\2\u013a\u013b\4\62\65\2\u013b\u013c\4\629\2\u013c\u0143"+
"\4\629\2\u013d\u013e\7^\2\2\u013e\u013f\4\629\2\u013f\u0143\4\629\2\u0140"+
"\u0141\7^\2\2\u0141\u0143\4\629\2\u0142\u0139\3\2\2\2\u0142\u013d\3\2"+
"\2\2\u0142\u0140\3\2\2\2\u0143@\3\2\2\2\u0144\u0145\7^\2\2\u0145\u0146"+
"\7w\2\2\u0146\u0147\5C\"\2\u0147\u0148\5C\"\2\u0148\u0149\5C\"\2\u0149"+
"\u014a\5C\"\2\u014aB\3\2\2\2\u014b\u014c\t\7\2\2\u014cD\3\2\2\2\u014d"+
"\u014f\t\b\2\2\u014e\u0150\t\t\2\2\u014f\u014e\3\2\2\2\u014f\u0150\3\2"+
"\2\2\u0150\u0152\3\2\2\2\u0151\u0153\4\62;\2\u0152\u0151\3\2\2\2\u0153"+
"\u0154\3\2\2\2\u0154\u0152\3\2\2\2\u0154\u0155\3\2\2\2\u0155F\3\2\2\2"+
"\u0156\u0157\t\n\2\2\u0157H\3\2\2\2\u0158\u0159\t\13\2\2\u0159\u015a\3"+
"\2\2\2\u015a\u015b\b%\2\2\u015bJ\3\2\2\2\"\2\u00c0\u00c5\u00ca\u00cf\u00d4"+
"\u00d6\u00db\u00dd\u00e3\u00e5\u00ed\u00ef\u00f5\u00fa\u0100\u0104\u0107"+
"\u010a\u0110\u0113\u0116\u0119\u011e\u0122\u0125\u012a\u012d\u0137\u0142"+
"\u014f\u0154\3\b\2\2";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.recovery;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.routing.Murmur3HashFunction;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.math.MathUtils;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.shard.DocsStats;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.index.translog.TranslogConfig;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.test.BackgroundIndexer;
import org.elasticsearch.test.ESIntegTestCase;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*;
public class RecoveryWhileUnderLoadIT extends ESIntegTestCase {
private final ESLogger logger = Loggers.getLogger(RecoveryWhileUnderLoadIT.class);
public void testRecoverWhileUnderLoadAllocateReplicasTest() throws Exception {
logger.info("--> creating test index ...");
int numberOfShards = numberOfShards();
assertAcked(prepareCreate("test", 1, settingsBuilder().put(SETTING_NUMBER_OF_SHARDS, numberOfShards).put(SETTING_NUMBER_OF_REPLICAS, 1).put(TranslogConfig.INDEX_TRANSLOG_DURABILITY, Translog.Durabilty.ASYNC)));
final int totalNumDocs = scaledRandomIntBetween(200, 10000);
int waitFor = totalNumDocs / 10;
int extraDocs = waitFor;
try (BackgroundIndexer indexer = new BackgroundIndexer("test", "type", client(), extraDocs)) {
logger.info("--> waiting for {} docs to be indexed ...", waitFor);
waitForDocs(waitFor, indexer);
indexer.assertNoFailures();
logger.info("--> {} docs indexed", waitFor);
extraDocs = totalNumDocs / 10;
waitFor += extraDocs;
indexer.continueIndexing(extraDocs);
logger.info("--> flushing the index ....");
// now flush, just to make sure we have some data in the index, not just translog
client().admin().indices().prepareFlush().execute().actionGet();
logger.info("--> waiting for {} docs to be indexed ...", waitFor);
waitForDocs(waitFor, indexer);
indexer.assertNoFailures();
logger.info("--> {} docs indexed", waitFor);
extraDocs = totalNumDocs - waitFor;
indexer.continueIndexing(extraDocs);
logger.info("--> allow 2 nodes for index [test] ...");
// now start another node, while we index
allowNodes("test", 2);
logger.info("--> waiting for GREEN health status ...");
// make sure the cluster state is green, and all has been recovered
assertNoTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("5m").setWaitForGreenStatus());
logger.info("--> waiting for {} docs to be indexed ...", totalNumDocs);
waitForDocs(totalNumDocs, indexer);
indexer.assertNoFailures();
logger.info("--> {} docs indexed", totalNumDocs);
logger.info("--> marking and waiting for indexing threads to stop ...");
indexer.stop();
logger.info("--> indexing threads stopped");
logger.info("--> refreshing the index");
refreshAndAssert();
logger.info("--> verifying indexed content");
iterateAssertCount(numberOfShards, indexer.totalIndexedDocs(), 10);
}
}
public void testRecoverWhileUnderLoadAllocateReplicasRelocatePrimariesTest() throws Exception {
logger.info("--> creating test index ...");
int numberOfShards = numberOfShards();
assertAcked(prepareCreate("test", 1, settingsBuilder().put(SETTING_NUMBER_OF_SHARDS, numberOfShards).put(SETTING_NUMBER_OF_REPLICAS, 1).put(TranslogConfig.INDEX_TRANSLOG_DURABILITY, Translog.Durabilty.ASYNC)));
final int totalNumDocs = scaledRandomIntBetween(200, 10000);
int waitFor = totalNumDocs / 10;
int extraDocs = waitFor;
try (BackgroundIndexer indexer = new BackgroundIndexer("test", "type", client(), extraDocs)) {
logger.info("--> waiting for {} docs to be indexed ...", waitFor);
waitForDocs(waitFor, indexer);
indexer.assertNoFailures();
logger.info("--> {} docs indexed", waitFor);
extraDocs = totalNumDocs / 10;
waitFor += extraDocs;
indexer.continueIndexing(extraDocs);
logger.info("--> flushing the index ....");
// now flush, just to make sure we have some data in the index, not just translog
client().admin().indices().prepareFlush().execute().actionGet();
logger.info("--> waiting for {} docs to be indexed ...", waitFor);
waitForDocs(waitFor, indexer);
indexer.assertNoFailures();
logger.info("--> {} docs indexed", waitFor);
extraDocs = totalNumDocs - waitFor;
indexer.continueIndexing(extraDocs);
logger.info("--> allow 4 nodes for index [test] ...");
allowNodes("test", 4);
logger.info("--> waiting for GREEN health status ...");
assertNoTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("5m").setWaitForGreenStatus());
logger.info("--> waiting for {} docs to be indexed ...", totalNumDocs);
waitForDocs(totalNumDocs, indexer);
indexer.assertNoFailures();
logger.info("--> {} docs indexed", totalNumDocs);
logger.info("--> marking and waiting for indexing threads to stop ...");
indexer.stop();
logger.info("--> indexing threads stopped");
logger.info("--> refreshing the index");
refreshAndAssert();
logger.info("--> verifying indexed content");
iterateAssertCount(numberOfShards, indexer.totalIndexedDocs(), 10);
}
}
public void testRecoverWhileUnderLoadWithReducedAllowedNodes() throws Exception {
logger.info("--> creating test index ...");
int numberOfShards = numberOfShards();
assertAcked(prepareCreate("test", 2, settingsBuilder().put(SETTING_NUMBER_OF_SHARDS, numberOfShards).put(SETTING_NUMBER_OF_REPLICAS, 1).put(TranslogConfig.INDEX_TRANSLOG_DURABILITY, Translog.Durabilty.ASYNC)));
final int totalNumDocs = scaledRandomIntBetween(200, 10000);
int waitFor = totalNumDocs / 10;
int extraDocs = waitFor;
try (BackgroundIndexer indexer = new BackgroundIndexer("test", "type", client(), extraDocs)) {
logger.info("--> waiting for {} docs to be indexed ...", waitFor);
waitForDocs(waitFor, indexer);
indexer.assertNoFailures();
logger.info("--> {} docs indexed", waitFor);
extraDocs = totalNumDocs / 10;
waitFor += extraDocs;
indexer.continueIndexing(extraDocs);
logger.info("--> flushing the index ....");
// now flush, just to make sure we have some data in the index, not just translog
client().admin().indices().prepareFlush().execute().actionGet();
logger.info("--> waiting for {} docs to be indexed ...", waitFor);
waitForDocs(waitFor, indexer);
indexer.assertNoFailures();
logger.info("--> {} docs indexed", waitFor);
// now start more nodes, while we index
extraDocs = totalNumDocs - waitFor;
indexer.continueIndexing(extraDocs);
logger.info("--> allow 4 nodes for index [test] ...");
allowNodes("test", 4);
logger.info("--> waiting for GREEN health status ...");
assertNoTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("5m").setWaitForGreenStatus().setWaitForRelocatingShards(0));
logger.info("--> waiting for {} docs to be indexed ...", totalNumDocs);
waitForDocs(totalNumDocs, indexer);
indexer.assertNoFailures();
logger.info("--> {} docs indexed", totalNumDocs);
// now, shutdown nodes
logger.info("--> allow 3 nodes for index [test] ...");
allowNodes("test", 3);
logger.info("--> waiting for relocations ...");
assertNoTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("5m").setWaitForRelocatingShards(0));
logger.info("--> allow 2 nodes for index [test] ...");
allowNodes("test", 2);
logger.info("--> waiting for relocations ...");
assertNoTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("5m").setWaitForRelocatingShards(0));
logger.info("--> allow 1 nodes for index [test] ...");
allowNodes("test", 1);
logger.info("--> waiting for relocations ...");
assertNoTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("5m").setWaitForRelocatingShards(0));
logger.info("--> marking and waiting for indexing threads to stop ...");
indexer.stop();
logger.info("--> indexing threads stopped");
assertNoTimeout(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("5m").setWaitForRelocatingShards(0));
logger.info("--> refreshing the index");
refreshAndAssert();
logger.info("--> verifying indexed content");
iterateAssertCount(numberOfShards, indexer.totalIndexedDocs(), 10);
}
}
public void testRecoverWhileRelocating() throws Exception {
final int numShards = between(2, 10);
final int numReplicas = 0;
logger.info("--> creating test index ...");
int allowNodes = 2;
assertAcked(prepareCreate("test", 3, settingsBuilder().put(SETTING_NUMBER_OF_SHARDS, numShards).put(SETTING_NUMBER_OF_REPLICAS, numReplicas).put(TranslogConfig.INDEX_TRANSLOG_DURABILITY, Translog.Durabilty.ASYNC)));
final int numDocs = scaledRandomIntBetween(200, 9999);
try (BackgroundIndexer indexer = new BackgroundIndexer("test", "type", client(), numDocs)) {
for (int i = 0; i < numDocs; i += scaledRandomIntBetween(100, Math.min(1000, numDocs))) {
indexer.assertNoFailures();
logger.info("--> waiting for {} docs to be indexed ...", i);
waitForDocs(i, indexer);
logger.info("--> {} docs indexed", i);
allowNodes = 2 / allowNodes;
allowNodes("test", allowNodes);
logger.info("--> waiting for GREEN health status ...");
ensureGreen(TimeValue.timeValueMinutes(5));
}
logger.info("--> marking and waiting for indexing threads to stop ...");
indexer.stop();
logger.info("--> indexing threads stopped");
logger.info("--> bump up number of replicas to 1 and allow all nodes to hold the index");
allowNodes("test", 3);
assertAcked(client().admin().indices().prepareUpdateSettings("test").setSettings(settingsBuilder().put("number_of_replicas", 1)).get());
ensureGreen(TimeValue.timeValueMinutes(5));
logger.info("--> refreshing the index");
refreshAndAssert();
logger.info("--> verifying indexed content");
iterateAssertCount(numShards, indexer.totalIndexedDocs(), 10);
}
}
private void iterateAssertCount(final int numberOfShards, final long numberOfDocs, final int iterations) throws Exception {
SearchResponse[] iterationResults = new SearchResponse[iterations];
boolean error = false;
SearchResponse lastErroneousResponse = null;
for (int i = 0; i < iterations; i++) {
SearchResponse searchResponse = client().prepareSearch().setSize((int) numberOfDocs).setQuery(matchAllQuery()).addSort("id", SortOrder.ASC).get();
logSearchResponse(numberOfShards, numberOfDocs, i, searchResponse);
iterationResults[i] = searchResponse;
if (searchResponse.getHits().totalHits() != numberOfDocs) {
error = true;
lastErroneousResponse = searchResponse;
}
}
if (error) {
//Printing out shards and their doc count
IndicesStatsResponse indicesStatsResponse = client().admin().indices().prepareStats().get();
for (ShardStats shardStats : indicesStatsResponse.getShards()) {
DocsStats docsStats = shardStats.getStats().docs;
logger.info("shard [{}] - count {}, primary {}", shardStats.getShardRouting().id(), docsStats.getCount(), shardStats.getShardRouting().primary());
}
for (int doc = 1, hit = 0; hit < lastErroneousResponse.getHits().getHits().length; hit++, doc++) {
SearchHit searchHit = lastErroneousResponse.getHits().getAt(hit);
while (doc < Integer.parseInt(searchHit.id())) {
logger.info("missing doc [{}], indexed to shard [{}]", doc, MathUtils.mod(Murmur3HashFunction.hash(Integer.toString(doc)), numberOfShards));
doc++;
}
}
//if there was an error we try to wait and see if at some point it'll get fixed
logger.info("--> trying to wait");
assertTrue(awaitBusy(() -> {
boolean errorOccurred = false;
for (int i = 0; i < iterations; i++) {
SearchResponse searchResponse = client().prepareSearch().setSize(0).setQuery(matchAllQuery()).get();
if (searchResponse.getHits().totalHits() != numberOfDocs) {
errorOccurred = true;
}
}
return !errorOccurred;
},
5,
TimeUnit.MINUTES
)
);
}
//lets now make the test fail if it was supposed to fail
for (int i = 0; i < iterations; i++) {
assertHitCount(iterationResults[i], numberOfDocs);
}
}
private void logSearchResponse(int numberOfShards, long numberOfDocs, int iteration, SearchResponse searchResponse) {
logger.info("iteration [{}] - successful shards: {} (expected {})", iteration, searchResponse.getSuccessfulShards(), numberOfShards);
logger.info("iteration [{}] - failed shards: {} (expected 0)", iteration, searchResponse.getFailedShards());
if (searchResponse.getShardFailures() != null && searchResponse.getShardFailures().length > 0) {
logger.info("iteration [{}] - shard failures: {}", iteration, Arrays.toString(searchResponse.getShardFailures()));
}
logger.info("iteration [{}] - returned documents: {} (expected {})", iteration, searchResponse.getHits().totalHits(), numberOfDocs);
}
private void refreshAndAssert() throws Exception {
assertBusy(new Runnable() {
@Override
public void run() {
RefreshResponse actionGet = client().admin().indices().prepareRefresh().get();
assertAllSuccessful(actionGet);
}
}, 5, TimeUnit.MINUTES);
}
}
| |
package jml.classification;
import static jml.matlab.Matlab.diag;
import static jml.matlab.Matlab.display;
import static jml.matlab.Matlab.exp;
import static jml.matlab.Matlab.fprintf;
import static jml.matlab.Matlab.full;
import static jml.matlab.Matlab.minus;
import static jml.matlab.Matlab.mtimes;
import static jml.matlab.Matlab.ne;
import static jml.matlab.Matlab.ones;
import static jml.matlab.Matlab.plus;
import static jml.matlab.Matlab.rdivide;
import static jml.matlab.Matlab.sign;
import static jml.matlab.Matlab.sumAll;
import static jml.matlab.Matlab.times;
import static jml.matlab.Matlab.zeros;
import static jml.utils.Time.tic;
import static jml.utils.Time.toc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Random;
import jml.options.Options;
import org.apache.commons.math.linear.BlockRealMatrix;
import org.apache.commons.math.linear.RealMatrix;
/***
* A Java implementation for AdaBoost.
*
* @author Mingjie Qian
* @version 1.0, Oct. 20th, 2013
*/
public class AdaBoost extends Classifier {
/**
*
*/
private static final long serialVersionUID = 1100546985050582205L;
/**
* @param args
*/
public static void main(String[] args) {
double[][] data = { {3.5, 4.4, 1.3},
{5.3, 2.2, 0.5},
{0.2, 0.3, 4.1},
{5.3, 2.2, -1.5},
{-1.2, 0.4, 3.2} };
int[] labels = {1, 1, -1, -1, -1};
RealMatrix X = new BlockRealMatrix(data);
X = X.transpose();
Options options = new Options();
options.epsilon = 1e-5;
Classifier logReg = new LogisticRegressionMCLBFGS(options);
logReg.feedData(X);
logReg.feedLabels(labels);
logReg.train();
RealMatrix Xt = X;
double accuracy = Classifier.getAccuracy(labels, logReg.predict(Xt));
fprintf("Accuracy for logistic regression: %.2f%%\n", 100 * accuracy);
int T = 10;
Classifier[] weakClassifiers = new Classifier[T];
for (int t = 0; t < 10; t++) {
options = new Options();
options.epsilon = 1e-5;
weakClassifiers[t] = new LogisticRegressionMCLBFGS(options);
}
Classifier adaBoost = new AdaBoost(weakClassifiers);
adaBoost.feedData(X);
adaBoost.feedLabels(labels);
tic();
adaBoost.train();
System.out.format("Elapsed time: %.2f seconds.%n", toc());
Xt = X.copy();
display(adaBoost.predictLabelScoreMatrix(Xt));
display(full(adaBoost.predictLabelMatrix(Xt)));
display(adaBoost.predict(Xt));
accuracy = Classifier.getAccuracy(labels, adaBoost.predict(Xt));
fprintf("Accuracy for AdaBoost with logistic regression: %.2f%%\n", 100 * accuracy);
// Save the model
String modelFilePath = "AdaBoostModel";
adaBoost.saveModel(modelFilePath);
// Load the model
Classifier adaBoost2 = new AdaBoost();
adaBoost2.loadModel(modelFilePath);
display(adaBoost2.predictLabelScoreMatrix(Xt));
display(full(adaBoost2.predictLabelMatrix(Xt)));
display(adaBoost2.predict(Xt));
accuracy = Classifier.getAccuracy(labels, adaBoost2.predict(Xt));
fprintf("Accuracy: %.2f%%\n", 100 * accuracy);
}
/**
* Number of iterations, or the number of weak classifiers.
*/
int T;
/**
* The sequence of weak classifiers during training.
*/
Classifier[] weakClassifiers;
/**
* Weights on the outputs of the trained weak classifiers.
*/
double[] alphas;
/**
* Constructor.
* @param weakClassifiers a sequence of weak classifiers to be
* trained during the boosting procedure
*/
public AdaBoost(Classifier[] weakClassifiers) {
T = weakClassifiers.length;
this.weakClassifiers = weakClassifiers;
alphas = new double[T];
}
/**
* Default constructor.
*/
public AdaBoost() {
}
@Override
public void loadModel(String filePath) {
System.out.println("Loading model...");
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
weakClassifiers = (Classifier[])ois.readObject();
T = weakClassifiers.length;
alphas = (double[])ois.readObject();
IDLabelMap = (int[])ois.readObject();
nClass = IDLabelMap.length;
ois.close();
System.out.println("Model loaded.");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
@Override
public void saveModel(String filePath) {
File parentFile = new File(filePath).getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
oos.writeObject(weakClassifiers);
oos.writeObject(alphas);
oos.writeObject(IDLabelMap);
oos.close();
System.out.println("Model saved.");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void train() {
int d = this.nFeature;
int m = this.nExample;
RealMatrix Dt = times(1.0/m, ones(m, 1));
RealMatrix Xt = zeros(d, m);
// RealMatrix Yt = zeros(m, 1); // Vector composed of 1 or -1
// RealMatrix I = eye(2);
// RealMatrix alphas = zeros(1, T);
RealMatrix errs = zeros(1, T);
RealMatrix ets = zeros(1, T);
RealMatrix Coef = diag(diag(new double[]{1, -1}));
Random generator = new Random();
RealMatrix Y_true_labels = mtimes(Y, Coef);
RealMatrix Yt_LabelMatrix = zeros(m, this.nClass);
for (int t = 1; t <= T; t++) {
// Sample Xt from X w.r.t Dt
if (t == 1) {
Xt = X.copy();
Yt_LabelMatrix = Y.copy();
// Yt = Y_true_labels;
} else {
if (sumAll(Dt) == 0) {
Xt = X.copy();
Yt_LabelMatrix = Y.copy();
} else {
for (int i = 1; i <= m; i++) {
double r_i = generator.nextDouble();
// Select Xt_i
double s = 0;
int j = 1;
while (j < m) {
if (s <= r_i && r_i < s + Dt.getEntry(j - 1, 0))
break;
else {
s = s + Dt.getEntry(j - 1, 0);
j++;
}
}
Xt.setColumnMatrix(i - 1, X.getColumnMatrix(j - 1));
Yt_LabelMatrix.setRowMatrix(i - 1, Y.getRowMatrix(j - 1));
// Yt.setEntry(i - 1, 0, Y_true_labels.getEntry(j - 1, 0));
}
}
}
// Train h_t
weakClassifiers[t - 1].feedData(Xt);
weakClassifiers[t - 1].feedLabels(Yt_LabelMatrix);
weakClassifiers[t - 1].train();
RealMatrix Y_pred_labels = mtimes(
weakClassifiers[t - 1].predictLabelMatrix(X), Coef);
RealMatrix I_err = ne(Y_true_labels, Y_pred_labels);
double et = 0;
for (int i = 0; i < m; i++) {
if (I_err.getEntry(i, 0) == 1)
et += Dt.getEntry(i, 0);
}
// et = sumAll(logicalIndexing(Dt, I_err));
ets.setEntry(0, t - 1, et);
errs.setEntry(0, t - 1, sumAll(I_err)/m);
double alpha_t = 0.5 * Math.log((1 - et) / et);
// alphas.setEntry(0, t - 1, alpha_t);
alphas[t - 1] = alpha_t;
Dt = times(Dt, exp(times(-alpha_t, times(Y_true_labels, Y_pred_labels))));
double zt = sumAll(Dt);
if (zt > 0)
Dt = rdivide(Dt, zt);
}
}
@Override
public RealMatrix predictLabelMatrix(RealMatrix Xt) {
int m = Xt.getColumnDimension();
RealMatrix Y_score = zeros(m, 1);
RealMatrix Coef = diag(diag(new double[]{1, -1}));
for (int t = 1; t <= T; t++) {
Y_score = plus(Y_score, times(alphas[t - 1],
mtimes(weakClassifiers[t - 1].predictLabelMatrix(Xt), Coef)));
}
RealMatrix H_final_pred = sign(Y_score);
RealMatrix Temp = minus(0.5, times(0.5, H_final_pred));
int[] labelIndices = new int[m];
for (int i = 0; i < m; i++) {
labelIndices[i] = (int)Temp.getEntry(i, 0);
}
return labelIndexArray2LabelMatrix(labelIndices, nClass);
}
@Override
public RealMatrix predictLabelScoreMatrix(RealMatrix Xt) {
int m = Xt.getColumnDimension();
RealMatrix lableScoreMatrix = zeros(m, 2);
RealMatrix Y_score = zeros(m, 1);
RealMatrix Coef = diag(diag(new double[]{1, -1}));
for (int t = 1; t <= T; t++) {
Y_score = plus(Y_score, times(alphas[t - 1],
mtimes(weakClassifiers[t - 1].predictLabelMatrix(Xt), Coef)));
}
lableScoreMatrix.setColumnMatrix(0, Y_score);
lableScoreMatrix.setColumnMatrix(1, times(-1, Y_score));
return lableScoreMatrix;
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* BrowserLanguageTargeting.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202105;
/**
* Represents browser languages that are being targeted or excluded
* by the
* {@link LineItem}.
*/
public class BrowserLanguageTargeting implements java.io.Serializable {
/* Indicates whether browsers languages should be targeted or
* excluded. This
* attribute is optional and defaults to {@code true}. */
private java.lang.Boolean isTargeted;
/* Browser languages that are being targeted or excluded by the
* {@link LineItem}. */
private com.google.api.ads.admanager.axis.v202105.Technology[] browserLanguages;
public BrowserLanguageTargeting() {
}
public BrowserLanguageTargeting(
java.lang.Boolean isTargeted,
com.google.api.ads.admanager.axis.v202105.Technology[] browserLanguages) {
this.isTargeted = isTargeted;
this.browserLanguages = browserLanguages;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("browserLanguages", getBrowserLanguages())
.add("isTargeted", getIsTargeted())
.toString();
}
/**
* Gets the isTargeted value for this BrowserLanguageTargeting.
*
* @return isTargeted * Indicates whether browsers languages should be targeted or
* excluded. This
* attribute is optional and defaults to {@code true}.
*/
public java.lang.Boolean getIsTargeted() {
return isTargeted;
}
/**
* Sets the isTargeted value for this BrowserLanguageTargeting.
*
* @param isTargeted * Indicates whether browsers languages should be targeted or
* excluded. This
* attribute is optional and defaults to {@code true}.
*/
public void setIsTargeted(java.lang.Boolean isTargeted) {
this.isTargeted = isTargeted;
}
/**
* Gets the browserLanguages value for this BrowserLanguageTargeting.
*
* @return browserLanguages * Browser languages that are being targeted or excluded by the
* {@link LineItem}.
*/
public com.google.api.ads.admanager.axis.v202105.Technology[] getBrowserLanguages() {
return browserLanguages;
}
/**
* Sets the browserLanguages value for this BrowserLanguageTargeting.
*
* @param browserLanguages * Browser languages that are being targeted or excluded by the
* {@link LineItem}.
*/
public void setBrowserLanguages(com.google.api.ads.admanager.axis.v202105.Technology[] browserLanguages) {
this.browserLanguages = browserLanguages;
}
public com.google.api.ads.admanager.axis.v202105.Technology getBrowserLanguages(int i) {
return this.browserLanguages[i];
}
public void setBrowserLanguages(int i, com.google.api.ads.admanager.axis.v202105.Technology _value) {
this.browserLanguages[i] = _value;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof BrowserLanguageTargeting)) return false;
BrowserLanguageTargeting other = (BrowserLanguageTargeting) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.isTargeted==null && other.getIsTargeted()==null) ||
(this.isTargeted!=null &&
this.isTargeted.equals(other.getIsTargeted()))) &&
((this.browserLanguages==null && other.getBrowserLanguages()==null) ||
(this.browserLanguages!=null &&
java.util.Arrays.equals(this.browserLanguages, other.getBrowserLanguages())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getIsTargeted() != null) {
_hashCode += getIsTargeted().hashCode();
}
if (getBrowserLanguages() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getBrowserLanguages());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getBrowserLanguages(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(BrowserLanguageTargeting.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "BrowserLanguageTargeting"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("isTargeted");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "isTargeted"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("browserLanguages");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "browserLanguages"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202105", "Technology"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package ca.mcgill.cs.sel.ram.impl;
import ca.mcgill.cs.sel.ram.Attribute;
import ca.mcgill.cs.sel.ram.Classifier;
import ca.mcgill.cs.sel.ram.RamPackage;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.EObjectResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Class</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link ca.mcgill.cs.sel.ram.impl.ClassImpl#getAttributes <em>Attributes</em>}</li>
* <li>{@link ca.mcgill.cs.sel.ram.impl.ClassImpl#isPartial <em>Partial</em>}</li>
* <li>{@link ca.mcgill.cs.sel.ram.impl.ClassImpl#isAbstract <em>Abstract</em>}</li>
* <li>{@link ca.mcgill.cs.sel.ram.impl.ClassImpl#getSuperTypes <em>Super Types</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ClassImpl extends ClassifierImpl implements ca.mcgill.cs.sel.ram.Class {
/**
* The cached value of the '{@link #getAttributes() <em>Attributes</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAttributes()
* @generated
* @ordered
*/
protected EList<Attribute> attributes;
/**
* The default value of the '{@link #isPartial() <em>Partial</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isPartial()
* @generated
* @ordered
*/
protected static final boolean PARTIAL_EDEFAULT = false;
/**
* The cached value of the '{@link #isPartial() <em>Partial</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isPartial()
* @generated
* @ordered
*/
protected boolean partial = PARTIAL_EDEFAULT;
/**
* The default value of the '{@link #isAbstract() <em>Abstract</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isAbstract()
* @generated
* @ordered
*/
protected static final boolean ABSTRACT_EDEFAULT = false;
/**
* The cached value of the '{@link #isAbstract() <em>Abstract</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isAbstract()
* @generated
* @ordered
*/
protected boolean abstract_ = ABSTRACT_EDEFAULT;
/**
* The cached value of the '{@link #getSuperTypes() <em>Super Types</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSuperTypes()
* @generated
* @ordered
*/
protected EList<Classifier> superTypes;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ClassImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return RamPackage.Literals.CLASS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Attribute> getAttributes() {
if (attributes == null) {
attributes = new EObjectContainmentEList<Attribute>(Attribute.class, this, RamPackage.CLASS__ATTRIBUTES);
}
return attributes;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isPartial() {
return partial;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPartial(boolean newPartial) {
boolean oldPartial = partial;
partial = newPartial;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, RamPackage.CLASS__PARTIAL, oldPartial, partial));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isAbstract() {
return abstract_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAbstract(boolean newAbstract) {
boolean oldAbstract = abstract_;
abstract_ = newAbstract;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, RamPackage.CLASS__ABSTRACT, oldAbstract, abstract_));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Classifier> getSuperTypes() {
if (superTypes == null) {
superTypes = new EObjectResolvingEList<Classifier>(Classifier.class, this, RamPackage.CLASS__SUPER_TYPES);
}
return superTypes;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case RamPackage.CLASS__ATTRIBUTES:
return ((InternalEList<?>)getAttributes()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case RamPackage.CLASS__ATTRIBUTES:
return getAttributes();
case RamPackage.CLASS__PARTIAL:
return isPartial();
case RamPackage.CLASS__ABSTRACT:
return isAbstract();
case RamPackage.CLASS__SUPER_TYPES:
return getSuperTypes();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case RamPackage.CLASS__ATTRIBUTES:
getAttributes().clear();
getAttributes().addAll((Collection<? extends Attribute>)newValue);
return;
case RamPackage.CLASS__PARTIAL:
setPartial((Boolean)newValue);
return;
case RamPackage.CLASS__ABSTRACT:
setAbstract((Boolean)newValue);
return;
case RamPackage.CLASS__SUPER_TYPES:
getSuperTypes().clear();
getSuperTypes().addAll((Collection<? extends Classifier>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case RamPackage.CLASS__ATTRIBUTES:
getAttributes().clear();
return;
case RamPackage.CLASS__PARTIAL:
setPartial(PARTIAL_EDEFAULT);
return;
case RamPackage.CLASS__ABSTRACT:
setAbstract(ABSTRACT_EDEFAULT);
return;
case RamPackage.CLASS__SUPER_TYPES:
getSuperTypes().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case RamPackage.CLASS__ATTRIBUTES:
return attributes != null && !attributes.isEmpty();
case RamPackage.CLASS__PARTIAL:
return partial != PARTIAL_EDEFAULT;
case RamPackage.CLASS__ABSTRACT:
return abstract_ != ABSTRACT_EDEFAULT;
case RamPackage.CLASS__SUPER_TYPES:
return superTypes != null && !superTypes.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (partial: ");
result.append(partial);
result.append(", abstract: ");
result.append(abstract_);
result.append(')');
return result.toString();
}
} //ClassImpl
| |
/*
* Copyright 2015-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.codec.impl;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.Ip4Address;
import org.onlab.packet.Ip6Address;
import org.onlab.packet.MacAddress;
import org.onlab.packet.MplsLabel;
import org.onlab.packet.VlanId;
import org.onosproject.codec.CodecContext;
import org.onosproject.codec.JsonCodec;
import org.onosproject.net.ChannelSpacing;
import org.onosproject.net.GridType;
import org.onosproject.net.Lambda;
import org.onosproject.net.OduSignalId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.flow.instructions.Instruction;
import org.onosproject.net.flow.instructions.Instructions;
import org.onosproject.net.flow.instructions.L0ModificationInstruction;
import org.onosproject.net.flow.instructions.L1ModificationInstruction;
import org.onosproject.net.flow.instructions.L2ModificationInstruction;
import org.onosproject.net.flow.instructions.L3ModificationInstruction;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.onosproject.codec.impl.InstructionJsonMatcher.matchesInstruction;
/**
* Unit tests for Instruction codec.
*/
public class InstructionCodecTest {
CodecContext context;
JsonCodec<Instruction> instructionCodec;
/**
* Sets up for each test. Creates a context and fetches the instruction
* codec.
*/
@Before
public void setUp() {
context = new MockCodecContext();
instructionCodec = context.codec(Instruction.class);
assertThat(instructionCodec, notNullValue());
}
/**
* Tests the encoding of push mpls header instructions.
*/
@Test
public void pushHeaderInstructionsTest() {
final L2ModificationInstruction.ModMplsHeaderInstruction instruction =
(L2ModificationInstruction.ModMplsHeaderInstruction) Instructions.pushMpls();
final ObjectNode instructionJson = instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of output instructions.
*/
@Test
public void outputInstructionTest() {
final Instructions.OutputInstruction instruction =
Instructions.createOutput(PortNumber.portNumber(22));
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod OCh signal instructions.
*/
@Test
public void modOchSignalInstructionTest() {
L0ModificationInstruction.ModOchSignalInstruction instruction =
(L0ModificationInstruction.ModOchSignalInstruction)
Instructions.modL0Lambda(Lambda.ochSignal(GridType.DWDM, ChannelSpacing.CHL_100GHZ, 4, 8));
ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod ODU signal ID instructions.
*/
@Test
public void modOduSignalIdInstructionTest() {
OduSignalId oduSignalId = OduSignalId.oduSignalId(1, 8, new byte[] {8, 0, 0, 0, 0, 0, 0, 0, 0, 0});
L1ModificationInstruction.ModOduSignalIdInstruction instruction =
(L1ModificationInstruction.ModOduSignalIdInstruction)
Instructions.modL1OduSignalId(oduSignalId);
ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod ether instructions.
*/
@Test
public void modEtherInstructionTest() {
final L2ModificationInstruction.ModEtherInstruction instruction =
(L2ModificationInstruction.ModEtherInstruction)
Instructions.modL2Src(MacAddress.valueOf("11:22:33:44:55:66"));
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod vlan id instructions.
*/
@Test
public void modVlanIdInstructionTest() {
final L2ModificationInstruction.ModVlanIdInstruction instruction =
(L2ModificationInstruction.ModVlanIdInstruction)
Instructions.modVlanId(VlanId.vlanId((short) 12));
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod vlan pcp instructions.
*/
@Test
public void modVlanPcpInstructionTest() {
final L2ModificationInstruction.ModVlanPcpInstruction instruction =
(L2ModificationInstruction.ModVlanPcpInstruction)
Instructions.modVlanPcp((byte) 9);
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod IPv4 src instructions.
*/
@Test
public void modIPSrcInstructionTest() {
final Ip4Address ip = Ip4Address.valueOf("1.2.3.4");
final L3ModificationInstruction.ModIPInstruction instruction =
(L3ModificationInstruction.ModIPInstruction)
Instructions.modL3Src(ip);
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod IPv4 dst instructions.
*/
@Test
public void modIPDstInstructionTest() {
final Ip4Address ip = Ip4Address.valueOf("1.2.3.4");
final L3ModificationInstruction.ModIPInstruction instruction =
(L3ModificationInstruction.ModIPInstruction)
Instructions.modL3Dst(ip);
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod IPv6 src instructions.
*/
@Test
public void modIPv6SrcInstructionTest() {
final Ip6Address ip = Ip6Address.valueOf("1111::2222");
final L3ModificationInstruction.ModIPInstruction instruction =
(L3ModificationInstruction.ModIPInstruction)
Instructions.modL3IPv6Src(ip);
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod IPv6 dst instructions.
*/
@Test
public void modIPv6DstInstructionTest() {
final Ip6Address ip = Ip6Address.valueOf("1111::2222");
final L3ModificationInstruction.ModIPInstruction instruction =
(L3ModificationInstruction.ModIPInstruction)
Instructions.modL3IPv6Dst(ip);
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod IPv6 flow label instructions.
*/
@Test
public void modIPv6FlowLabelInstructionTest() {
final int flowLabel = 0xfffff;
final L3ModificationInstruction.ModIPv6FlowLabelInstruction instruction =
(L3ModificationInstruction.ModIPv6FlowLabelInstruction)
Instructions.modL3IPv6FlowLabel(flowLabel);
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
/**
* Tests the encoding of mod MPLS label instructions.
*/
@Test
public void modMplsLabelInstructionTest() {
final L2ModificationInstruction.ModMplsLabelInstruction instruction =
(L2ModificationInstruction.ModMplsLabelInstruction)
Instructions.modMplsLabel(MplsLabel.mplsLabel(99));
final ObjectNode instructionJson =
instructionCodec.encode(instruction, context);
assertThat(instructionJson, matchesInstruction(instruction));
}
}
| |
package io.searchbox.client.config.discovery;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.gson.Gson;
import io.searchbox.action.Action;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.client.config.ClientConfig;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.*;
public class NodeCheckerTest {
ClientConfig clientConfig;
JestClient jestClient;
@Before
public void setUp() throws Exception {
clientConfig = new ClientConfig.Builder("http://localhost:9200")
.discoveryEnabled(true)
.discoveryFrequency(1l, TimeUnit.SECONDS)
.build();
jestClient = mock(JestClient.class);
}
@Test
public void testWithResolvedWithoutHostnameAddressWithCustomScheme() throws Exception {
NodeChecker nodeChecker = new NodeChecker(jestClient, new ClientConfig.Builder("http://localhost:9200")
.discoveryEnabled(true)
.discoveryFrequency(1l, TimeUnit.SECONDS)
.defaultSchemeForDiscoveredNodes("https")
.build());
JestResult result = new JestResult(new Gson());
result.setJsonMap(ImmutableMap.<String, Object>of(
"ok", "true",
"nodes", ImmutableMap.of(
"node_name", ImmutableMap.of(
"http_address", "inet[/192.168.2.7:9200]"
)
)
));
result.setSucceeded(true);
when(jestClient.execute(isA(Action.class))).thenReturn(result);
nodeChecker.runOneIteration();
verify(jestClient).execute(isA(Action.class));
ArgumentCaptor<LinkedHashSet> argument = ArgumentCaptor.forClass(LinkedHashSet.class);
verify(jestClient).setServers(argument.capture());
verifyNoMoreInteractions(jestClient);
Set servers = argument.getValue();
assertEquals(1, servers.size());
assertEquals("https://192.168.2.7:9200", servers.iterator().next());
}
@Test
public void testWithResolvedWithoutHostnameAddress() throws Exception {
NodeChecker nodeChecker = new NodeChecker(jestClient, clientConfig);
JestResult result = new JestResult(new Gson());
result.setJsonMap(ImmutableMap.<String, Object>of(
"ok", "true",
"nodes", ImmutableMap.of(
"node_name", ImmutableMap.of(
"http_address", "inet[/192.168.2.7:9200]"
)
)
));
result.setSucceeded(true);
when(jestClient.execute(isA(Action.class))).thenReturn(result);
nodeChecker.runOneIteration();
verify(jestClient).execute(isA(Action.class));
ArgumentCaptor<LinkedHashSet> argument = ArgumentCaptor.forClass(LinkedHashSet.class);
verify(jestClient).setServers(argument.capture());
verifyNoMoreInteractions(jestClient);
Set servers = argument.getValue();
assertEquals(1, servers.size());
assertEquals("http://192.168.2.7:9200", servers.iterator().next());
}
@Test
public void testWithResolvedWithHostnameAddress() throws Exception {
NodeChecker nodeChecker = new NodeChecker(jestClient, clientConfig);
JestResult result = new JestResult(new Gson());
result.setJsonMap(ImmutableMap.<String, Object>of(
"ok", "true",
"nodes", ImmutableMap.of(
"node_name", ImmutableMap.of(
"http_address", "inet[searchly.com/192.168.2.7:9200]"
)
)
));
result.setSucceeded(true);
when(jestClient.execute(isA(Action.class))).thenReturn(result);
nodeChecker.runOneIteration();
verify(jestClient).execute(isA(Action.class));
ArgumentCaptor<LinkedHashSet> argument = ArgumentCaptor.forClass(LinkedHashSet.class);
verify(jestClient).setServers(argument.capture());
verifyNoMoreInteractions(jestClient);
Set servers = argument.getValue();
assertEquals(1, servers.size());
assertEquals("http://192.168.2.7:9200", servers.iterator().next());
}
@Test
public void testWithUnresolvedAddress() throws Exception {
NodeChecker nodeChecker = new NodeChecker(jestClient, clientConfig);
JestResult result = new JestResult(new Gson());
result.setJsonMap(ImmutableMap.<String, Object>of(
"ok", "true",
"nodes", ImmutableMap.of(
"node_name", ImmutableMap.of(
"http_address", "inet[192.168.2.7:9200]"
)
)
));
result.setSucceeded(true);
when(jestClient.execute(isA(Action.class))).thenReturn(result);
nodeChecker.runOneIteration();
verify(jestClient).execute(isA(Action.class));
ArgumentCaptor<LinkedHashSet> argument = ArgumentCaptor.forClass(LinkedHashSet.class);
verify(jestClient).setServers(argument.capture());
verifyNoMoreInteractions(jestClient);
Set servers = argument.getValue();
assertEquals(1, servers.size());
assertEquals("http://192.168.2.7:9200", servers.iterator().next());
}
@Test
public void testWithInvalidUnresolvedAddress() throws Exception {
NodeChecker nodeChecker = new NodeChecker(jestClient, clientConfig);
JestResult result = new JestResult(new Gson());
result.setJsonMap(ImmutableMap.<String, Object>of(
"ok", "true",
"nodes", ImmutableMap.of(
"node_name", ImmutableMap.of(
"http_address", "inet[192.168.2.7:]"
)
)
));
result.setSucceeded(true);
when(jestClient.execute(isA(Action.class))).thenReturn(result);
nodeChecker.runOneIteration();
verify(jestClient).execute(isA(Action.class));
ArgumentCaptor<LinkedHashSet> argument = ArgumentCaptor.forClass(LinkedHashSet.class);
verify(jestClient).setServers(argument.capture());
verifyNoMoreInteractions(jestClient);
Set servers = argument.getValue();
assertEquals(0, servers.size());
}
@Test
public void testWithInvalidResolvedAddress() throws Exception {
NodeChecker nodeChecker = new NodeChecker(jestClient, clientConfig);
JestResult result = new JestResult(new Gson());
result.setJsonMap(ImmutableMap.<String, Object>of(
"ok", "true",
"nodes", ImmutableMap.of(
"node_name", ImmutableMap.of(
"http_address", "inet[gg/192.168.2.7:]"
)
)
));
result.setSucceeded(true);
when(jestClient.execute(isA(Action.class))).thenReturn(result);
nodeChecker.runOneIteration();
verify(jestClient).execute(isA(Action.class));
ArgumentCaptor<LinkedHashSet> argument = ArgumentCaptor.forClass(LinkedHashSet.class);
verify(jestClient).setServers(argument.capture());
verifyNoMoreInteractions(jestClient);
Set servers = argument.getValue();
assertEquals(0, servers.size());
}
@Test
public void testNodesInfoExceptionUsesBootstrapServerList() throws Exception {
NodeChecker nodeChecker = new NodeChecker(jestClient, clientConfig);
when(jestClient.execute(isA(Action.class))).thenThrow(Exception.class);
nodeChecker.runOneIteration();
verify(jestClient).execute(isA(Action.class));
ArgumentCaptor<LinkedHashSet> argument = ArgumentCaptor.forClass(LinkedHashSet.class);
verify(jestClient).setServers(argument.capture());
verifyNoMoreInteractions(jestClient);
Set servers = argument.getValue();
assertEquals(1, servers.size());
assertEquals("http://localhost:9200", servers.iterator().next());
}
@Test
public void testNodesInfoFailureUsesBootstrapServerList() throws Exception {
NodeChecker nodeChecker = new NodeChecker(jestClient, clientConfig);
JestResult result = new JestResult(new Gson());
result.setSucceeded(false);
when(jestClient.execute(isA(Action.class))).thenReturn(result);
nodeChecker.runOneIteration();
verify(jestClient).execute(isA(Action.class));
ArgumentCaptor<LinkedHashSet> argument = ArgumentCaptor.forClass(LinkedHashSet.class);
verify(jestClient).setServers(argument.capture());
verifyNoMoreInteractions(jestClient);
Set servers = argument.getValue();
assertEquals(1, servers.size());
assertEquals("http://localhost:9200", servers.iterator().next());
}
}
| |
/*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.jvm.java.intellij;
import com.facebook.buck.graph.MutableDirectedGraph;
import com.facebook.buck.io.MorePaths;
import com.facebook.buck.jvm.core.JavaPackageFinder;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.immutables.value.Value;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Groups {@link IjFolder}s into sets which are of the same type and belong to the same package
* structure.
*/
public class IjSourceRootSimplifier {
private JavaPackageFinder javaPackageFinder;
public IjSourceRootSimplifier(JavaPackageFinder javaPackageFinder) {
this.javaPackageFinder = javaPackageFinder;
}
/**
* Merges {@link IjFolder}s of the same type and package prefix.
*
* @param limit if a path has this many segments it will not be simplified further.
* @param folders set of {@link IjFolder}s to simplify.
* @return simplified set of {@link IjFolder}s.
*/
public ImmutableSet<IjFolder> simplify(
SimplificationLimit limit,
ImmutableSet<IjFolder> folders) {
ImmutableSet.Builder<IjFolder> mergedFoldersBuilder = ImmutableSet.builder();
ImmutableSet.Builder<IjFolder> foldersToMergeBuilder = ImmutableSet.builder();
for (IjFolder folder : folders) {
if (folder.isCoalescent()) {
foldersToMergeBuilder.add(folder);
} else {
mergedFoldersBuilder.add(folder);
}
}
ImmutableSet<IjFolder> foldersToMerge = foldersToMergeBuilder.build();
PackagePathCache packagePathCache = new PackagePathCache(foldersToMerge, javaPackageFinder);
BottomUpPathMerger walker =
new BottomUpPathMerger(foldersToMerge, limit.getValue(), packagePathCache);
return mergedFoldersBuilder
.addAll(walker.getMergedFolders())
.build();
}
@Value.Immutable
@BuckStyleImmutable
abstract static class AbstractSimplificationLimit {
@Value.Parameter
public abstract int getValue();
}
private static class BottomUpPathMerger {
// Graph where edges represent the parent path -> child path relationship. We need this
// to efficiently look up children.
private MutableDirectedGraph<Path> tree;
// Keeps track of paths which actually have a folder attached to them. It's a bit simpler to
// use a map like this, especially that the folders then move up the tree as we merge them.
private Map<Path, IjFolder> mergePathsMap;
// Efficient package prefix lookup.
private PackagePathCache packagePathCache;
public BottomUpPathMerger(
Iterable<IjFolder> foldersToWalk,
int limit,
PackagePathCache packagePathCache) {
this.tree = new MutableDirectedGraph<>();
this.packagePathCache = packagePathCache;
this.mergePathsMap = new HashMap<>();
for (IjFolder folder : foldersToWalk) {
mergePathsMap.put(folder.getPath(), folder);
Path path = folder.getPath();
while (path.getNameCount() > limit) {
Path parent = path.getParent();
if (parent == null) {
break;
}
boolean isParentAndGrandParentAlreadyInTree = tree.containsNode(parent);
tree.addEdge(parent, path);
if (isParentAndGrandParentAlreadyInTree) {
break;
}
path = parent;
}
}
}
public ImmutableSet<IjFolder> getMergedFolders() {
for (Path topLevel : tree.getNodesWithNoIncomingEdges()) {
walk(topLevel);
}
return ImmutableSet.copyOf(mergePathsMap.values());
}
/**
* Walks the trie of paths attempting to merge all of the children of the current path into
* itself. As soon as this fails we know we can't merge the parent path with the current path
* either.
*
* @param currentPath current path
* @return Optional.of(a successfully merged folder) or absent if merging did not succeed.
*/
private Optional<IjFolder> walk(Path currentPath) {
ImmutableList<Optional<IjFolder>> children =
FluentIterable.from(tree.getOutgoingNodesFor(currentPath))
.transform(
new Function<Path, Optional<IjFolder>>() {
@Override
public Optional<IjFolder> apply(Path input) {
return walk(input);
}
})
.toList();
boolean anyAbsent = FluentIterable.from(children)
.anyMatch(Predicates.equalTo(Optional.<IjFolder>absent()));
if (anyAbsent) {
// Signal that no further merging should be done.
return Optional.absent();
}
ImmutableSet<IjFolder> presentChildren = FluentIterable.from(children)
.transform(
new Function<Optional<IjFolder>, IjFolder>() {
@Override
public IjFolder apply(Optional<IjFolder> input) {
return input.get();
}
})
.toSet();
IjFolder currentFolder = mergePathsMap.get(currentPath);
if (presentChildren.isEmpty()) {
return Optional.of(Preconditions.checkNotNull(currentFolder));
}
final IjFolder myFolder;
if (currentFolder != null) {
myFolder = currentFolder;
} else {
IjFolder aChild = findBestChildToAggregateTo(presentChildren);
myFolder = aChild.createCopyWith(currentPath);
}
boolean allChildrenCanBeMerged = FluentIterable.from(presentChildren)
.allMatch(
new Predicate<IjFolder>() {
@Override
public boolean apply(IjFolder input) {
return canMerge(myFolder, input, packagePathCache);
}
});
if (!allChildrenCanBeMerged) {
return Optional.absent();
}
IjFolder mergedFolder = myFolder;
for (IjFolder presentChild : presentChildren) {
mergePathsMap.remove(presentChild.getPath());
mergedFolder = presentChild.merge(mergedFolder);
}
mergePathsMap.put(mergedFolder.getPath(), mergedFolder);
return Optional.of(mergedFolder);
}
}
/**
* Find a child which can be used as the aggregation point for the other folders.
* The order of preference is;
* - AndroidResource - because there should be only one
* - SourceFolder - because most things should merge into it
* - First Child - because no other folders significantly affect aggregation.
*/
private static IjFolder findBestChildToAggregateTo(ImmutableSet<IjFolder> children) {
Iterator<IjFolder> childIterator = children.iterator();
IjFolder bestCandidate = childIterator.next();
while (childIterator.hasNext()) {
IjFolder candidate = childIterator.next();
if (candidate instanceof AndroidResourceFolder) {
return candidate;
}
if (candidate instanceof SourceFolder) {
bestCandidate = candidate;
}
}
return bestCandidate;
}
private static boolean canMerge(
IjFolder parent,
IjFolder child,
PackagePathCache packagePathCache) {
Preconditions.checkArgument(child.getPath().startsWith(parent.getPath()));
if (!parent.getClass().equals(child.getClass())) {
return false;
}
if (!child.isCoalescent()) {
return false;
}
if (!child.canMergeWith(parent)) {
return false;
}
if (parent.getWantsPackagePrefix() != child.getWantsPackagePrefix()) {
return false;
}
if (parent.getWantsPackagePrefix()) {
Optional<Path> parentPackage = packagePathCache.lookup(parent);
if (!parentPackage.isPresent()) {
return false;
}
Path childPackage = packagePathCache.lookup(child).get();
int pathDifference = child.getPath().getNameCount() - parent.getPath().getNameCount();
Preconditions.checkState(pathDifference == 1);
if (childPackage.getNameCount() == 0) {
return false;
}
if (!MorePaths.getParentOrEmpty(childPackage).equals(parentPackage.get())) {
return false;
}
}
return true;
}
/**
* Hierarchical path cache. If the path a/b/c/d has package c/d it assumes that
* a/b/c has the package c/.
*/
private static class PackagePathCache {
ParsingJavaPackageFinder.PackagePathCache delegate;
public PackagePathCache(
ImmutableSet<IjFolder> startingFolders,
JavaPackageFinder javaPackageFinder) {
delegate = new ParsingJavaPackageFinder.PackagePathCache();
for (IjFolder startingFolder : startingFolders) {
if (!startingFolder.getWantsPackagePrefix()) {
continue;
}
Path path = FluentIterable.from(startingFolder.getInputs())
.first()
.or(lookupPath(startingFolder));
delegate.insert(path, javaPackageFinder.findJavaPackageFolder(path));
}
}
private Path lookupPath(IjFolder folder) {
return folder.getPath().resolve("notfound");
}
public Optional<Path> lookup(IjFolder folder) {
return delegate.lookup(lookupPath(folder));
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.core.runtime.system;
import java.io.File;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.fixtures.LogonFixture;
import org.apache.isis.core.commons.config.IsisConfiguration;
import org.apache.isis.core.commons.debug.DebugBuilder;
import org.apache.isis.core.commons.debug.DebuggableWithTitle;
import org.apache.isis.core.metamodel.adapter.oid.OidMarshaller;
import org.apache.isis.core.metamodel.facetapi.MetaModelRefiner;
import org.apache.isis.core.metamodel.services.ServicesInjectorSpi;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.core.metamodel.spec.SpecificationLoaderSpi;
import org.apache.isis.core.metamodel.specloader.ServiceInitializer;
import org.apache.isis.core.runtime.about.AboutIsis;
import org.apache.isis.core.runtime.authentication.AuthenticationManager;
import org.apache.isis.core.runtime.authentication.exploration.ExplorationSession;
import org.apache.isis.core.runtime.authorization.AuthorizationManager;
import org.apache.isis.core.runtime.installerregistry.InstallerLookup;
import org.apache.isis.core.runtime.system.context.IsisContext;
import org.apache.isis.core.runtime.system.internal.InitialisationSession;
import org.apache.isis.core.runtime.system.internal.IsisLocaleInitializer;
import org.apache.isis.core.runtime.system.internal.IsisTimeZoneInitializer;
import org.apache.isis.core.runtime.system.persistence.PersistenceSession;
import org.apache.isis.core.runtime.system.persistence.PersistenceSessionFactory;
import org.apache.isis.core.runtime.system.session.IsisSession;
import org.apache.isis.core.runtime.system.session.IsisSessionFactory;
import org.apache.isis.core.runtime.system.transaction.IsisTransactionManager;
import org.apache.isis.core.runtime.system.transaction.IsisTransactionManagerException;
/**
* An implementation of {@link IsisSystem} that has a hook for installing
* fixtures but does not install them itself.
*/
public abstract class IsisSystemFixturesHookAbstract implements IsisSystem {
public static final Logger LOG = LoggerFactory.getLogger(IsisSystemFixturesHookAbstract.class);
private final IsisLocaleInitializer localeInitializer;
private final IsisTimeZoneInitializer timeZoneInitializer;
private final DeploymentType deploymentType;
private boolean initialized = false;
private IsisSessionFactory sessionFactory;
private ServiceInitializer serviceInitializer;
// ///////////////////////////////////////////
// Constructors
// ///////////////////////////////////////////
public IsisSystemFixturesHookAbstract(final DeploymentType deploymentType) {
this(deploymentType, new IsisLocaleInitializer(), new IsisTimeZoneInitializer());
}
public IsisSystemFixturesHookAbstract(final DeploymentType deploymentType, final IsisLocaleInitializer localeInitializer, final IsisTimeZoneInitializer timeZoneInitializer) {
this.deploymentType = deploymentType;
this.localeInitializer = localeInitializer;
this.timeZoneInitializer = timeZoneInitializer;
}
// ///////////////////////////////////////////
// DeploymentType
// ///////////////////////////////////////////
@Override
public DeploymentType getDeploymentType() {
return deploymentType;
}
// ///////////////////////////////////////////
// init, shutdown
// ///////////////////////////////////////////
@Override
public void init() {
if (initialized) {
throw new IllegalStateException("Already initialized");
} else {
initialized = true;
}
LOG.info("initialising Isis System");
LOG.info("working directory: " + new File(".").getAbsolutePath());
LOG.info("resource stream source: " + getConfiguration().getResourceStreamSource());
localeInitializer.initLocale(getConfiguration());
timeZoneInitializer.initTimeZone(getConfiguration());
try {
sessionFactory = doCreateSessionFactory(deploymentType);
// temporarily make a configuration available
// REVIEW: would rather inject this, or perhaps even the
// ConfigurationBuilder
IsisContext.setConfiguration(getConfiguration());
initContext(sessionFactory);
sessionFactory.init();
serviceInitializer = initializeServices();
installFixturesIfRequired();
translateServicesAndEnumConstants();
} catch (final IsisSystemException ex) {
LOG.error("failed to initialise", ex);
throw new RuntimeException(ex);
}
}
private void initContext(final IsisSessionFactory sessionFactory) {
getDeploymentType().initContext(sessionFactory);
}
/**
* @see #shutdownServices(ServiceInitializer)
*/
private ServiceInitializer initializeServices() {
final List<Object> services = sessionFactory.getServices();
// validate
final ServiceInitializer serviceInitializer = new ServiceInitializer();
serviceInitializer.validate(getConfiguration(), services);
// call @PostConstruct (in a session)
IsisContext.openSession(new InitialisationSession());
try {
getTransactionManager().startTransaction();
try {
serviceInitializer.postConstruct();
return serviceInitializer;
} catch(RuntimeException ex) {
getTransactionManager().getTransaction().setAbortCause(new IsisTransactionManagerException(ex));
return serviceInitializer;
} finally {
// will commit or abort
getTransactionManager().endTransaction();
}
} finally {
IsisContext.closeSession();
}
}
/**
* The act of invoking titleOf(...) will cause translations to be requested.
*/
private void translateServicesAndEnumConstants() {
IsisContext.openSession(new InitialisationSession());
try {
final List<Object> services = sessionFactory.getServices();
final DomainObjectContainer container = lookupService(DomainObjectContainer.class);
for (Object service : services) {
final String unused = container.titleOf(service);
}
for (final ObjectSpecification objSpec : allSpecifications()) {
final Class<?> correspondingClass = objSpec.getCorrespondingClass();
if(correspondingClass.isEnum()) {
final Object[] enumConstants = correspondingClass.getEnumConstants();
for (Object enumConstant : enumConstants) {
final String unused = container.titleOf(enumConstant);
}
}
}
} finally {
IsisContext.closeSession();
}
}
private <T> T lookupService(final Class<T> serviceClass) {
return getServicesInjector().lookupService(serviceClass);
}
private ServicesInjectorSpi getServicesInjector() {
return getPersistenceSession().getServicesInjector();
}
private PersistenceSession getPersistenceSession() {
return IsisContext.getPersistenceSession();
}
Collection<ObjectSpecification> allSpecifications() {
return IsisContext.getSpecificationLoader().allSpecifications();
}
@Override
public void shutdown() {
LOG.info("shutting down system");
shutdownServices(this.serviceInitializer);
IsisContext.closeAllSessions();
}
/**
* @see #initializeServices()
*/
private void shutdownServices(final ServiceInitializer serviceInitializer) {
// call @PostDestroy (in a session)
IsisContext.openSession(new InitialisationSession());
try {
getTransactionManager().startTransaction();
try {
serviceInitializer.preDestroy();
} catch(RuntimeException ex) {
getTransactionManager().getTransaction().setAbortCause(new IsisTransactionManagerException(ex));
} finally {
// will commit or abort
getTransactionManager().endTransaction();
}
} finally {
IsisContext.closeSession();
}
}
// ///////////////////////////////////////////
// Hook:
// ///////////////////////////////////////////
/**
* Hook method; the returned implementation is expected to use the same
* general approach as the subclass itself.
*
* <p>
* So, for example, <tt>IsisSystemUsingInstallers</tt> uses the
* {@link InstallerLookup} mechanism to find its components. The
* corresponding <tt>ExecutionContextFactoryUsingInstallers</tt> object
* returned by this method should use {@link InstallerLookup} likewise.
*/
protected abstract IsisSessionFactory doCreateSessionFactory(final DeploymentType deploymentType) throws IsisSystemException;
// ///////////////////////////////////////////
// Configuration
// ///////////////////////////////////////////
/**
* Populated after {@link #init()}.
*/
@Override
public IsisSessionFactory getSessionFactory() {
return sessionFactory;
}
// ///////////////////////////////////////////
// Configuration
// ///////////////////////////////////////////
@Override
public abstract IsisConfiguration getConfiguration();
// ///////////////////////////////////////////
// OidMarshaller
// ///////////////////////////////////////////
/**
* Just returns a {@link OidMarshaller}; subclasses may override if
* required.
*/
protected OidMarshaller obtainOidMarshaller() {
return new OidMarshaller();
}
// ///////////////////////////////////////////
// Reflector
// ///////////////////////////////////////////
protected abstract SpecificationLoaderSpi obtainSpecificationLoaderSpi(DeploymentType deploymentType, Collection<MetaModelRefiner> metaModelRefiners) throws IsisSystemException;
// ///////////////////////////////////////////
// PersistenceSessionFactory
// ///////////////////////////////////////////
protected abstract PersistenceSessionFactory obtainPersistenceSessionFactory(DeploymentType deploymentType) throws IsisSystemException;
// ///////////////////////////////////////////
// Fixtures (hooks)
// ///////////////////////////////////////////
/**
* Optional hook for appending debug information pertaining to fixtures
* installer if required.
*/
protected void appendFixturesInstallerDebug(final DebugBuilder debug) {
}
/**
* The {@link LogonFixture}, if any, obtained by running fixtures.
*
* <p>
* Intended to be used when for {@link DeploymentType#SERVER_EXPLORATION
* exploration} (instead of an {@link ExplorationSession}) or
* {@link DeploymentType#SERVER_PROTOTYPE prototype} deployments (saves logging
* in). Should be <i>ignored</i> in other {@link DeploymentType}s.
*
* <p>
* This implementation always returns <tt>null</tt>.
*/
@Override
public LogonFixture getLogonFixture() {
return null;
}
/**
* Optional hook for installing fixtures.
*
* <p>
* This implementation does nothing.
*/
protected void installFixturesIfRequired() throws IsisSystemException {
}
// ///////////////////////////////////////////
// Authentication & Authorization Manager
// ///////////////////////////////////////////
protected abstract AuthenticationManager obtainAuthenticationManager(DeploymentType deploymentType) throws IsisSystemException;
protected abstract AuthorizationManager obtainAuthorizationManager(final DeploymentType deploymentType);
// ///////////////////////////////////////////
// Services
// ///////////////////////////////////////////
protected abstract List<Object> obtainServices();
// ///////////////////////////////////////////
// debugging
// ///////////////////////////////////////////
private void debug(final DebugBuilder debug, final Object object) {
if (object instanceof DebuggableWithTitle) {
final DebuggableWithTitle d = (DebuggableWithTitle) object;
debug.appendTitle(d.debugTitle());
d.debugData(debug);
} else {
debug.appendln(object.toString());
debug.appendln("... no further debug information");
}
}
@Override
public DebuggableWithTitle debugSection(final String selectionName) {
// DebugInfo deb;
if (selectionName.equals("Configuration")) {
return getConfiguration();
} /*
* else if (selectionName.equals("Overview")) { debugOverview(debug);
* } else if (selectionName.equals("Authenticator")) { deb =
* IsisContext.getAuthenticationManager(); } else if
* (selectionName.equals("Reflector")) { deb =
* IsisContext.getSpecificationLoader(); } else if
* (selectionName.equals("Contexts")) { deb =
* debugListContexts(debug); } else { deb =
* debugDisplayContext(selectionName, debug); }
*/
return null;
}
private void debugDisplayContext(final String selector, final DebugBuilder debug) {
final IsisSession d = IsisContext.getSession(selector);
if (d != null) {
d.debugAll(debug);
} else {
debug.appendln("No context: " + selector);
}
}
private void debugListContexts(final DebugBuilder debug) {
final String[] contextIds = IsisContext.getInstance().allSessionIds();
for (final String contextId : contextIds) {
debug.appendln(contextId);
debug.appendln("-----");
final IsisSession d = IsisContext.getSession(contextId);
d.debug(debug);
debug.appendln();
}
}
@Override
public String[] debugSectionNames() {
final String[] general = new String[] { "Overview", "Authenticator", "Configuration", "Reflector", "Requests", "Contexts" };
final String[] contextIds = IsisContext.getInstance().allSessionIds();
final String[] combined = new String[general.length + contextIds.length];
System.arraycopy(general, 0, combined, 0, general.length);
System.arraycopy(contextIds, 0, combined, general.length, contextIds.length);
return combined;
}
private void debugOverview(final DebugBuilder debug) {
try {
debug.appendln(AboutIsis.getFrameworkName());
debug.appendln(AboutIsis.getFrameworkVersion());
if (AboutIsis.getApplicationName() != null) {
debug.appendln("application: " + AboutIsis.getApplicationName());
}
if (AboutIsis.getApplicationVersion() != null) {
debug.appendln("version" + AboutIsis.getApplicationVersion());
}
final String user = System.getProperty("user.name");
final String system = System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") " + System.getProperty("os.version");
final String java = System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version");
debug.appendln("user: " + user);
debug.appendln("os: " + system);
debug.appendln("java: " + java);
debug.appendln("working directory: " + new File(".").getAbsolutePath());
debug.appendTitle("System Installer");
appendFixturesInstallerDebug(debug);
debug.appendTitle("System Components");
debug.appendln("Authentication manager", IsisContext.getAuthenticationManager().getClass().getName());
debug.appendln("Configuration", getConfiguration().getClass().getName());
final DebuggableWithTitle[] inf = IsisContext.debugSystem();
for (final DebuggableWithTitle element : inf) {
if (element != null) {
element.debugData(debug);
}
}
} catch (final RuntimeException e) {
debug.appendException(e);
}
}
IsisTransactionManager getTransactionManager() {
return IsisContext.getTransactionManager();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.platform.dotnet;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.portable.PortableException;
import org.apache.ignite.portable.PortableMarshalAware;
import org.apache.ignite.portable.PortableRawReader;
import org.apache.ignite.portable.PortableRawWriter;
import org.apache.ignite.portable.PortableReader;
import org.apache.ignite.portable.PortableWriter;
import java.util.ArrayList;
import java.util.Collection;
/**
* Mirror of .Net class PortableConfiguration.cs
*/
public class PlatformDotNetPortableConfiguration implements PortableMarshalAware {
/** Type cfgs. */
private Collection<PlatformDotNetPortableTypeConfiguration> typesCfg;
/** Types. */
private Collection<String> types;
/** Default name mapper. */
private String dfltNameMapper;
/** Default id mapper. */
private String dfltIdMapper;
/** Default serializer. */
private String dfltSerializer;
/** Default metadata enabled. */
private boolean dfltMetadataEnabled = true;
/** Whether to cache deserialized value in IGridPortableObject */
private boolean dfltKeepDeserialized = true;
/**
* Default constructor.
*/
public PlatformDotNetPortableConfiguration() {
// No-op.
}
/**
* Copy constructor.
* @param cfg configuration to copy.
*/
public PlatformDotNetPortableConfiguration(PlatformDotNetPortableConfiguration cfg) {
if (cfg.getTypesConfiguration() != null) {
typesCfg = new ArrayList<>();
for (PlatformDotNetPortableTypeConfiguration typeCfg : cfg.getTypesConfiguration())
typesCfg.add(new PlatformDotNetPortableTypeConfiguration(typeCfg));
}
if (cfg.getTypes() != null)
types = new ArrayList<>(cfg.getTypes());
dfltNameMapper = cfg.getDefaultNameMapper();
dfltIdMapper = cfg.getDefaultIdMapper();
dfltSerializer = cfg.getDefaultSerializer();
dfltMetadataEnabled = cfg.isDefaultMetadataEnabled();
dfltKeepDeserialized = cfg.isDefaultKeepDeserialized();
}
/**
* @return Type cfgs.
*/
public Collection<PlatformDotNetPortableTypeConfiguration> getTypesConfiguration() {
return typesCfg;
}
/**
* @param typesCfg New type cfgs.
*/
public void setTypesConfiguration(Collection<PlatformDotNetPortableTypeConfiguration> typesCfg) {
this.typesCfg = typesCfg;
}
/**
* @return Types.
*/
public Collection<String> getTypes() {
return types;
}
/**
* @param types New types.
*/
public void setTypes(Collection<String> types) {
this.types = types;
}
/**
* @return Default name mapper.
*/
public String getDefaultNameMapper() {
return dfltNameMapper;
}
/**
* @param dfltNameMapper New default name mapper.
*/
public void setDefaultNameMapper(String dfltNameMapper) {
this.dfltNameMapper = dfltNameMapper;
}
/**
* @return Default id mapper.
*/
public String getDefaultIdMapper() {
return dfltIdMapper;
}
/**
* @param dfltIdMapper New default id mapper.
*/
public void setDefaultIdMapper(String dfltIdMapper) {
this.dfltIdMapper = dfltIdMapper;
}
/**
* @return Default serializer.
*/
public String getDefaultSerializer() {
return dfltSerializer;
}
/**
* @param dfltSerializer New default serializer.
*/
public void setDefaultSerializer(String dfltSerializer) {
this.dfltSerializer = dfltSerializer;
}
/**
* Gets default metadata enabled flag. See {@link #setDefaultMetadataEnabled(boolean)} for more information.
*
* @return Default metadata enabled flag.
*/
public boolean isDefaultMetadataEnabled() {
return dfltMetadataEnabled;
}
/**
* Sets default metadata enabled flag. When set to {@code true} all portable types will save it's metadata to
* cluster.
* <p />
* Can be overridden for particular type using
* {@link PlatformDotNetPortableTypeConfiguration#setMetadataEnabled(Boolean)}.
*
* @param dfltMetadataEnabled Default metadata enabled flag.
*/
public void setDefaultMetadataEnabled(boolean dfltMetadataEnabled) {
this.dfltMetadataEnabled = dfltMetadataEnabled;
}
/**
* Gets default keep deserialized flag. See {@link #setDefaultKeepDeserialized(boolean)} for more information.
*
* @return Flag indicates whether to cache deserialized value in IGridPortableObject.
*/
public boolean isDefaultKeepDeserialized() {
return dfltKeepDeserialized;
}
/**
* Sets default keep deserialized flag.
* <p />
* Can be overridden for particular type using
* {@link PlatformDotNetPortableTypeConfiguration#setKeepDeserialized(Boolean)}.
*
* @param keepDeserialized Keep deserialized flag.
*/
public void setDefaultKeepDeserialized(boolean keepDeserialized) {
this.dfltKeepDeserialized = keepDeserialized;
}
/** {@inheritDoc} */
@Override public void writePortable(PortableWriter writer) throws PortableException {
PortableRawWriter rawWriter = writer.rawWriter();
rawWriter.writeCollection(typesCfg);
rawWriter.writeCollection(types);
rawWriter.writeString(dfltNameMapper);
rawWriter.writeString(dfltIdMapper);
rawWriter.writeString(dfltSerializer);
rawWriter.writeBoolean(dfltMetadataEnabled);
rawWriter.writeBoolean(dfltKeepDeserialized);
}
/** {@inheritDoc} */
@Override public void readPortable(PortableReader reader) throws PortableException {
PortableRawReader rawReader = reader.rawReader();
typesCfg = rawReader.readCollection();
types = rawReader.readCollection();
dfltNameMapper = rawReader.readString();
dfltIdMapper = rawReader.readString();
dfltSerializer = rawReader.readString();
dfltMetadataEnabled = rawReader.readBoolean();
dfltKeepDeserialized = rawReader.readBoolean();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(PlatformDotNetPortableConfiguration.class, this);
}
}
| |
// Copyright 2011-2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.security.zynamics.reil.translators;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.security.zynamics.reil.ReilBlock;
import com.google.security.zynamics.reil.ReilEdge;
import com.google.security.zynamics.reil.ReilFunction;
import com.google.security.zynamics.reil.ReilGraph;
import com.google.security.zynamics.reil.ReilHelpers;
import com.google.security.zynamics.reil.ReilInstruction;
import com.google.security.zynamics.reil.ReilProgram;
import com.google.security.zynamics.reil.translators.arm.TranslatorARM;
import com.google.security.zynamics.reil.translators.mips.TranslatorMIPS;
import com.google.security.zynamics.reil.translators.ppc.TranslatorPPC;
import com.google.security.zynamics.reil.translators.reil.TranslatorREIL;
import com.google.security.zynamics.reil.translators.x86.TranslatorX86;
import com.google.security.zynamics.zylib.disassembly.IAddress;
import com.google.security.zynamics.zylib.disassembly.IBlockContainer;
import com.google.security.zynamics.zylib.disassembly.ICodeContainer;
import com.google.security.zynamics.zylib.disassembly.ICodeEdge;
import com.google.security.zynamics.zylib.disassembly.IInstruction;
import com.google.security.zynamics.zylib.general.Pair;
import com.google.security.zynamics.zylib.gui.zygraph.edges.EdgeType;
import com.google.security.zynamics.zylib.types.common.CollectionHelpers;
import com.google.security.zynamics.zylib.types.common.ICollectionFilter;
import com.google.security.zynamics.zylib.types.common.ICollectionMapper;
/**
* Translates disassembled programs to REIL code.
*/
public class ReilTranslator<InstructionType extends IInstruction> {
private final Map<String, ITranslator<InstructionType>> m_translators =
new HashMap<String, ITranslator<InstructionType>>();
public ReilTranslator() {
m_translators.put("X86-32", new TranslatorX86<InstructionType>());
m_translators.put("ARM-32", new TranslatorARM<InstructionType>());
m_translators.put("POWERPC-32", new TranslatorPPC<InstructionType>());
m_translators.put("REIL", new TranslatorREIL<InstructionType>());
m_translators.put("MIPS-32", new TranslatorMIPS<InstructionType>());
}
/**
* Returns the addresses of all basic blocks of a function. Note that the addresses are already
* converted to REIL addresses.
*
* @param function The input function.
*
* @return A list of all basic block addresses of the function.
*/
private static Collection<IAddress> getBlockAddresses(final IBlockContainer<?> function) {
return CollectionHelpers.map(function.getBasicBlocks(),
new ICollectionMapper<ICodeContainer<?>, IAddress>() {
private boolean isDelayedBranch(final ReilInstruction instruction) {
return instruction.getMnemonic().equals(ReilHelpers.OPCODE_JCC)
&& ReilHelpers.isDelayedBranch(instruction);
}
@Override
public IAddress map(final ICodeContainer<?> block) {
final IInstruction lastInstruction = Iterables.getFirst(block.getInstructions(), null); // getLastInstruction(block);
final ReilTranslator<IInstruction> translator = new ReilTranslator<IInstruction>();
try {
final ReilGraph reilGraph =
translator.translate(new StandardEnvironment(), lastInstruction);
final ReilBlock lastNode = reilGraph.getNodes().get(reilGraph.getNodes().size() - 1);
final ReilInstruction lastReilInstruction =
Iterables.getLast(lastNode.getInstructions());
if (isDelayedBranch(lastReilInstruction)) // If branch-delay
{
return ReilHelpers.toReilAddress(Iterables.get(block.getInstructions(), 1)
.getAddress());
} else {
return ReilHelpers.toReilAddress(block.getAddress());
}
} catch (final InternalTranslationException e) {
return ReilHelpers.toReilAddress(block.getAddress());
}
}
});
}
/**
* Returns the first instruction from a code container.
*
* @param container The code container.
*
* @return The first instruction from the code container.
*/
private static IInstruction getFirstInstruction(final ICodeContainer<?> container) {
return Iterables.getFirst(container.getInstructions(), null);
}
/**
* Returns the first instruction from a list of REIL instructions.
*
* @param list The list of REIL instructions.
*
* @return The first instruction from the list.
*/
private static ReilInstruction getFirstInstruction(final List<ReilInstruction> list) {
return list.get(0);
}
/**
* Returns the last instruction from a code container.
*
* @param container The code container.
*
* @return The last instruction from the code container.
*/
private static IInstruction getLastInstruction(final ICodeContainer<?> container) {
return Iterables.getLast(container.getInstructions());
}
/**
* Returns the last instruction from a list of REIL instructions.
*
* @param list The list of REIL instructions.
*
* @return The last instruction from the list.
*/
private static ReilInstruction getLastInstruction(final List<ReilInstruction> list) {
return list.get(list.size() - 1);
}
/**
* Returns the REIL block from a list of REIL blocks that starts with a given instruction.
*
* @param instruction The REIL instruction to search for.
* @param blocks The blocks to search through.
*
* @return The block that starts with the given REIL instruction.
*/
private static ReilBlock getNode(final ReilInstruction instruction, final List<ReilBlock> blocks) {
for (final ReilBlock block : blocks) {
for (final ReilInstruction reilInstruction : block) {
if (instruction == reilInstruction) {
return block;
}
}
// if (getFirstInstruction(block) == instruction)
// {
// return block;
// }
}
throw new IllegalStateException(String.format(
"Error: Unknown block (Instruction '%s' not found)", instruction));
}
/**
* This function is responsible for modifying the generated graph at all likely delayed branches.
*
* @param nodes
* @param edges
* @param delayedTrueBranches
*/
private static void handleDelayedTrueBranches(final List<ReilBlock> nodes,
final List<ReilEdge> edges, final List<List<ReilInstruction>> delayedTrueBranches) {
for (final List<ReilInstruction> lastReil : delayedTrueBranches) {
// In this post-processing step we consider all the delayed branches where the delayed
// instruction is only executed if the branch is taken.
//
// We solve the problem by removing the branch-delayed instruction from the original
// block. Then we take the removed instructions to form a new block. The true branch
// of the original block is connected with the new block. The false branch of the
// original block remains unchanged.
final ReilInstruction lastReilInstruction = lastReil.get(lastReil.size() - 1);
for (final ReilBlock node : nodes) {
final Iterable<ReilInstruction> nodeInstructions = node.getInstructions();
if (Iterables.getLast(nodeInstructions) == lastReilInstruction) {
// The situation we are having here is that have located the
// node that contains the delayed instruction. In fact this node
// contains only the code of the delayed instruction. It has one
// incoming edge and two outgoing edges.
//
// We now have to rewrite the edges to make sure the jump has
// the two outgoing edges.
final ReilEdge incomingEdge = node.getIncomingEdges().get(0);
final ReilBlock parentNode = incomingEdge.getSource();
edges.remove(incomingEdge);
boolean first = true;
for (final ReilEdge outgoingEdge : node.getOutgoingEdges()) {
if (first) {
first = false;
final ReilEdge newEdge =
new ReilEdge(parentNode, node, EdgeType.JUMP_CONDITIONAL_TRUE);
ReilBlock.link(parentNode, node, newEdge);
edges.add(newEdge);
final ReilEdge newEdge2 =
new ReilEdge(parentNode, outgoingEdge.getTarget(),
EdgeType.JUMP_CONDITIONAL_FALSE);
ReilBlock.link(parentNode, outgoingEdge.getTarget(), newEdge2);
edges.add(newEdge2);
} else {
final ReilEdge newEdge2 =
new ReilEdge(node, outgoingEdge.getTarget(), outgoingEdge.getType());
ReilBlock.link(node, outgoingEdge.getTarget(), newEdge2);
edges.add(newEdge2);
}
edges.remove(outgoingEdge);
ReilBlock.unlink(outgoingEdge.getSource(), outgoingEdge.getTarget(), outgoingEdge);
}
}
}
}
}
/**
* Tests whether there is any node in a list of nodes that were generated from the same
* instruction as a given node and have an outgoing edge to a given instruction.
*
* Basically, what this function checks is whether there is an edge from an original native
* instruction to a given REIL instruction.
*
* @param nodes The list of nodes to check.
* @param node The node that provides the core address of all nodes that are checked.
* @param instruction The instruction to that is the edge target.
*
* @return True, if any node exists with an edge to the given instruction.
*/
private static boolean hasEdge(final List<ReilBlock> nodes, final ReilBlock node,
final ReilInstruction instruction) {
for (final ReilBlock block : nodes) {
if (shareOriginalInstruction(node, block) && hasEdge(block, instruction)) {
return true;
}
}
return false;
}
/**
* Determines whether a REIL node has an outgoing edge to a given REIL instruction.
*
* @param node The node whose outgoing edges are checked.
* @param instruction The instruction to search for.
*
* @return True, if the node has an outgoing edge to the instructions. False, otherwise.
*/
private static boolean hasEdge(final ReilBlock node, final ReilInstruction instruction) {
return CollectionHelpers.any(node.getOutgoingEdges(), new ICollectionFilter<ReilEdge>() {
@Override
public boolean qualifies(final ReilEdge outgoingEdge) {
return getFirstInstruction(outgoingEdge.getTarget()) == instruction;
}
});
}
/**
* Inserts a single missing edge that could not be deduced automatically from the REIL
* instructions and their operands.
*
* @param nodes List of translated REIL nodes.
* @param edges List of translated REIL edges. This list is extended by the function.
* @param nativeEdge The native to check for and add if necessary.
* @param sourceReilInstruction Source REIL instruction of the edge.
* @param targetReilInstruction Target REIL instruction of the edge.
*/
private static void insertNativeEdge(final List<ReilBlock> nodes, final List<ReilEdge> edges,
final ICodeEdge<?> nativeEdge, final ReilInstruction sourceReilInstruction,
final ReilInstruction targetReilInstruction) {
// This part here is very hackish. We want to find out whether there is already an edge that
// connects the original source and target nodes passed to the function.
// This is trickier than expected because it is not guaranteed that the final REIL instruction
// that is generated for the original source contains the jump. For this reason we need to check
// all the REIL blocks generated from the original input block (and at this point it is not
// clear that this behaviour is what we want).
// Furthermore it is not guaranteed that the final instruction of a translated jump instruction
// is the JCC instruction. In some cases the translated instruction series end with other REIL
// instructions (mostly nop). In these cases, there will only be one outgoing edge and the type
// of this outgoing edge must explicitly set to Unconditional. At this point it is not clear if
// this is the desired behaviour.
//
// When changing this code please check back with
//
// - notepad.exe, NPCommand, the jumps at the beginning of the entry basic block
// - coredll.dll, mbstowcs_std__3Unothrow_t_1_B, the outgoing edges of the nop-nodes
for (final ReilBlock node : nodes) {
if ((sourceReilInstruction == getLastInstruction(node))
&& !hasEdge(nodes, node, targetReilInstruction)) {
final EdgeType edgeType =
ReilHelpers.isJump(sourceReilInstruction) ? nativeEdge.getType()
: EdgeType.JUMP_UNCONDITIONAL;
final ReilBlock targetNode = getNode(targetReilInstruction, nodes);
final ReilEdge newEdge = new ReilEdge(node, targetNode, edgeType);
ReilBlock.link(node, targetNode, newEdge);
edges.add(newEdge);
}
}
}
/**
* Inserts missing edges that could not be deduced automatically from the REIL instructions and
* their operands.
*
* @param nativeEdges List of native edges of the input graph.
* @param nodes List of translated REIL nodes.
* @param edges List of translated REIL edges. This list is extended by the function.
* @param firstMap Maps between native instructions and their first REIL instructions.
* @param lastMap Maps between native instructions and their last REIL instructions.
*/
private static void insertNativeEdges(final List<? extends ICodeEdge<?>> nativeEdges,
final List<ReilBlock> nodes, final List<ReilEdge> edges,
final Map<IInstruction, ReilInstruction> firstMap,
final Map<IInstruction, ReilInstruction> lastMap) {
for (final ICodeEdge<?> nativeEdge : nativeEdges) {
final Object source = nativeEdge.getSource();
final Object target = nativeEdge.getTarget();
if ((source instanceof ICodeContainer) && (target instanceof ICodeContainer)) {
final ICodeContainer<?> sourceCodeNode = (ICodeContainer<?>) source;
final ICodeContainer<?> targetCodeNode = (ICodeContainer<?>) target;
final IInstruction sourceInstruction = getLastInstruction(sourceCodeNode);
final IInstruction targetInstruction = getFirstInstruction(targetCodeNode);
final ReilInstruction sourceReilInstruction = lastMap.get(sourceInstruction);
final ReilInstruction targetReilInstruction = firstMap.get(targetInstruction);
insertNativeEdge(nodes, edges, nativeEdge, sourceReilInstruction, targetReilInstruction);
}
}
}
private static boolean isInlineSource(final ICodeContainer<?> container) {
return (container.getOutgoingEdges().size() == 1)
&& (container.getOutgoingEdges().get(0).getType() == EdgeType.ENTER_INLINED_FUNCTION);
}
private static boolean shareOriginalInstruction(final ReilBlock node, final ReilBlock block) {
return (getLastInstruction(block).getAddress().toLong() & ~0xFF) == (getLastInstruction(node)
.getAddress().toLong() & ~0xFF);
}
private List<ReilInstruction> getReilInstructions(final IInstruction instruction,
final ArrayList<ReilInstruction> instructions) {
final List<ReilInstruction> result = new ArrayList<ReilInstruction>();
for (final ReilInstruction reilInstruction : instructions) {
if (ReilHelpers.toNativeAddress(reilInstruction.getAddress())
.equals(instruction.getAddress())) {
result.add(reilInstruction);
}
}
return result;
}
/**
* Translates a disassembled function to REIL code.
*
* @param environment The translation environment for the translation process
* @param function The disassembled function
*
* @return The function translated to REIL code
*
* @throws InternalTranslationException Thrown if an internal error occurs
*/
public ReilFunction translate(final ITranslationEnvironment environment,
final IBlockContainer<InstructionType> function) throws InternalTranslationException {
return translate(environment, function, new ArrayList<ITranslationExtension<InstructionType>>());
}
/**
* Translates a disassembled function to REIL code.
*
* @param environment The translation environment for the translation process
* @param function The disassembled function
*
* @return The function translated to REIL code
*
* @throws InternalTranslationException Thrown if an internal error occurs
*/
public ReilFunction translate(final ITranslationEnvironment environment,
final IBlockContainer<InstructionType> function,
final List<ITranslationExtension<InstructionType>> extensions)
throws InternalTranslationException {
final LinkedHashMap<ICodeContainer<InstructionType>, List<ReilInstruction>> instructionMap =
new LinkedHashMap<ICodeContainer<InstructionType>, List<ReilInstruction>>();
final Map<IInstruction, ReilInstruction> firstMap =
new HashMap<IInstruction, ReilInstruction>();
final Map<IInstruction, ReilInstruction> lastMap = new HashMap<IInstruction, ReilInstruction>();
final List<List<ReilInstruction>> delayedTrueBranches = new ArrayList<List<ReilInstruction>>();
for (final ICodeContainer<InstructionType> block : function.getBasicBlocks()) {
final Iterable<InstructionType> blockInstructions = block.getInstructions();
final IInstruction lastBlockInstruction = Iterables.getLast(blockInstructions);
final boolean endsWithInlining = isInlineSource(block);
final ArrayList<ReilInstruction> instructions = new ArrayList<ReilInstruction>();
instructionMap.put(block, instructions);
for (final InstructionType instruction : blockInstructions) {
environment.nextInstruction();
final ITranslator<InstructionType> translator =
m_translators.get(instruction.getArchitecture().toUpperCase());
if (translator == null) {
throw new InternalTranslationException(
"Could not translate instruction from unknown architecture "
+ instruction.getArchitecture());
}
try {
final List<ReilInstruction> result =
translator.translate(environment, instruction, extensions);
instructions.addAll(result);
if (endsWithInlining && (instruction == lastBlockInstruction)) {
// We skip the last JCC instruction of blocks that were split by inlining. In 99%
// of all cases this should be the inlined call; unless the user removed the
// call from the block.
final ReilInstruction lastInstruction = instructions.get(instructions.size() - 1);
if (lastInstruction.getMnemonic().equals(ReilHelpers.OPCODE_JCC)
&& lastInstruction.getMetaData().containsKey("isCall")) {
instructions.remove(instructions.size() - 1);
result.remove(result.size() - 1);
}
}
firstMap.put(instruction, getFirstInstruction(result));
lastMap.put(instruction, getLastInstruction(result));
} catch (final InternalTranslationException exception) {
exception.setInstruction(instruction);
throw exception;
}
}
// In this step we have to consider delayed branches of the form
//
// BRANCH CONDITION, SOMEWHERE
// EXECUTE ALWAYS
//
// We basically re-order the instructions to
//
// EVALUATE CONDITION -> TEMP
// EXECUTE ALWAYS
// BRANCH TEMP, SOMEWHERE
final IInstruction secondLastInstruction =
Iterables.size(block.getInstructions()) > 2 ? Iterables.get(block.getInstructions(),
Iterables.size(block.getInstructions()) - 2, null) : null;
if (secondLastInstruction != null) {
final List<ReilInstruction> secondLastReil =
getReilInstructions(secondLastInstruction, instructions);
if (ReilHelpers.isDelayedBranch(secondLastReil.get(secondLastReil.size() - 1))) {
final IInstruction lastInstruction = getLastInstruction(block);
final List<ReilInstruction> lastReil = getReilInstructions(lastInstruction, instructions);
if (secondLastReil.get(secondLastReil.size() - 1).getMnemonic()
.equals(ReilHelpers.OPCODE_JCC)) {
instructions.removeAll(lastReil);
instructions.addAll(instructions.size() - 1, lastReil);
}
} else if (ReilHelpers.isDelayedTrueBranch(secondLastReil.get(secondLastReil.size() - 1))) {
final IInstruction lastInstruction = getLastInstruction(block);
final List<ReilInstruction> lastReil = getReilInstructions(lastInstruction, instructions);
delayedTrueBranches.add(lastReil);
}
}
}
// In this step we determine all jump targets of the input graph.
// We need them later because not all original jump targets can be
// found in the translated REIL graph. The reason for this is that
// source instructions of edges in the input graph do not necessarily
// have a reference to the address of the edge target. This happens
// for example when removing the first instruction from a code node.
// The edge still goes to the code node, but the jump instruction now
// refers to the removed instruction.
final Collection<IAddress> nativeJumpTargets = getBlockAddresses(function);
final Pair<List<ReilBlock>, List<ReilEdge>> pair =
ReilGraphGenerator.createGraphElements(instructionMap.values(), nativeJumpTargets);
final List<ReilBlock> nodes = pair.first();
final List<ReilEdge> edges = pair.second();
// In a post-processing step all edges which could not be determined
// from the REIL instructions alone are inserted into the graph.
insertNativeEdges(function.getBasicBlockEdges(), nodes, edges, firstMap, lastMap);
handleDelayedTrueBranches(nodes, edges, delayedTrueBranches);
return new ReilFunction("REIL - " + function.getName(), new ReilGraph(nodes, edges));
}
public ReilGraph translate(final ITranslationEnvironment environment,
final ICodeContainer<InstructionType> block) throws InternalTranslationException {
return translate(environment, block, new ArrayList<ITranslationExtension<InstructionType>>());
}
public ReilGraph translate(final ITranslationEnvironment environment,
final ICodeContainer<InstructionType> block,
final List<ITranslationExtension<InstructionType>> extensions)
throws InternalTranslationException {
final List<ReilInstruction> instructions = new ArrayList<ReilInstruction>();
for (final InstructionType instruction : block.getInstructions()) {
environment.nextInstruction();
final ITranslator<InstructionType> translator =
m_translators.get(instruction.getArchitecture().toUpperCase());
if (translator == null) {
throw new InternalTranslationException(
"Could not translate instruction from unknown architecture "
+ instruction.getArchitecture());
}
try {
instructions.addAll(translator.translate(environment, instruction, extensions));
} catch (final InternalTranslationException exception) {
exception.setInstruction(instruction);
throw exception;
}
}
final LinkedHashMap<ICodeContainer<InstructionType>, List<ReilInstruction>> instructionMap =
new LinkedHashMap<ICodeContainer<InstructionType>, List<ReilInstruction>>();
instructionMap.put(block, instructions);
return ReilGraphGenerator.createGraph(instructionMap.values(), new ArrayList<IAddress>());
}
public ReilGraph translate(final ITranslationEnvironment environment,
final InstructionType instruction) throws InternalTranslationException {
return translate(environment, instruction,
new ArrayList<ITranslationExtension<InstructionType>>());
}
public ReilGraph translate(final ITranslationEnvironment environment,
final InstructionType instruction,
final List<ITranslationExtension<InstructionType>> extensions)
throws InternalTranslationException {
final List<ReilInstruction> instructions = new ArrayList<ReilInstruction>();
environment.nextInstruction();
final ITranslator<InstructionType> translator =
m_translators.get(instruction.getArchitecture().toUpperCase());
if (translator == null) {
throw new InternalTranslationException(
"Could not translate instruction from unknown architecture "
+ instruction.getArchitecture());
}
try {
instructions.addAll(translator.translate(environment, instruction, extensions));
} catch (final InternalTranslationException exception) {
exception.setInstruction(instruction);
throw exception;
}
final LinkedHashMap<ICodeContainer<InstructionType>, List<ReilInstruction>> instructionMap =
new LinkedHashMap<ICodeContainer<InstructionType>, List<ReilInstruction>>();
final InstructionContainer<InstructionType> container =
new InstructionContainer<InstructionType>(instruction);
instructionMap.put(container, instructions);
return ReilGraphGenerator.createGraph(instructionMap.values(), new ArrayList<IAddress>());
}
/**
* Translates a disassembled program to REIL code.
*
* @param environment The translation environment for the translation process
* @param functions The functions of the program to be translated.
*
* @return The program translated to REIL code
*
* @throws InternalTranslationException Thrown if an internal error occurs
* @throws IllegalArgumentException Thrown if any of the arguments are invalid
*/
public ReilProgram<InstructionType> translate(final ITranslationEnvironment environment,
final List<? extends IBlockContainer<InstructionType>> functions)
throws InternalTranslationException {
Preconditions.checkNotNull(environment, "Error: Argument environment can't be null");
final ReilProgram<InstructionType> program = new ReilProgram<InstructionType>();
for (final IBlockContainer<InstructionType> function : functions) {
program.addFunction(function, translate(environment, function));
}
return program;
}
private static class InstructionContainer<InstructionType extends IInstruction> implements
ICodeContainer<InstructionType> {
private final InstructionType m_instruction;
private InstructionContainer(final InstructionType instruction) {
m_instruction = instruction;
}
@Override
public IAddress getAddress() {
return m_instruction.getAddress();
}
@SuppressWarnings("unchecked")
@Override
public Iterable<InstructionType> getInstructions() {
return Lists.newArrayList(m_instruction);
}
@Override
public InstructionType getLastInstruction() {
return m_instruction;
}
@Override
public List<? extends ICodeEdge<?>> getOutgoingEdges() {
return new ArrayList<ICodeEdge<?>>();
}
@Override
public boolean hasInstruction(final InstructionType instruction) {
return m_instruction == instruction;
}
}
}
| |
/*
* Copyright 2006-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.dsl.builder;
import com.consol.citrus.TestAction;
import com.consol.citrus.dsl.actions.DelegatingTestAction;
import com.consol.citrus.endpoint.Endpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
/**
* Action executes http server operations such as receiving requests and sending response messages.
*
* @author Christoph Deppisch
* @since 2.4
*/
public class HttpServerActionBuilder extends AbstractTestActionBuilder<DelegatingTestAction<TestAction>> {
/** Spring application context */
private ApplicationContext applicationContext;
/** Target http client instance */
private final Endpoint httpServer;
/**
* Default constructor.
*/
public HttpServerActionBuilder(DelegatingTestAction<TestAction> action, Endpoint httpServer) {
super(action);
this.httpServer = httpServer;
}
/**
* Generic response builder for sending response messages to client.
* @return
*/
public HttpServerResponseActionBuilder respond() {
return new HttpServerSendActionBuilder().response();
}
/**
* Generic response builder for sending response messages to client with response status code.
* @return
*/
public HttpServerResponseActionBuilder respond(HttpStatus status) {
return new HttpServerSendActionBuilder().response(status);
}
/**
* Receive Http requests as server.
*/
public HttpServerReceiveActionBuilder receive() {
return new HttpServerReceiveActionBuilder();
}
/**
* Send Http response messages as server to client.
*/
public HttpServerSendActionBuilder send() {
return new HttpServerSendActionBuilder();
}
/**
* Generic request builder with request method and path.
* @param method
* @param path
* @return
*/
private HttpServerRequestActionBuilder request(HttpMethod method, String path) {
HttpServerRequestActionBuilder httpServerRequestActionBuilder = new HttpServerRequestActionBuilder(action, httpServer)
.withApplicationContext(applicationContext)
.method(method);
if (StringUtils.hasText(path)) {
httpServerRequestActionBuilder.path(path);
}
return httpServerRequestActionBuilder;
}
/**
* Sets the Spring bean application context.
* @param applicationContext
*/
public HttpServerActionBuilder withApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
return this;
}
/**
* Provides send response action methods.
*/
public class HttpServerSendActionBuilder {
/**
* Generic response builder for sending response messages to client.
* @return
*/
public HttpServerResponseActionBuilder response() {
return new HttpServerResponseActionBuilder(action, httpServer)
.withApplicationContext(applicationContext);
}
/**
* Generic response builder for sending response messages to client with response status code.
* @return
*/
public HttpServerResponseActionBuilder response(HttpStatus status) {
return new HttpServerResponseActionBuilder(action, httpServer)
.withApplicationContext(applicationContext)
.status(status);
}
}
/**
* Provides receive request action methods.
*/
public class HttpServerReceiveActionBuilder {
/**
* Receive Http GET request as server.
*/
public HttpServerRequestActionBuilder get() {
return request(HttpMethod.GET, null);
}
/**
* Receive Http GET request as server.
*/
public HttpServerRequestActionBuilder get(String path) {
return request(HttpMethod.GET, path);
}
/**
* Receive Http POST request as server.
*/
public HttpServerRequestActionBuilder post() {
return request(HttpMethod.POST, null);
}
/**
* Receive Http POST request as server.
*/
public HttpServerRequestActionBuilder post(String path) {
return request(HttpMethod.POST, path);
}
/**
* Receive Http PUT request as server.
*/
public HttpServerRequestActionBuilder put() {
return request(HttpMethod.PUT, null);
}
/**
* Receive Http PUT request as server.
*/
public HttpServerRequestActionBuilder put(String path) {
return request(HttpMethod.PUT, path);
}
/**
* Receive Http DELETE request as server.
*/
public HttpServerRequestActionBuilder delete() {
return request(HttpMethod.DELETE, null);
}
/**
* Receive Http DELETE request as server.
*/
public HttpServerRequestActionBuilder delete(String path) {
return request(HttpMethod.DELETE, path);
}
/**
* Receive Http HEAD request as server.
*/
public HttpServerRequestActionBuilder head() {
return request(HttpMethod.HEAD, null);
}
/**
* Receive Http HEAD request as server.
*/
public HttpServerRequestActionBuilder head(String path) {
return request(HttpMethod.HEAD, path);
}
/**
* Receive Http OPTIONS request as server.
*/
public HttpServerRequestActionBuilder options() {
return request(HttpMethod.OPTIONS, null);
}
/**
* Receive Http OPTIONS request as server.
*/
public HttpServerRequestActionBuilder options(String path) {
return request(HttpMethod.OPTIONS, path);
}
/**
* Receive Http TRACE request as server.
*/
public HttpServerRequestActionBuilder trace() {
return request(HttpMethod.TRACE, null);
}
/**
* Receive Http TRACE request as server.
*/
public HttpServerRequestActionBuilder trace(String path) {
return request(HttpMethod.TRACE, path);
}
/**
* Receive Http PATCH request as server.
*/
public HttpServerRequestActionBuilder patch() {
return request(HttpMethod.PATCH, null);
}
/**
* Receive Http PATCH request as server.
*/
public HttpServerRequestActionBuilder patch(String path) {
return request(HttpMethod.PATCH, path);
}
}
}
| |
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.entity;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.flowpowered.math.vector.Vector3d;
import org.spongepowered.api.data.DataHolder;
import org.spongepowered.api.data.DataSerializable;
import org.spongepowered.api.data.manipulator.mutable.TargetedLocationData;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.event.cause.entity.damage.source.DamageSource;
import org.spongepowered.api.util.Identifiable;
import org.spongepowered.api.util.RelativePositions;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.TeleportHelper;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.storage.WorldProperties;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Random;
import java.util.UUID;
import java.util.function.Predicate;
/**
* An entity is a Minecraft entity.
*
* <p>Examples of entities include:</p>
*
* <ul>
* <li>Zombies</li>
* <li>Sheep</li>
* <li>Players</li>
* <li>Dropped items</li>
* <li>Dropped experience points</li>
* <li>etc.</li>
* </ul>
*
* <p>Blocks and items (when they are in inventories) are not entities.</p>
*/
public interface Entity extends Identifiable, DataHolder, DataSerializable {
/**
* Get the type of entity.
*
* @return The type of entity
*/
EntityType getType();
/**
* Gets the current world this entity resides in.
*
* @return The current world this entity resides in
*/
World getWorld();
/**
* Creates a {@link EntitySnapshot} containing the {@link EntityType} and data of this entity.
* @return The snapshot
*/
EntitySnapshot createSnapshot();
/**
* Gets the RNG for this entity.
* @return The RNG
*/
Random getRandom();
/**
* Get the location of this entity.
*
* @return The location
*/
Location<World> getLocation();
/**
* Sets the location of this entity. This is equivalent to a teleport,
* and also moves this entity's passengers.
*
* @param location The location to set
*/
void setLocation(Location<World> location);
/**
* Sets the location of this entity using a safe one from {@link TeleportHelper#getSafeLocation(Location)}. This is equivalent to a
* teleport and also moves this entity's passengers.
*
* @param location The location to set
* @return True if location was set successfully, false if location couldn't be set as no safe location was found
*/
boolean setLocationSafely(Location<World> location);
/**
* Gets the rotation.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul><code>x -> pitch</code>, <code>y -> yaw</code>, <code>z -> roll
* </code></ul>
*
* @return The rotation
*/
Vector3d getRotation();
/**
* Sets the rotation of this entity.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul><code>x -> pitch</code>, <code>y -> yaw</code>, <code>z -> roll
* </code></ul>
*
* @param rotation The rotation to set the entity to
*/
void setRotation(Vector3d rotation);
/**
* Moves the entity to the specified location, and sets the rotation.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul><code>x -> pitch</code>, <code>y -> yaw</code>, <code>z -> roll
* </code></ul>
*
* @param location The location to set
* @param rotation The rotation to set
*/
void setLocationAndRotation(Location<World> location, Vector3d rotation);
/**
* Sets the location using a safe one from {@link TeleportHelper#getSafeLocation(Location)} and the rotation of this entity.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul><code>x -> pitch</code>, <code>y -> yaw</code>, <code>z -> roll
* </code></ul>
*
* @param location The location to set
* @param rotation The rotation to set
* @return True if location was set successfully, false if location couldn't be set as no safe location was found
*/
boolean setLocationAndRotationSafely(Location<World> location, Vector3d rotation);
/**
* Moves the entity to the specified location, and sets the rotation. {@link RelativePositions}
* listed inside the EnumSet are considered relative.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul><code>x -> pitch</code>, <code>y -> yaw</code>, <code>z -> roll
* </code></ul>
*
* @param location The location to set
* @param rotation The rotation to set
* @param relativePositions The coordinates to set relatively
*/
void setLocationAndRotation(Location<World> location, Vector3d rotation, EnumSet<RelativePositions> relativePositions);
/**
* Sets the location using a safe one from
* {@link TeleportHelper#getSafeLocation(Location)} and the rotation of this
* entity. {@link RelativePositions} listed inside the EnumSet are
* considered relative.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul><code>x -> pitch</code>, <code>y -> yaw</code>, <code>z -> roll
* </code></ul>
*
* @param location The location to set
* @param rotation The rotation to set
* @param relativePositions The coordinates to set relatively
* @return True if location was set successfully, false if location
* couldn't be set as no safe location was found
*/
boolean setLocationAndRotationSafely(Location<World> location, Vector3d rotation, EnumSet<RelativePositions> relativePositions);
/**
* Gets the entity scale. Not currently used.
* Returns {@link Vector3d#ONE}.
*
* @return The entity scale
*/
Vector3d getScale();
/**
* Sets the entity scale. Not currently used.
* Does nothing.
*
* @param scale The scale
*/
void setScale(Vector3d scale);
/**
* Returns the entity transform as a new copy.
* Combines the position, rotation and scale.
*
* @return The transform as a new copy
*/
Transform<World> getTransform();
/**
* Sets the entity transform. Sets the
* position, rotation and scale at once.
*
* @param transform The transform to set
*/
void setTransform(Transform<World> transform);
/**
* Sets the location of this entity to a new position in a world which does
* not have to be loaded (but must at least be enabled).
*
* <p>If the target world is loaded then this is equivalent to
* setting the location via {@link TargetedLocationData}.</p>
*
* <p>If the target world is unloaded but is enabled according to its
* {@link WorldProperties#isEnabled()} then this will first load the world
* before transferring the entity to that world.</p>
*
* <p>If the target world is unloaded and not enabled then the transfer
* will fail.</p>
*
* @param worldName The name of the world to transfer to
* @param position The position in the target world
* @return True if the teleport was successful
*/
boolean transferToWorld(String worldName, Vector3d position);
/**
* Sets the location of this entity to a new position in a world which does
* not have to be loaded (but must at least be enabled).
*
* <p>If the target world is loaded then this is equivalent to
* setting the location via {@link TargetedLocationData}.</p>
*
* <p>If the target world is unloaded but is enabled according to its
* {@link WorldProperties#isEnabled()} then this will first load the world
* before transferring the entity to that world.</p>
*
* <p>If the target world is unloaded and not enabled then the transfer
* will fail.</p>
*
* @param uuid The UUID of the target world to transfer to
* @param position The position in the target world
* @return True if the teleport was successful
*/
boolean transferToWorld(UUID uuid, Vector3d position);
/**
* Returns whether this entity is on the ground (not in the air) or not.
*
* @return Whether this entity is on the ground or not
*/
boolean isOnGround();
/**
* Returns whether this entity has been removed.
*
* @return True if this entity has been removed
*/
boolean isRemoved();
/**
* Returns whether this entity is still loaded in a world/chunk.
*
* @return True if this entity is still loaded
*/
boolean isLoaded();
/**
* Mark this entity for removal in the very near future, preferably
* within one game tick.
*/
void remove();
/**
* Damages this {@link Entity} with the given {@link DamageSource}.
*
* @param damage The damage to deal
* @param damageSource The cause of the damage
* @return True if damaging the entity was successful
*/
default boolean damage(double damage, DamageSource damageSource) {
return damage(damage, damageSource, Cause.of(NamedCause.source(damageSource)));
}
/**
* Damages this {@link Entity} with the given {@link Cause}. It is
* imperative that a {@link DamageSource} is included
* with the cause for maximum compatibility with plugins and the game
* itself.
*
* @param damage The damage to deal
* @param damageSource The source of damage
* @param cause The cause containing auxiliary objects
* @return True if damaging the entity was successful
*/
boolean damage(double damage, DamageSource damageSource, Cause cause);
/**
* Gets the nearby entities within the desired distance.
*
* @see World#getEntities(Predicate)
* @param distance The distance
* @return The collection of nearby entities
*/
default Collection<Entity> getNearbyEntities(double distance) {
checkArgument(distance > 0, "Distance must be above zero!");
return getNearbyEntities(entity -> entity.getTransform().getPosition().distance(this.getTransform().getPosition()) <= distance);
}
/**
* Gets the nearby entities that satisfy the desired predicate.
*
* @see World#getEntities(Predicate)
* @param predicate The predicate to use
* @return The collection of entities
*/
default Collection<Entity> getNearbyEntities(Predicate<Entity> predicate) {
checkNotNull(predicate, "Null predicate!");
return getWorld().getEntities(predicate::test);
}
}
| |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight.override;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.featureStatistics.ProductivityFeatureNames;
import com.intellij.ide.util.MemberChooser;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.SpeedSearchComparator;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyFunctionBuilder;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import com.jetbrains.python.psi.types.PyClassLikeType;
import com.jetbrains.python.psi.types.PyNoneType;
import com.jetbrains.python.psi.types.PyTypeUtil;
import com.jetbrains.python.psi.types.TypeEvalContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @author Alexey.Ivanov
*/
public class PyOverrideImplementUtil {
@Nullable
public static PyClass getContextClass(@NotNull final Editor editor, @NotNull final PsiFile file) {
int offset = editor.getCaretModel().getOffset();
PsiElement element = file.findElementAt(offset);
if (element == null) {
// are we in whitespace after last class? PY-440
final PsiElement lastChild = file.getLastChild();
if (lastChild != null &&
offset >= lastChild.getTextRange().getStartOffset() &&
offset <= lastChild.getTextRange().getEndOffset()) {
element = lastChild;
}
}
final PyClass pyClass = PsiTreeUtil.getParentOfType(element, PyClass.class, false);
if (pyClass == null && element instanceof PsiWhiteSpace && element.getPrevSibling() instanceof PyClass) {
return (PyClass)element.getPrevSibling();
}
return pyClass;
}
public static void chooseAndOverrideMethods(final Project project, @NotNull final Editor editor, @NotNull final PyClass pyClass) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(ProductivityFeatureNames.CODEASSISTS_OVERRIDE_IMPLEMENT);
chooseAndOverrideOrImplementMethods(project, editor, pyClass);
}
private static void chooseAndOverrideOrImplementMethods(final Project project,
@NotNull final Editor editor,
@NotNull final PyClass pyClass) {
PyPsiUtils.assertValid(pyClass);
ApplicationManager.getApplication().assertReadAccessAllowed();
final Set<PyFunction> result = new HashSet<>();
TypeEvalContext context = TypeEvalContext.codeCompletion(project, null);
final Collection<PyFunction> superFunctions = getAllSuperFunctions(pyClass, context);
result.addAll(superFunctions);
chooseAndOverrideOrImplementMethods(project, editor, pyClass, result, "Select Methods to Override", false);
}
public static void chooseAndOverrideOrImplementMethods(@NotNull final Project project,
@NotNull final Editor editor,
@NotNull final PyClass pyClass,
@NotNull final Collection<PyFunction> superFunctions,
@NotNull final String title, final boolean implement) {
List<PyMethodMember> elements = new ArrayList<>();
for (PyFunction function : superFunctions) {
final String name = function.getName();
if (name == null || PyUtil.isClassPrivateName(name)) {
continue;
}
if (pyClass.findMethodByName(name, false, null) == null) {
final PyMethodMember member = new PyMethodMember(function);
elements.add(member);
}
}
if (elements.size() == 0) {
return;
}
final MemberChooser<PyMethodMember> chooser =
new MemberChooser<PyMethodMember>(elements.toArray(new PyMethodMember[elements.size()]), false, true, project) {
@Override
protected SpeedSearchComparator getSpeedSearchComparator() {
return new SpeedSearchComparator(false) {
@Nullable
@Override
public Iterable<TextRange> matchingFragments(@NotNull String pattern, @NotNull String text) {
return super.matchingFragments(PyMethodMember.trimUnderscores(pattern), text);
}
};
}
};
chooser.setTitle(title);
chooser.setCopyJavadocVisible(false);
chooser.show();
if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE) {
return;
}
List<PyMethodMember> membersToOverride = chooser.getSelectedElements();
overrideMethods(editor, pyClass, membersToOverride, implement);
}
public static void overrideMethods(final Editor editor, final PyClass pyClass, final List<PyMethodMember> membersToOverride,
final boolean implement) {
if (membersToOverride == null) {
return;
}
new WriteCommandAction(pyClass.getProject(), pyClass.getContainingFile()) {
protected void run(@NotNull final Result result) throws Throwable {
write(pyClass, membersToOverride, editor, implement);
}
}.execute();
}
private static void write(@NotNull final PyClass pyClass,
@NotNull final List<PyMethodMember> newMembers,
@NotNull final Editor editor, boolean implement) {
final PyStatementList statementList = pyClass.getStatementList();
final int offset = editor.getCaretModel().getOffset();
PsiElement anchor = null;
for (PyStatement statement : statementList.getStatements()) {
if (statement.getTextRange().getStartOffset() < offset ||
(statement instanceof PyExpressionStatement &&
((PyExpressionStatement)statement).getExpression() instanceof PyStringLiteralExpression)) {
anchor = statement;
}
}
PyFunction element = null;
for (PyMethodMember newMember : newMembers) {
PyFunction baseFunction = (PyFunction)newMember.getPsiElement();
final PyFunctionBuilder builder = buildOverriddenFunction(pyClass, baseFunction, implement);
PyFunction function = builder.addFunctionAfter(statementList, anchor, LanguageLevel.forElement(statementList));
element = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(function);
}
PyPsiUtils.removeRedundantPass(statementList);
if (element != null) {
final PyStatementList targetStatementList = element.getStatementList();
final int start = targetStatementList.getTextRange().getStartOffset();
editor.getCaretModel().moveToOffset(start);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().setSelection(start, element.getTextRange().getEndOffset());
}
}
private static PyFunctionBuilder buildOverriddenFunction(PyClass pyClass,
PyFunction baseFunction,
boolean implement) {
final boolean overridingNew = PyNames.NEW.equals(baseFunction.getName());
assert baseFunction.getName() != null;
PyFunctionBuilder pyFunctionBuilder = new PyFunctionBuilder(baseFunction.getName(), baseFunction);
final PyDecoratorList decorators = baseFunction.getDecoratorList();
boolean baseMethodIsStatic = false;
if (decorators != null) {
if (decorators.findDecorator(PyNames.CLASSMETHOD) != null) {
pyFunctionBuilder.decorate(PyNames.CLASSMETHOD);
}
else if (decorators.findDecorator(PyNames.STATICMETHOD) != null) {
baseMethodIsStatic = true;
pyFunctionBuilder.decorate(PyNames.STATICMETHOD);
}
else if (decorators.findDecorator(PyNames.PROPERTY) != null ||
decorators.findDecorator(PyNames.ABSTRACTPROPERTY) != null) {
pyFunctionBuilder.decorate(PyNames.PROPERTY);
}
}
final LanguageLevel level = LanguageLevel.forElement(pyClass);
PyAnnotation anno = baseFunction.getAnnotation();
if (anno != null && level.isAtLeast(LanguageLevel.PYTHON30)) {
pyFunctionBuilder.annotation(anno.getText());
}
final TypeEvalContext context = TypeEvalContext.userInitiated(baseFunction.getProject(), baseFunction.getContainingFile());
final List<PyParameter> baseParams = PyUtil.getParameters(baseFunction, context);
for (PyParameter parameter : baseParams) {
final PyNamedParameter namedParameter = parameter.getAsNamed();
if (namedParameter != null) {
final StringBuilder parameterBuilder = new StringBuilder();
if (namedParameter.isPositionalContainer()) {
parameterBuilder.append("*");
}
else if (namedParameter.isKeywordContainer()) {
parameterBuilder.append("**");
}
parameterBuilder.append(namedParameter.getName());
final PyAnnotation annotation = namedParameter.getAnnotation();
if (annotation != null && level.isAtLeast(LanguageLevel.PYTHON30)) {
parameterBuilder.append(annotation.getText());
}
final PyExpression defaultValue = namedParameter.getDefaultValue();
if (defaultValue != null) {
parameterBuilder.append("=");
parameterBuilder.append(defaultValue.getText());
}
pyFunctionBuilder.parameter(parameterBuilder.toString());
}
else {
pyFunctionBuilder.parameter(parameter.getText());
}
}
PyClass baseClass = baseFunction.getContainingClass();
assert baseClass != null;
StringBuilder statementBody = new StringBuilder();
boolean hadStar = false;
List<String> parameters = new ArrayList<>();
for (PyParameter parameter : baseParams) {
final PyNamedParameter pyNamedParameter = parameter.getAsNamed();
if (pyNamedParameter != null) {
String repr = pyNamedParameter.getRepr(false);
parameters.add(hadStar && !pyNamedParameter.isKeywordContainer() ? pyNamedParameter.getName() + "=" + repr : repr);
if (pyNamedParameter.isPositionalContainer()) {
hadStar = true;
}
}
else if (parameter instanceof PySingleStarParameter) {
hadStar = true;
}
else {
parameters.add(parameter.getText());
}
}
if (PyNames.TYPES_INSTANCE_TYPE.equals(baseClass.getQualifiedName()) || raisesNotImplementedError(baseFunction) || implement) {
statementBody.append(PyNames.PASS);
}
else {
if (!PyNames.INIT.equals(baseFunction.getName()) && context.getReturnType(baseFunction) != PyNoneType.INSTANCE || overridingNew) {
statementBody.append("return ");
}
if (baseClass.isNewStyleClass(context)) {
statementBody.append(PyNames.SUPER);
statementBody.append("(");
final LanguageLevel langLevel = ((PyFile)pyClass.getContainingFile()).getLanguageLevel();
if (!langLevel.isPy3K()) {
final String baseFirstName = !baseParams.isEmpty() ? baseParams.get(0).getName() : null;
final String firstName = baseFirstName != null ? baseFirstName : PyNames.CANONICAL_SELF;
PsiElement outerClass = PsiTreeUtil.getParentOfType(pyClass, PyClass.class, true, PyFunction.class);
String className = pyClass.getName();
final List<String> nameResult = Lists.newArrayList(className);
while (outerClass != null) {
nameResult.add(0, ((PyClass)outerClass).getName());
outerClass = PsiTreeUtil.getParentOfType(outerClass, PyClass.class, true, PyFunction.class);
}
StringUtil.join(nameResult, ".", statementBody);
statementBody.append(", ").append(firstName);
}
statementBody.append(").").append(baseFunction.getName()).append("(");
// type.__new__ is explicitly decorated as @staticmethod in our stubs, but not in real Python code
if (parameters.size() > 0 && !(baseMethodIsStatic || overridingNew)) {
parameters.remove(0);
}
}
else {
statementBody.append(getReferenceText(pyClass, baseClass)).append(".").append(baseFunction.getName()).append("(");
}
StringUtil.join(parameters, ", ", statementBody);
statementBody.append(")");
}
pyFunctionBuilder.statement(statementBody.toString());
return pyFunctionBuilder;
}
public static boolean raisesNotImplementedError(@NotNull PyFunction function) {
PyStatementList statementList = function.getStatementList();
IfVisitor visitor = new IfVisitor();
statementList.accept(visitor);
return !visitor.hasReturnInside && visitor.raiseNotImplemented;
}
// TODO find a better place for this logic
private static String getReferenceText(PyClass fromClass, PyClass toClass) {
final PyExpression[] superClassExpressions = fromClass.getSuperClassExpressions();
for (PyExpression expression : superClassExpressions) {
if (expression instanceof PyReferenceExpression) {
PsiElement target = ((PyReferenceExpression)expression).getReference().resolve();
if (target == toClass) {
return expression.getText();
}
}
}
return toClass.getName();
}
/**
* Returns all super functions available through MRO.
*/
@NotNull
public static List<PyFunction> getAllSuperFunctions(@NotNull PyClass pyClass, @NotNull TypeEvalContext context) {
final Map<String, PyFunction> functions = Maps.newLinkedHashMap();
for (final PyClassLikeType type : pyClass.getAncestorTypes(context)) {
if (type != null) {
for (PyFunction function : PyTypeUtil.getMembersOfType(type, PyFunction.class, false, context)) {
final String name = function.getName();
if (name != null && !functions.containsKey(name)) {
functions.put(name, function);
}
}
}
}
return Lists.newArrayList(functions.values());
}
private static class IfVisitor extends PyRecursiveElementVisitor {
private boolean hasReturnInside;
private boolean raiseNotImplemented;
@Override
public void visitPyReturnStatement(PyReturnStatement node) {
hasReturnInside = true;
}
@Override
public void visitPyRaiseStatement(PyRaiseStatement node) {
final PyExpression[] expressions = node.getExpressions();
if (expressions.length > 0) {
final PyExpression firstExpression = expressions[0];
if (firstExpression instanceof PyCallExpression) {
final PyExpression callee = ((PyCallExpression)firstExpression).getCallee();
if (callee != null && callee.getText().equals(PyNames.NOT_IMPLEMENTED_ERROR)) {
raiseNotImplemented = true;
}
}
else if (firstExpression.getText().equals(PyNames.NOT_IMPLEMENTED_ERROR)) {
raiseNotImplemented = true;
}
}
}
}
}
| |
package org.jutility.javafx.control.labeled;
//@formatter:off
/*
* #%L
* jutility-javafx
* %%
* Copyright (C) 2013 - 2014 jutility.org
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
//@formatter:on
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import org.jutility.javafx.control.wrapper.TextAreaWrapper;
/**
* The {@code LabeledTextArea} class provides a {@link TextAreaWrapper} with a
* freely positionable {@link Label}.
*
* @author Peter J. Radics
*
* @version 0.1.2
* @since 0.1.0
*/
public class LabeledTextArea
extends TextAreaWrapper
implements ILabeledControl {
private final ObjectProperty<Label> label;
private final ObjectProperty<Pos> labelPosition;
@Override
public ObjectProperty<Label> labelProperty() {
return this.label;
}
@Override
public Label getLabel() {
return this.label.get();
}
@Override
public void setLabel(final Label label) {
this.label.set(label);
}
@Override
public ObjectProperty<Pos> labelPositionProperty() {
return this.labelPosition;
}
@Override
public Pos getLabelPosition() {
return this.labelPosition.get();
}
@Override
public void setLabelPosition(final Pos labelPosition) {
this.labelPosition.set(labelPosition);
}
/**
* Creates a new instance of the {@code LabeledTextArea} class with the
* provided label text, positioning the {@link Label} to the left of the
* {@link TextField}.
*
* @param labelText
* the text of the {@link Label}.
*/
public LabeledTextArea(final String labelText) {
this(labelText, Pos.CENTER_LEFT);
}
/**
* Creates a new instance of the {@code LabeledTextArea} class with the
* provided label text, positioning the {@link Label} relative to the
* {@link TextField} according to the provided {@link Pos Position}.
*
* @param labelText
* the text of the {@link Label}.
* @param position
* the desired {@link Pos Position} of the {@link Label}.
*/
public LabeledTextArea(final String labelText, final Pos position) {
this(labelText, position, null);
}
/**
* Creates a new instance of the {@code LabeledTextArea} class with the
* provided label text, positioning the {@link Label} relative to the
* {@link TextField} according to the provided {@link Pos Position}.
*
* @param labelText
* the text of the {@link Label}.
* @param position
* the desired {@link Pos Position} of the {@link Label}.
* @param text
* the initial text of the {@link TextField}.
*/
public LabeledTextArea(final String labelText, final Pos position,
final String text) {
this(new Label(labelText), position, text);
}
/**
* Creates a new instance of the {@code LabeledTextArea} class with the
* provided {@link Label}, positioning the {@link Label} to the left of the
* {@link TextField}.
*
* @param label
* the {@link Label}.
*/
public LabeledTextArea(final Label label) {
this(label, Pos.CENTER_LEFT);
}
/**
* Creates a new instance of the {@code LabeledTextArea} class with the
* provided {@link Label}, positioning the {@link Label} relative to the
* {@link TextField} according to the provided {@link Pos Position}.
*
* @param label
* the {@link Label}.
* @param position
* the desired {@link Pos Position} of the {@link Label}.
*/
public LabeledTextArea(final Label label, final Pos position) {
this(label, position, null);
}
/**
* Creates a new instance of the {@code LabeledTextArea} class with the
* provided {@link Label}, positioning the {@link Label} relative to the
* {@link TextField} according to the provided {@link Pos Position}.
*
* @param label
* the {@link Label}.
* @param position
* the desired {@link Pos Position} of the {@link Label}.
* @param text
* the initial text of the {@link TextField}.
*/
public LabeledTextArea(final Label label, final Pos position,
final String text) {
super(text);
this.label = new SimpleObjectProperty<>(label);
this.labelPosition = new SimpleObjectProperty<>(position);
this.addNode(label, position);
if (label != null) {
label.setLabelFor(this.getWrappedControl());
}
this.setUpEventHandlers();
}
private void setUpEventHandlers() {
this.label.addListener((observable, oldValue, newValue) -> {
if (oldValue != null) {
this.getNodes().remove(oldValue);
}
if (newValue != null) {
this.getLabel().setLabelFor(this.getWrappedControl());
}
this.addNode(newValue, this.getLabelPosition());
});
this.labelPosition.addListener((observable, oldValue, newValue) -> {
this.removeNode(this.getLabel(), oldValue);
if (newValue != null) {
this.addNode(this.getLabel(), newValue);
}
});
this.wrappedControlProperty().addListener(
(observable, oldValue, newValue) -> {
if ((this.getLabel() != null) && (newValue != null)) {
this.getLabel().setLabelFor(newValue);
}
});
}
}
| |
package com.etk.parser;// Generated from C:\Users\Georgy\IdeaProjects\SELECTParser\src\SELECT.g4 by ANTLR 4.1
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode;
/**
* This class provides an empty implementation of {@link SELECTListener},
* which can be extended to create a listener which only needs to handle a subset
* of the available methods.
*/
public class SELECTBaseListener implements SELECTListener {
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterWhereClause(@NotNull SELECTParser.WhereClauseContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitWhereClause(@NotNull SELECTParser.WhereClauseContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterTableExpression(@NotNull SELECTParser.TableExpressionContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitTableExpression(@NotNull SELECTParser.TableExpressionContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterBooleanTest(@NotNull SELECTParser.BooleanTestContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitBooleanTest(@NotNull SELECTParser.BooleanTestContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterTruthValue(@NotNull SELECTParser.TruthValueContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitTruthValue(@NotNull SELECTParser.TruthValueContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterTablePrimary(@NotNull SELECTParser.TablePrimaryContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitTablePrimary(@NotNull SELECTParser.TablePrimaryContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterQuerySpecification(@NotNull SELECTParser.QuerySpecificationContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitQuerySpecification(@NotNull SELECTParser.QuerySpecificationContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterSelectList(@NotNull SELECTParser.SelectListContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitSelectList(@NotNull SELECTParser.SelectListContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterBooleanValueExpression(@NotNull SELECTParser.BooleanValueExpressionContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitBooleanValueExpression(@NotNull SELECTParser.BooleanValueExpressionContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterDerivedColumn(@NotNull SELECTParser.DerivedColumnContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitDerivedColumn(@NotNull SELECTParser.DerivedColumnContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterBooleanPredicand(@NotNull SELECTParser.BooleanPredicandContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitBooleanPredicand(@NotNull SELECTParser.BooleanPredicandContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterBooleanTerm(@NotNull SELECTParser.BooleanTermContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitBooleanTerm(@NotNull SELECTParser.BooleanTermContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterBooleanPrimary(@NotNull SELECTParser.BooleanPrimaryContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitBooleanPrimary(@NotNull SELECTParser.BooleanPrimaryContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterTablePrimaryAs(@NotNull SELECTParser.TablePrimaryAsContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitTablePrimaryAs(@NotNull SELECTParser.TablePrimaryAsContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterDerivedColumnList(@NotNull SELECTParser.DerivedColumnListContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitDerivedColumnList(@NotNull SELECTParser.DerivedColumnListContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterSetQuantifier(@NotNull SELECTParser.SetQuantifierContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitSetQuantifier(@NotNull SELECTParser.SetQuantifierContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterTableName(@NotNull SELECTParser.TableNameContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitTableName(@NotNull SELECTParser.TableNameContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterParenthizedBooleanValueExpression(@NotNull SELECTParser.ParenthizedBooleanValueExpressionContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitParenthizedBooleanValueExpression(@NotNull SELECTParser.ParenthizedBooleanValueExpressionContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterSearchCondition(@NotNull SELECTParser.SearchConditionContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitSearchCondition(@NotNull SELECTParser.SearchConditionContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterColumnName(@NotNull SELECTParser.ColumnNameContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitColumnName(@NotNull SELECTParser.ColumnNameContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterAsClause(@NotNull SELECTParser.AsClauseContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitAsClause(@NotNull SELECTParser.AsClauseContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterBooleanFactor(@NotNull SELECTParser.BooleanFactorContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitBooleanFactor(@NotNull SELECTParser.BooleanFactorContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterSelectStmnt(@NotNull SELECTParser.SelectStmntContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitSelectStmnt(@NotNull SELECTParser.SelectStmntContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterFromClause(@NotNull SELECTParser.FromClauseContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitFromClause(@NotNull SELECTParser.FromClauseContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void enterEveryRule(@NotNull ParserRuleContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void exitEveryRule(@NotNull ParserRuleContext ctx) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void visitTerminal(@NotNull TerminalNode node) { }
/**
* {@inheritDoc}
* <p/>
* The default implementation does nothing.
*/
@Override public void visitErrorNode(@NotNull ErrorNode node) { }
}
| |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tests.applaunch;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActivityManager;
import android.app.ActivityManager.ProcessErrorStateInfo;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.IActivityManager.WaitResult;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.UserHandle;
import android.test.InstrumentationTestCase;
import android.test.InstrumentationTestRunner;
import android.util.Log;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This test is intended to measure the time it takes for the apps to start.
* Names of the applications are passed in command line, and the
* test starts each application, and reports the start up time in milliseconds.
* The instrumentation expects the following key to be passed on the command line:
* apps - A list of applications to start and their corresponding result keys
* in the following format:
* -e apps <app name>^<result key>|<app name>^<result key>
*/
public class AppLaunch extends InstrumentationTestCase {
private static final int JOIN_TIMEOUT = 10000;
private static final String TAG = AppLaunch.class.getSimpleName();
private static final String KEY_APPS = "apps";
private static final String KEY_LAUNCH_ITERATIONS = "launch_iterations";
// optional parameter: comma separated list of required account types before proceeding
// with the app launch
private static final String KEY_REQUIRED_ACCOUNTS = "required_accounts";
private static final int INITIAL_LAUNCH_IDLE_TIMEOUT = 7500; //7.5s to allow app to idle
private static final int POST_LAUNCH_IDLE_TIMEOUT = 750; //750ms idle for non initial launches
private static final int BETWEEN_LAUNCH_SLEEP_TIMEOUT = 2000; //2s between launching apps
private Map<String, Intent> mNameToIntent;
private Map<String, String> mNameToProcess;
private Map<String, String> mNameToResultKey;
private Map<String, Long> mNameToLaunchTime;
private IActivityManager mAm;
private int mLaunchIterations = 10;
private Bundle mResult = new Bundle();
private Set<String> mRequiredAccounts;
public void testMeasureStartUpTime() throws RemoteException, NameNotFoundException {
InstrumentationTestRunner instrumentation =
(InstrumentationTestRunner)getInstrumentation();
Bundle args = instrumentation.getArguments();
mAm = ActivityManagerNative.getDefault();
createMappings();
parseArgs(args);
checkAccountSignIn();
// do initial app launch, without force stopping
for (String app : mNameToResultKey.keySet()) {
long launchTime = startApp(app, false);
if (launchTime <=0 ) {
mNameToLaunchTime.put(app, -1L);
// simply pass the app if launch isn't successful
// error should have already been logged by startApp
continue;
}
sleep(INITIAL_LAUNCH_IDLE_TIMEOUT);
closeApp(app, false);
sleep(BETWEEN_LAUNCH_SLEEP_TIMEOUT);
}
// do the real app launch now
for (int i = 0; i < mLaunchIterations; i++) {
for (String app : mNameToResultKey.keySet()) {
long totalLaunchTime = mNameToLaunchTime.get(app);
long launchTime = 0;
if (totalLaunchTime < 0) {
// skip if the app has previous failures
continue;
}
launchTime = startApp(app, true);
if (launchTime <= 0) {
// if it fails once, skip the rest of the launches
mNameToLaunchTime.put(app, -1L);
continue;
}
totalLaunchTime += launchTime;
mNameToLaunchTime.put(app, totalLaunchTime);
sleep(POST_LAUNCH_IDLE_TIMEOUT);
closeApp(app, true);
sleep(BETWEEN_LAUNCH_SLEEP_TIMEOUT);
}
}
for (String app : mNameToResultKey.keySet()) {
long totalLaunchTime = mNameToLaunchTime.get(app);
if (totalLaunchTime != -1) {
mResult.putDouble(mNameToResultKey.get(app),
((double) totalLaunchTime) / mLaunchIterations);
}
}
instrumentation.sendStatus(0, mResult);
}
private void parseArgs(Bundle args) {
mNameToResultKey = new LinkedHashMap<String, String>();
mNameToLaunchTime = new HashMap<String, Long>();
String launchIterations = args.getString(KEY_LAUNCH_ITERATIONS);
if (launchIterations != null) {
mLaunchIterations = Integer.parseInt(launchIterations);
}
String appList = args.getString(KEY_APPS);
if (appList == null)
return;
String appNames[] = appList.split("\\|");
for (String pair : appNames) {
String[] parts = pair.split("\\^");
if (parts.length != 2) {
Log.e(TAG, "The apps key is incorectly formatted");
fail();
}
mNameToResultKey.put(parts[0], parts[1]);
mNameToLaunchTime.put(parts[0], 0L);
}
String requiredAccounts = args.getString(KEY_REQUIRED_ACCOUNTS);
if (requiredAccounts != null) {
mRequiredAccounts = new HashSet<String>();
for (String accountType : requiredAccounts.split(",")) {
mRequiredAccounts.add(accountType);
}
}
}
private void createMappings() {
mNameToIntent = new LinkedHashMap<String, Intent>();
mNameToProcess = new LinkedHashMap<String, String>();
PackageManager pm = getInstrumentation().getContext()
.getPackageManager();
Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> ris = pm.queryIntentActivities(intentToResolve, 0);
if (ris == null || ris.isEmpty()) {
Log.i(TAG, "Could not find any apps");
} else {
for (ResolveInfo ri : ris) {
Intent startIntent = new Intent(intentToResolve);
startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
startIntent.setClassName(ri.activityInfo.packageName,
ri.activityInfo.name);
String appName = ri.loadLabel(pm).toString();
if (appName != null) {
mNameToIntent.put(appName, startIntent);
mNameToProcess.put(appName, ri.activityInfo.processName);
}
}
}
}
private long startApp(String appName, boolean forceStopBeforeLaunch)
throws NameNotFoundException, RemoteException {
Log.i(TAG, "Starting " + appName);
Intent startIntent = mNameToIntent.get(appName);
if (startIntent == null) {
Log.w(TAG, "App does not exist: " + appName);
mResult.putString(mNameToResultKey.get(appName), "App does not exist");
return -1;
}
AppLaunchRunnable runnable = new AppLaunchRunnable(startIntent, forceStopBeforeLaunch);
Thread t = new Thread(runnable);
t.start();
try {
t.join(JOIN_TIMEOUT);
} catch (InterruptedException e) {
// ignore
}
WaitResult result = runnable.getResult();
// report error if any of the following is true:
// * launch thread is alive
// * result is not null, but:
// * result is not START_SUCESS
// * or in case of no force stop, result is not TASK_TO_FRONT either
if (t.isAlive() || (result != null
&& ((result.result != ActivityManager.START_SUCCESS)
&& (!forceStopBeforeLaunch
&& result.result != ActivityManager.START_TASK_TO_FRONT)))) {
Log.w(TAG, "Assuming app " + appName + " crashed.");
reportError(appName, mNameToProcess.get(appName));
return -1;
}
return result.thisTime;
}
private void checkAccountSignIn() {
// ensure that the device has the required account types before starting test
// e.g. device must have a valid Google account sign in to measure a meaningful launch time
// for Gmail
if (mRequiredAccounts == null || mRequiredAccounts.isEmpty()) {
return;
}
final AccountManager am =
(AccountManager) getInstrumentation().getTargetContext().getSystemService(
Context.ACCOUNT_SERVICE);
Account[] accounts = am.getAccounts();
// use set here in case device has multiple accounts of the same type
Set<String> foundAccounts = new HashSet<String>();
for (Account account : accounts) {
if (mRequiredAccounts.contains(account.type)) {
foundAccounts.add(account.type);
}
}
// check if account type matches, if not, fail test with message on what account types
// are missing
if (mRequiredAccounts.size() != foundAccounts.size()) {
mRequiredAccounts.removeAll(foundAccounts);
StringBuilder sb = new StringBuilder("Device missing these accounts:");
for (String account : mRequiredAccounts) {
sb.append(' ');
sb.append(account);
}
fail(sb.toString());
}
}
private void closeApp(String appName, boolean forceStopApp) {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
getInstrumentation().getContext().startActivity(homeIntent);
sleep(POST_LAUNCH_IDLE_TIMEOUT);
if (forceStopApp) {
Intent startIntent = mNameToIntent.get(appName);
if (startIntent != null) {
String packageName = startIntent.getComponent().getPackageName();
try {
mAm.forceStopPackage(packageName, UserHandle.USER_CURRENT);
} catch (RemoteException e) {
Log.w(TAG, "Error closing app", e);
}
}
}
}
private void sleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// ignore
}
}
private void reportError(String appName, String processName) {
ActivityManager am = (ActivityManager) getInstrumentation()
.getContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ProcessErrorStateInfo> crashes = am.getProcessesInErrorState();
if (crashes != null) {
for (ProcessErrorStateInfo crash : crashes) {
if (!crash.processName.equals(processName))
continue;
Log.w(TAG, appName + " crashed: " + crash.shortMsg);
mResult.putString(mNameToResultKey.get(appName), crash.shortMsg);
return;
}
}
mResult.putString(mNameToResultKey.get(appName),
"Crashed for unknown reason");
Log.w(TAG, appName
+ " not found in process list, most likely it is crashed");
}
private class AppLaunchRunnable implements Runnable {
private Intent mLaunchIntent;
private IActivityManager.WaitResult mResult;
private boolean mForceStopBeforeLaunch;
public AppLaunchRunnable(Intent intent, boolean forceStopBeforeLaunch) {
mLaunchIntent = intent;
mForceStopBeforeLaunch = forceStopBeforeLaunch;
}
public IActivityManager.WaitResult getResult() {
return mResult;
}
public void run() {
try {
String packageName = mLaunchIntent.getComponent().getPackageName();
if (mForceStopBeforeLaunch) {
mAm.forceStopPackage(packageName, UserHandle.USER_CURRENT);
}
String mimeType = mLaunchIntent.getType();
if (mimeType == null && mLaunchIntent.getData() != null
&& "content".equals(mLaunchIntent.getData().getScheme())) {
mimeType = mAm.getProviderMimeType(mLaunchIntent.getData(),
UserHandle.USER_CURRENT);
}
mResult = mAm.startActivityAndWait(null, null, mLaunchIntent, mimeType,
null, null, 0, mLaunchIntent.getFlags(), null, null, null,
UserHandle.USER_CURRENT);
} catch (RemoteException e) {
Log.w(TAG, "Error launching app", e);
}
}
}
}
| |
/*
* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.ssl;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import sun.security.ssl.NamedGroup.NamedGroupSpec;
import sun.security.ssl.SupportedGroupsExtension.SupportedGroups;
import sun.security.ssl.X509Authentication.X509Possession;
import sun.security.util.KeyUtil;
import sun.security.util.SignatureUtil;
enum SignatureScheme {
// ECDSA algorithms
ECDSA_SECP256R1_SHA256 (0x0403, "ecdsa_secp256r1_sha256",
"SHA256withECDSA",
"EC",
NamedGroup.SECP256_R1,
ProtocolVersion.PROTOCOLS_TO_13),
ECDSA_SECP384R1_SHA384 (0x0503, "ecdsa_secp384r1_sha384",
"SHA384withECDSA",
"EC",
NamedGroup.SECP384_R1,
ProtocolVersion.PROTOCOLS_TO_13),
ECDSA_SECP521R1_SHA512 (0x0603, "ecdsa_secp521r1_sha512",
"SHA512withECDSA",
"EC",
NamedGroup.SECP521_R1,
ProtocolVersion.PROTOCOLS_TO_13),
// EdDSA algorithms
ED25519 (0x0807, "ed25519", "Ed25519",
"EdDSA",
ProtocolVersion.PROTOCOLS_12_13),
ED448 (0x0808, "ed448", "Ed448",
"EdDSA",
ProtocolVersion.PROTOCOLS_12_13),
// RSASSA-PSS algorithms with public key OID rsaEncryption
//
// The minimalKeySize is calculated as (See RFC 8017 for details):
// hash length + salt length + 16
RSA_PSS_RSAE_SHA256 (0x0804, "rsa_pss_rsae_sha256",
"RSASSA-PSS", "RSA",
SigAlgParamSpec.RSA_PSS_SHA256, 528,
ProtocolVersion.PROTOCOLS_12_13),
RSA_PSS_RSAE_SHA384 (0x0805, "rsa_pss_rsae_sha384",
"RSASSA-PSS", "RSA",
SigAlgParamSpec.RSA_PSS_SHA384, 784,
ProtocolVersion.PROTOCOLS_12_13),
RSA_PSS_RSAE_SHA512 (0x0806, "rsa_pss_rsae_sha512",
"RSASSA-PSS", "RSA",
SigAlgParamSpec.RSA_PSS_SHA512, 1040,
ProtocolVersion.PROTOCOLS_12_13),
// RSASSA-PSS algorithms with public key OID RSASSA-PSS
//
// The minimalKeySize is calculated as (See RFC 8017 for details):
// hash length + salt length + 16
RSA_PSS_PSS_SHA256 (0x0809, "rsa_pss_pss_sha256",
"RSASSA-PSS", "RSASSA-PSS",
SigAlgParamSpec.RSA_PSS_SHA256, 528,
ProtocolVersion.PROTOCOLS_12_13),
RSA_PSS_PSS_SHA384 (0x080A, "rsa_pss_pss_sha384",
"RSASSA-PSS", "RSASSA-PSS",
SigAlgParamSpec.RSA_PSS_SHA384, 784,
ProtocolVersion.PROTOCOLS_12_13),
RSA_PSS_PSS_SHA512 (0x080B, "rsa_pss_pss_sha512",
"RSASSA-PSS", "RSASSA-PSS",
SigAlgParamSpec.RSA_PSS_SHA512, 1040,
ProtocolVersion.PROTOCOLS_12_13),
// RSASSA-PKCS1-v1_5 algorithms
RSA_PKCS1_SHA256 (0x0401, "rsa_pkcs1_sha256", "SHA256withRSA",
"RSA", null, null, 511,
ProtocolVersion.PROTOCOLS_TO_13,
ProtocolVersion.PROTOCOLS_TO_12),
RSA_PKCS1_SHA384 (0x0501, "rsa_pkcs1_sha384", "SHA384withRSA",
"RSA", null, null, 768,
ProtocolVersion.PROTOCOLS_TO_13,
ProtocolVersion.PROTOCOLS_TO_12),
RSA_PKCS1_SHA512 (0x0601, "rsa_pkcs1_sha512", "SHA512withRSA",
"RSA", null, null, 768,
ProtocolVersion.PROTOCOLS_TO_13,
ProtocolVersion.PROTOCOLS_TO_12),
// Legacy algorithms
DSA_SHA256 (0x0402, "dsa_sha256", "SHA256withDSA",
"DSA",
ProtocolVersion.PROTOCOLS_TO_12),
ECDSA_SHA224 (0x0303, "ecdsa_sha224", "SHA224withECDSA",
"EC",
ProtocolVersion.PROTOCOLS_TO_12),
RSA_SHA224 (0x0301, "rsa_sha224", "SHA224withRSA",
"RSA", 511,
ProtocolVersion.PROTOCOLS_TO_12),
DSA_SHA224 (0x0302, "dsa_sha224", "SHA224withDSA",
"DSA",
ProtocolVersion.PROTOCOLS_TO_12),
ECDSA_SHA1 (0x0203, "ecdsa_sha1", "SHA1withECDSA",
"EC",
ProtocolVersion.PROTOCOLS_TO_13),
RSA_PKCS1_SHA1 (0x0201, "rsa_pkcs1_sha1", "SHA1withRSA",
"RSA", null, null, 511,
ProtocolVersion.PROTOCOLS_TO_13,
ProtocolVersion.PROTOCOLS_TO_12),
DSA_SHA1 (0x0202, "dsa_sha1", "SHA1withDSA",
"DSA",
ProtocolVersion.PROTOCOLS_TO_12),
RSA_MD5 (0x0101, "rsa_md5", "MD5withRSA",
"RSA", 511,
ProtocolVersion.PROTOCOLS_TO_12);
final int id; // hash + signature
final String name; // literal name
private final String algorithm; // signature algorithm
final String keyAlgorithm; // signature key algorithm
private final SigAlgParamSpec signAlgParams; // signature parameters
private final NamedGroup namedGroup; // associated named group
// The minimal required key size in bits.
//
// Only need to check RSA algorithm at present. RSA keys of 512 bits
// have been shown to be practically breakable, it does not make much
// sense to use the strong hash algorithm for keys whose key size less
// than 512 bits. So it is not necessary to calculate the minimal
// required key size exactly for a hash algorithm.
//
// Note that some provider may use 511 bits for 512-bit strength RSA keys.
final int minimalKeySize;
final List<ProtocolVersion> supportedProtocols;
// Some signature schemes are supported in different versions for handshake
// messages and certificates. This field holds the supported protocols
// for handshake messages.
final List<ProtocolVersion> handshakeSupportedProtocols;
final boolean isAvailable;
private static final String[] hashAlgorithms = new String[] {
"none", "md5", "sha1", "sha224",
"sha256", "sha384", "sha512"
};
private static final String[] signatureAlgorithms = new String[] {
"anonymous", "rsa", "dsa", "ecdsa",
};
static enum SigAlgParamSpec { // support RSASSA-PSS only now
RSA_PSS_SHA256 ("SHA-256", 32),
RSA_PSS_SHA384 ("SHA-384", 48),
RSA_PSS_SHA512 ("SHA-512", 64);
private final AlgorithmParameterSpec parameterSpec;
private final AlgorithmParameters parameters;
private final boolean isAvailable;
SigAlgParamSpec(String hash, int saltLength) {
// See RFC 8017
PSSParameterSpec pssParamSpec =
new PSSParameterSpec(hash, "MGF1",
new MGF1ParameterSpec(hash), saltLength, 1);
AlgorithmParameters pssParams = null;
boolean mediator = true;
try {
Signature signer = Signature.getInstance("RSASSA-PSS");
signer.setParameter(pssParamSpec);
pssParams = signer.getParameters();
} catch (InvalidAlgorithmParameterException |
NoSuchAlgorithmException | RuntimeException exp) {
// Signature.getParameters() may throw RuntimeException.
mediator = false;
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.warning(
"RSASSA-PSS signature with " + hash +
" is not supported by the underlying providers", exp);
}
}
this.isAvailable = mediator;
this.parameterSpec = mediator ? pssParamSpec : null;
this.parameters = mediator ? pssParams : null;
}
}
// performance optimization
private static final Set<CryptoPrimitive> SIGNATURE_PRIMITIVE_SET =
Collections.unmodifiableSet(EnumSet.of(CryptoPrimitive.SIGNATURE));
private SignatureScheme(int id, String name,
String algorithm, String keyAlgorithm,
ProtocolVersion[] supportedProtocols) {
this(id, name, algorithm, keyAlgorithm, -1, supportedProtocols);
}
private SignatureScheme(int id, String name,
String algorithm, String keyAlgorithm,
int minimalKeySize,
ProtocolVersion[] supportedProtocols) {
this(id, name, algorithm, keyAlgorithm,
null, minimalKeySize, supportedProtocols);
}
private SignatureScheme(int id, String name,
String algorithm, String keyAlgorithm,
SigAlgParamSpec signAlgParamSpec, int minimalKeySize,
ProtocolVersion[] supportedProtocols) {
this(id, name, algorithm, keyAlgorithm,
signAlgParamSpec, null, minimalKeySize,
supportedProtocols, supportedProtocols);
}
private SignatureScheme(int id, String name,
String algorithm, String keyAlgorithm,
NamedGroup namedGroup,
ProtocolVersion[] supportedProtocols) {
this(id, name, algorithm, keyAlgorithm,
null, namedGroup, -1,
supportedProtocols, supportedProtocols);
}
private SignatureScheme(int id, String name,
String algorithm, String keyAlgorithm,
SigAlgParamSpec signAlgParams,
NamedGroup namedGroup, int minimalKeySize,
ProtocolVersion[] supportedProtocols,
ProtocolVersion[] handshakeSupportedProtocols) {
this.id = id;
this.name = name;
this.algorithm = algorithm;
this.keyAlgorithm = keyAlgorithm;
this.signAlgParams = signAlgParams;
this.namedGroup = namedGroup;
this.minimalKeySize = minimalKeySize;
this.supportedProtocols = Arrays.asList(supportedProtocols);
this.handshakeSupportedProtocols =
Arrays.asList(handshakeSupportedProtocols);
boolean mediator = true;
// An EC provider, for example the SunEC provider, may support
// AlgorithmParameters but not KeyPairGenerator or Signature.
//
// Note: Please be careful if removing this block!
if ("EC".equals(keyAlgorithm)) {
mediator = JsseJce.isEcAvailable();
}
// Check the specific algorithm and parameters.
if (mediator) {
if (signAlgParams != null) {
mediator = signAlgParams.isAvailable;
} else {
try {
Signature.getInstance(algorithm);
} catch (Exception e) {
mediator = false;
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.warning(
"Signature algorithm, " + algorithm +
", is not supported by the underlying providers");
}
}
}
}
if (mediator && ((id >> 8) & 0xFF) == 0x03) { // SHA224
// There are some problems to use SHA224 on Windows.
if (Security.getProvider("SunMSCAPI") != null) {
mediator = false;
}
}
this.isAvailable = mediator;
}
static SignatureScheme valueOf(int id) {
for (SignatureScheme ss: SignatureScheme.values()) {
if (ss.id == id) {
return ss;
}
}
return null;
}
static String nameOf(int id) {
for (SignatureScheme ss: SignatureScheme.values()) {
if (ss.id == id) {
return ss.name;
}
}
// Use TLS 1.2 style name for unknown signature scheme.
int hashId = ((id >> 8) & 0xFF);
int signId = (id & 0xFF);
String hashName = (hashId >= hashAlgorithms.length) ?
"UNDEFINED-HASH(" + hashId + ")" : hashAlgorithms[hashId];
String signName = (signId >= signatureAlgorithms.length) ?
"UNDEFINED-SIGNATURE(" + signId + ")" :
signatureAlgorithms[signId];
return signName + "_" + hashName;
}
// Note: the signatureSchemeName is not case-sensitive.
static SignatureScheme nameOf(String signatureSchemeName) {
for (SignatureScheme ss: SignatureScheme.values()) {
if (ss.name.equalsIgnoreCase(signatureSchemeName)) {
return ss;
}
}
return null;
}
// Return the size of a SignatureScheme structure in TLS record
static int sizeInRecord() {
return 2;
}
private boolean isPermitted(AlgorithmConstraints constraints) {
return constraints.permits(SIGNATURE_PRIMITIVE_SET,
this.name, null) &&
constraints.permits(SIGNATURE_PRIMITIVE_SET,
this.keyAlgorithm, null) &&
constraints.permits(SIGNATURE_PRIMITIVE_SET,
this.algorithm, (signAlgParams != null ?
signAlgParams.parameters : null)) &&
(namedGroup == null ||
namedGroup.isPermitted(constraints));
}
// Get local supported algorithm collection complying to algorithm
// constraints.
static List<SignatureScheme> getSupportedAlgorithms(
SSLConfiguration config,
AlgorithmConstraints constraints,
List<ProtocolVersion> activeProtocols) {
List<SignatureScheme> supported = new LinkedList<>();
// If config.signatureSchemes is non-empty then it means that
// it was defined by a System property. Per
// SSLConfiguration.getCustomizedSignatureScheme() the list will
// only contain schemes that are in the enum.
// Otherwise, use the enum constants (converted to a List).
List<SignatureScheme> schemesToCheck =
config.signatureSchemes.isEmpty() ?
Arrays.asList(SignatureScheme.values()) :
config.signatureSchemes;
for (SignatureScheme ss: schemesToCheck) {
if (!ss.isAvailable) {
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Ignore unsupported signature scheme: " + ss.name);
}
continue;
}
boolean isMatch = false;
for (ProtocolVersion pv : activeProtocols) {
if (ss.supportedProtocols.contains(pv)) {
isMatch = true;
break;
}
}
if (isMatch) {
if (ss.isPermitted(constraints)) {
supported.add(ss);
} else if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Ignore disabled signature scheme: " + ss.name);
}
} else if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Ignore inactive signature scheme: " + ss.name);
}
}
return supported;
}
static List<SignatureScheme> getSupportedAlgorithms(
SSLConfiguration config,
AlgorithmConstraints constraints,
ProtocolVersion protocolVersion, int[] algorithmIds) {
List<SignatureScheme> supported = new LinkedList<>();
for (int ssid : algorithmIds) {
SignatureScheme ss = SignatureScheme.valueOf(ssid);
if (ss == null) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.warning(
"Unsupported signature scheme: " +
SignatureScheme.nameOf(ssid));
}
} else if (ss.isAvailable &&
ss.supportedProtocols.contains(protocolVersion) &&
(config.signatureSchemes.isEmpty() ||
config.signatureSchemes.contains(ss)) &&
ss.isPermitted(constraints)) {
supported.add(ss);
} else {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.warning(
"Unsupported signature scheme: " + ss.name);
}
}
}
return supported;
}
static SignatureScheme getPreferableAlgorithm(
AlgorithmConstraints constraints,
List<SignatureScheme> schemes,
SignatureScheme certScheme,
ProtocolVersion version) {
for (SignatureScheme ss : schemes) {
if (ss.isAvailable &&
ss.handshakeSupportedProtocols.contains(version) &&
certScheme.keyAlgorithm.equalsIgnoreCase(ss.keyAlgorithm) &&
ss.isPermitted(constraints)) {
return ss;
}
}
return null;
}
static Map.Entry<SignatureScheme, Signature> getSignerOfPreferableAlgorithm(
AlgorithmConstraints constraints,
List<SignatureScheme> schemes,
X509Possession x509Possession,
ProtocolVersion version) {
PrivateKey signingKey = x509Possession.popPrivateKey;
String keyAlgorithm = signingKey.getAlgorithm();
int keySize;
// Only need to check RSA algorithm at present.
if (keyAlgorithm.equalsIgnoreCase("RSA") ||
keyAlgorithm.equalsIgnoreCase("RSASSA-PSS")) {
keySize = KeyUtil.getKeySize(signingKey);
} else {
keySize = Integer.MAX_VALUE;
}
for (SignatureScheme ss : schemes) {
if (ss.isAvailable && (keySize >= ss.minimalKeySize) &&
ss.handshakeSupportedProtocols.contains(version) &&
keyAlgorithm.equalsIgnoreCase(ss.keyAlgorithm) &&
ss.isPermitted(constraints)) {
if ((ss.namedGroup != null) && (ss.namedGroup.spec ==
NamedGroupSpec.NAMED_GROUP_ECDHE)) {
ECParameterSpec params =
x509Possession.getECParameterSpec();
if (params != null &&
ss.namedGroup == NamedGroup.valueOf(params)) {
Signature signer = ss.getSigner(signingKey);
if (signer != null) {
return new SimpleImmutableEntry<>(ss, signer);
}
}
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Ignore the signature algorithm (" + ss +
"), unsupported EC parameter spec: " + params);
}
} else if ("EC".equals(ss.keyAlgorithm)) {
// Must be a legacy signature algorithm, which does not
// specify the associated named groups. The connection
// cannot be established if the peer cannot recognize
// the named group used for the signature. RFC 8446
// does not define countermeasures for the corner cases.
// In order to mitigate the impact, we choose to check
// against the local supported named groups. The risk
// should be minimal as applications should not use
// unsupported named groups for its certificates.
ECParameterSpec params =
x509Possession.getECParameterSpec();
if (params != null) {
NamedGroup keyGroup = NamedGroup.valueOf(params);
if (keyGroup != null &&
SupportedGroups.isSupported(keyGroup)) {
Signature signer = ss.getSigner(signingKey);
if (signer != null) {
return new SimpleImmutableEntry<>(ss, signer);
}
}
}
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Ignore the legacy signature algorithm (" + ss +
"), unsupported EC parameter spec: " + params);
}
} else {
Signature signer = ss.getSigner(signingKey);
if (signer != null) {
return new SimpleImmutableEntry<>(ss, signer);
}
}
}
}
return null;
}
static String[] getAlgorithmNames(Collection<SignatureScheme> schemes) {
if (schemes != null) {
ArrayList<String> names = new ArrayList<>(schemes.size());
for (SignatureScheme scheme : schemes) {
names.add(scheme.algorithm);
}
return names.toArray(new String[0]);
}
return new String[0];
}
// This method is used to get the signature instance of this signature
// scheme for the specific public key. Unlike getSigner(), the exception
// is bubbled up. If the public key does not support this signature
// scheme, it normally means the TLS handshaking cannot continue and
// the connection should be terminated.
Signature getVerifier(PublicKey publicKey) throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException, InvalidKeyException {
if (!isAvailable) {
return null;
}
Signature verifier = Signature.getInstance(algorithm);
SignatureUtil.initVerifyWithParam(verifier, publicKey,
(signAlgParams != null ? signAlgParams.parameterSpec : null));
return verifier;
}
// This method is also used to choose preferable signature scheme for the
// specific private key. If the private key does not support the signature
// scheme, {@code null} is returned, and the caller may fail back to next
// available signature scheme.
private Signature getSigner(PrivateKey privateKey) {
if (!isAvailable) {
return null;
}
try {
Signature signer = Signature.getInstance(algorithm);
SignatureUtil.initSignWithParam(signer, privateKey,
(signAlgParams != null ? signAlgParams.parameterSpec : null),
null);
return signer;
} catch (NoSuchAlgorithmException | InvalidKeyException |
InvalidAlgorithmParameterException nsae) {
if (SSLLogger.isOn &&
SSLLogger.isOn("ssl,handshake,verbose")) {
SSLLogger.finest(
"Ignore unsupported signature algorithm (" +
this.name + ")", nsae);
}
}
return null;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.security.ssl;
import static org.junit.Assert.assertTrue;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.alias.CredentialProviderFactory;
import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.log4j.Level;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import java.io.File;
import java.net.URL;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Map;
public class TestSSLFactory {
private static final Logger LOG = LoggerFactory
.getLogger(TestSSLFactory.class);
private static final String BASEDIR =
GenericTestUtils.getTempPath(TestSSLFactory.class.getSimpleName());
private static final String KEYSTORES_DIR =
new File(BASEDIR).getAbsolutePath();
private String sslConfsDir;
private static final String excludeCiphers = "TLS_ECDHE_RSA_WITH_RC4_128_SHA,"
+ "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,"
+ "SSL_RSA_WITH_DES_CBC_SHA,"
+ "SSL_DHE_RSA_WITH_DES_CBC_SHA,"
+ "SSL_RSA_EXPORT_WITH_RC4_40_MD5,"
+ "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,"
+ "SSL_RSA_WITH_RC4_128_MD5";
@BeforeClass
public static void setUp() throws Exception {
File base = new File(BASEDIR);
FileUtil.fullyDelete(base);
base.mkdirs();
}
private Configuration createConfiguration(boolean clientCert,
boolean trustStore)
throws Exception {
Configuration conf = new Configuration();
KeyStoreTestUtil.setupSSLConfig(KEYSTORES_DIR, sslConfsDir, conf,
clientCert, trustStore, excludeCiphers);
return conf;
}
@After
@Before
public void cleanUp() throws Exception {
sslConfsDir = KeyStoreTestUtil.getClasspathDir(TestSSLFactory.class);
KeyStoreTestUtil.cleanupSSLConfig(KEYSTORES_DIR, sslConfsDir);
}
@Test(expected = IllegalStateException.class)
public void clientMode() throws Exception {
Configuration conf = createConfiguration(false, true);
SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
try {
sslFactory.init();
Assert.assertNotNull(sslFactory.createSSLSocketFactory());
Assert.assertNotNull(sslFactory.getHostnameVerifier());
sslFactory.createSSLServerSocketFactory();
} finally {
sslFactory.destroy();
}
}
private void serverMode(boolean clientCert, boolean socket) throws Exception {
Configuration conf = createConfiguration(clientCert, true);
SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.SERVER, conf);
try {
sslFactory.init();
Assert.assertNotNull(sslFactory.createSSLServerSocketFactory());
Assert.assertEquals(clientCert, sslFactory.isClientCertRequired());
if (socket) {
sslFactory.createSSLSocketFactory();
} else {
sslFactory.getHostnameVerifier();
}
} finally {
sslFactory.destroy();
}
}
@Test(expected = IllegalStateException.class)
public void serverModeWithoutClientCertsSocket() throws Exception {
serverMode(false, true);
}
@Test(expected = IllegalStateException.class)
public void serverModeWithClientCertsSocket() throws Exception {
serverMode(true, true);
}
@Test(expected = IllegalStateException.class)
public void serverModeWithoutClientCertsVerifier() throws Exception {
serverMode(false, false);
}
@Test(expected = IllegalStateException.class)
public void serverModeWithClientCertsVerifier() throws Exception {
serverMode(true, false);
}
private void runDelegatedTasks(SSLEngineResult result, SSLEngine engine)
throws Exception {
Runnable runnable;
if (result.getHandshakeStatus() ==
SSLEngineResult.HandshakeStatus.NEED_TASK) {
while ((runnable = engine.getDelegatedTask()) != null) {
LOG.info("running delegated task...");
runnable.run();
}
SSLEngineResult.HandshakeStatus hsStatus = engine.getHandshakeStatus();
if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) {
throw new Exception("handshake shouldn't need additional tasks");
}
}
}
private static boolean isEngineClosed(SSLEngine engine) {
return engine.isOutboundDone() && engine.isInboundDone();
}
private static void checkTransfer(ByteBuffer a, ByteBuffer b)
throws Exception {
a.flip();
b.flip();
assertTrue("transfer did not complete", a.equals(b));
a.position(a.limit());
b.position(b.limit());
a.limit(a.capacity());
b.limit(b.capacity());
}
@Test
public void testServerWeakCiphers() throws Exception {
// a simple test case to verify that SSL server rejects weak cipher suites,
// inspired by https://docs.oracle.com/javase/8/docs/technotes/guides/
// security/jsse/samples/sslengine/SSLEngineSimpleDemo.java
// set up a client and a server SSLEngine object, and let them exchange
// data over ByteBuffer instead of network socket.
GenericTestUtils.setLogLevel(SSLFactory.LOG, Level.DEBUG);
final Configuration conf = createConfiguration(true, true);
SSLFactory serverSSLFactory = new SSLFactory(SSLFactory.Mode.SERVER, conf);
SSLFactory clientSSLFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
serverSSLFactory.init();
clientSSLFactory.init();
SSLEngine serverSSLEngine = serverSSLFactory.createSSLEngine();
SSLEngine clientSSLEngine = clientSSLFactory.createSSLEngine();
// client selects cipher suites excluded by server
clientSSLEngine.setEnabledCipherSuites(excludeCiphers.split(","));
// use the same buffer size for server and client.
SSLSession session = clientSSLEngine.getSession();
int appBufferMax = session.getApplicationBufferSize();
int netBufferMax = session.getPacketBufferSize();
ByteBuffer clientOut = ByteBuffer.wrap("client".getBytes());
ByteBuffer clientIn = ByteBuffer.allocate(appBufferMax);
ByteBuffer serverOut = ByteBuffer.wrap("server".getBytes());
ByteBuffer serverIn = ByteBuffer.allocate(appBufferMax);
// send data from client to server
ByteBuffer cTOs = ByteBuffer.allocateDirect(netBufferMax);
// send data from server to client
ByteBuffer sTOc = ByteBuffer.allocateDirect(netBufferMax);
boolean dataDone = false;
try {
/**
* Server and client engines call wrap()/unwrap() to perform handshaking,
* until both engines are closed.
*/
while (!isEngineClosed(clientSSLEngine) ||
!isEngineClosed(serverSSLEngine)) {
LOG.info("client wrap " + wrap(clientSSLEngine, clientOut, cTOs));
LOG.info("server wrap " + wrap(serverSSLEngine, serverOut, sTOc));
cTOs.flip();
sTOc.flip();
LOG.info("client unwrap " + unwrap(clientSSLEngine, sTOc, clientIn));
LOG.info("server unwrap " + unwrap(serverSSLEngine, cTOs, serverIn));
cTOs.compact();
sTOc.compact();
if (!dataDone && (clientOut.limit() == serverIn.position()) &&
(serverOut.limit() == clientIn.position())) {
checkTransfer(serverOut, clientIn);
checkTransfer(clientOut, serverIn);
LOG.info("closing client");
clientSSLEngine.closeOutbound();
dataDone = true;
}
}
Assert.fail("The exception was not thrown");
} catch (SSLHandshakeException e) {
GenericTestUtils.assertExceptionContains("no cipher suites in common", e);
}
}
private SSLEngineResult wrap(SSLEngine engine, ByteBuffer from,
ByteBuffer to) throws Exception {
SSLEngineResult result = engine.wrap(from, to);
runDelegatedTasks(result, engine);
return result;
}
private SSLEngineResult unwrap(SSLEngine engine, ByteBuffer from,
ByteBuffer to) throws Exception {
SSLEngineResult result = engine.unwrap(from, to);
runDelegatedTasks(result, engine);
return result;
}
@Test
public void validHostnameVerifier() throws Exception {
Configuration conf = createConfiguration(false, true);
conf.unset(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY);
SSLFactory sslFactory = new
SSLFactory(SSLFactory.Mode.CLIENT, conf);
sslFactory.init();
Assert.assertEquals("DEFAULT", sslFactory.getHostnameVerifier().toString());
sslFactory.destroy();
conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "ALLOW_ALL");
sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
sslFactory.init();
Assert.assertEquals("ALLOW_ALL",
sslFactory.getHostnameVerifier().toString());
sslFactory.destroy();
conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "DEFAULT_AND_LOCALHOST");
sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
sslFactory.init();
Assert.assertEquals("DEFAULT_AND_LOCALHOST",
sslFactory.getHostnameVerifier().toString());
sslFactory.destroy();
conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "STRICT");
sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
sslFactory.init();
Assert.assertEquals("STRICT", sslFactory.getHostnameVerifier().toString());
sslFactory.destroy();
conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "STRICT_IE6");
sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
sslFactory.init();
Assert.assertEquals("STRICT_IE6",
sslFactory.getHostnameVerifier().toString());
sslFactory.destroy();
}
@Test(expected = GeneralSecurityException.class)
public void invalidHostnameVerifier() throws Exception {
Configuration conf = createConfiguration(false, true);
conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "foo");
SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
try {
sslFactory.init();
} finally {
sslFactory.destroy();
}
}
@Test
public void testConnectionConfigurator() throws Exception {
Configuration conf = createConfiguration(false, true);
conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "STRICT_IE6");
SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
try {
sslFactory.init();
HttpsURLConnection sslConn =
(HttpsURLConnection) new URL("https://foo").openConnection();
Assert.assertNotSame("STRICT_IE6",
sslConn.getHostnameVerifier().toString());
sslFactory.configure(sslConn);
Assert.assertEquals("STRICT_IE6",
sslConn.getHostnameVerifier().toString());
} finally {
sslFactory.destroy();
}
}
@Test
public void testServerDifferentPasswordAndKeyPassword() throws Exception {
checkSSLFactoryInitWithPasswords(SSLFactory.Mode.SERVER, "password",
"keyPassword", "password", "keyPassword");
}
@Test
public void testServerKeyPasswordDefaultsToPassword() throws Exception {
checkSSLFactoryInitWithPasswords(SSLFactory.Mode.SERVER, "password",
"password", "password", null);
}
@Test
public void testClientDifferentPasswordAndKeyPassword() throws Exception {
checkSSLFactoryInitWithPasswords(SSLFactory.Mode.CLIENT, "password",
"keyPassword", "password", "keyPassword");
}
@Test
public void testClientKeyPasswordDefaultsToPassword() throws Exception {
checkSSLFactoryInitWithPasswords(SSLFactory.Mode.CLIENT, "password",
"password", "password", null);
}
@Test
public void testServerCredProviderPasswords() throws Exception {
KeyStoreTestUtil.provisionPasswordsToCredentialProvider();
checkSSLFactoryInitWithPasswords(SSLFactory.Mode.SERVER,
"storepass", "keypass", null, null, true);
}
/**
* Checks that SSLFactory initialization is successful with the given
* arguments. This is a helper method for writing test cases that cover
* different combinations of settings for the store password and key password.
* It takes care of bootstrapping a keystore, a truststore, and SSL client or
* server configuration. Then, it initializes an SSLFactory. If no exception
* is thrown, then initialization was successful.
*
* @param mode SSLFactory.Mode mode to test
* @param password String store password to set on keystore
* @param keyPassword String key password to set on keystore
* @param confPassword String store password to set in SSL config file, or null
* to avoid setting in SSL config file
* @param confKeyPassword String key password to set in SSL config file, or
* null to avoid setting in SSL config file
* @throws Exception for any error
*/
private void checkSSLFactoryInitWithPasswords(SSLFactory.Mode mode,
String password, String keyPassword, String confPassword,
String confKeyPassword) throws Exception {
checkSSLFactoryInitWithPasswords(mode, password, keyPassword,
confPassword, confKeyPassword, false);
}
/**
* Checks that SSLFactory initialization is successful with the given
* arguments. This is a helper method for writing test cases that cover
* different combinations of settings for the store password and key password.
* It takes care of bootstrapping a keystore, a truststore, and SSL client or
* server configuration. Then, it initializes an SSLFactory. If no exception
* is thrown, then initialization was successful.
*
* @param mode SSLFactory.Mode mode to test
* @param password String store password to set on keystore
* @param keyPassword String key password to set on keystore
* @param confPassword String store password to set in SSL config file, or null
* to avoid setting in SSL config file
* @param confKeyPassword String key password to set in SSL config file, or
* null to avoid setting in SSL config file
* @param useCredProvider boolean to indicate whether passwords should be set
* into the config or not. When set to true nulls are set and aliases are
* expected to be resolved through credential provider API through the
* Configuration.getPassword method
* @throws Exception for any error
*/
private void checkSSLFactoryInitWithPasswords(SSLFactory.Mode mode,
String password, String keyPassword, String confPassword,
String confKeyPassword, boolean useCredProvider) throws Exception {
String keystore = new File(KEYSTORES_DIR, "keystore.jks").getAbsolutePath();
String truststore = new File(KEYSTORES_DIR, "truststore.jks")
.getAbsolutePath();
String trustPassword = "trustP";
// Create keys, certs, keystore, and truststore.
KeyPair keyPair = KeyStoreTestUtil.generateKeyPair("RSA");
X509Certificate cert = KeyStoreTestUtil.generateCertificate("CN=Test",
keyPair, 30, "SHA1withRSA");
KeyStoreTestUtil.createKeyStore(keystore, password, keyPassword, "Test",
keyPair.getPrivate(), cert);
Map<String, X509Certificate> certs = Collections.singletonMap("server",
cert);
KeyStoreTestUtil.createTrustStore(truststore, trustPassword, certs);
// Create SSL configuration file, for either server or client.
final String sslConfFileName;
final Configuration sslConf;
// if the passwords are provisioned in a cred provider then don't set them
// in the configuration properly - expect them to be resolved through the
// provider
if (useCredProvider) {
confPassword = null;
confKeyPassword = null;
}
if (mode == SSLFactory.Mode.SERVER) {
sslConfFileName = "ssl-server.xml";
sslConf = KeyStoreTestUtil.createServerSSLConfig(keystore, confPassword,
confKeyPassword, truststore);
if (useCredProvider) {
File testDir = GenericTestUtils.getTestDir();
final Path jksPath = new Path(testDir.toString(), "test.jks");
final String ourUrl =
JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri();
sslConf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, ourUrl);
}
} else {
sslConfFileName = "ssl-client.xml";
sslConf = KeyStoreTestUtil.createClientSSLConfig(keystore, confPassword,
confKeyPassword, truststore);
}
KeyStoreTestUtil.saveConfig(new File(sslConfsDir, sslConfFileName), sslConf);
// Create the master configuration for use by the SSLFactory, which by
// default refers to the ssl-server.xml or ssl-client.xml created above.
Configuration conf = new Configuration();
conf.setBoolean(SSLFactory.SSL_REQUIRE_CLIENT_CERT_KEY, true);
// Try initializing an SSLFactory.
SSLFactory sslFactory = new SSLFactory(mode, conf);
try {
sslFactory.init();
} finally {
sslFactory.destroy();
}
}
@Test
public void testNoClientCertsInitialization() throws Exception {
Configuration conf = createConfiguration(false, true);
conf.unset(SSLFactory.SSL_REQUIRE_CLIENT_CERT_KEY);
SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
try {
sslFactory.init();
} finally {
sslFactory.destroy();
}
}
@Test
public void testNoTrustStore() throws Exception {
Configuration conf = createConfiguration(false, false);
conf.unset(SSLFactory.SSL_REQUIRE_CLIENT_CERT_KEY);
SSLFactory sslFactory = new SSLFactory(SSLFactory.Mode.SERVER, conf);
try {
sslFactory.init();
} finally {
sslFactory.destroy();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.shindig.gadgets.servlet;
import org.apache.shindig.auth.AuthInfo;
import org.apache.shindig.auth.SecurityToken;
import org.apache.shindig.gadgets.GadgetContext;
import org.apache.shindig.gadgets.RenderingContext;
import org.apache.shindig.gadgets.UserPrefs;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* Implements GadgetContext using an HttpServletRequest
*/
public class HttpGadgetContext extends GadgetContext {
public static final String USERPREF_PARAM_PREFIX = "up_";
private final HttpServletRequest request;
private final String container;
private final Boolean debug;
private final Boolean ignoreCache;
private final Locale locale;
private final Integer moduleId;
private final RenderingContext renderingContext;
private final URI url;
private final UserPrefs userPrefs;
private final String view;
public HttpGadgetContext(HttpServletRequest request) {
this.request = request;
container = getContainer(request);
debug = getDebug(request);
ignoreCache = getIgnoreCache(request);
locale = getLocale(request);
moduleId = getModuleId(request);
renderingContext = getRenderingContext(request);
url = getUrl(request);
userPrefs = getUserPrefs(request);
view = getView(request);
}
@Override
public String getParameter(String name) {
return request.getParameter(name);
}
@Override
public String getContainer() {
if (container == null) {
return super.getContainer();
}
return container;
}
@Override
public String getHost() {
String host = request.getHeader("Host");
if (host == null) {
return super.getHost();
}
return host;
}
@Override
public String getUserIp() {
String ip = request.getRemoteAddr();
if (ip == null) {
return super.getUserIp();
}
return ip;
}
@Override
public boolean getDebug() {
if (debug == null) {
return super.getDebug();
}
return debug;
}
@Override
public boolean getIgnoreCache() {
if (ignoreCache == null) {
return super.getIgnoreCache();
}
return ignoreCache;
}
@Override
public Locale getLocale() {
if (locale == null) {
return super.getLocale();
}
return locale;
}
@Override
public int getModuleId() {
if (moduleId == null) {
return super.getModuleId();
}
return moduleId;
}
@Override
public RenderingContext getRenderingContext() {
if (renderingContext == null) {
return super.getRenderingContext();
}
return renderingContext;
}
@Override
public SecurityToken getToken() {
return new AuthInfo(request).getSecurityToken();
}
@Override
public URI getUrl() {
if (url == null) {
return super.getUrl();
}
return url;
}
@Override
public UserPrefs getUserPrefs() {
if (userPrefs == null) {
return super.getUserPrefs();
}
return userPrefs;
}
@Override
public String getView() {
if (view == null) {
return super.getView();
}
return view;
}
/**
* @param req
* @return The container, if set, or null.
*/
private static String getContainer(HttpServletRequest req) {
String container = req.getParameter("container");
if (container == null) {
// The parameter used to be called 'synd' FIXME: schedule removal
container = req.getParameter("synd");
}
return container;
}
/**
* @param req
* @return Debug setting, if set, or null.
*/
private static Boolean getDebug(HttpServletRequest req) {
String debug = req.getParameter("debug");
if (debug == null) {
return null;
} else if ("0".equals(debug)) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* @param req
* @return The ignore cache setting, if appropriate params are set, or null.
*/
private static Boolean getIgnoreCache(HttpServletRequest req) {
String ignoreCache = req.getParameter("nocache");
if (ignoreCache == null) {
return null;
} else if ("0".equals(ignoreCache)) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* @param req
* @return The locale, if appropriate parameters are set, or null.
*/
private static Locale getLocale(HttpServletRequest req) {
String language = req.getParameter("lang");
String country = req.getParameter("country");
if (language == null && country == null) {
return null;
} else if (language == null) {
language = "all";
} else if (country == null) {
country = "ALL";
}
return new Locale(language, country);
}
/**
* @param req
* @return module id, if specified
*/
private static Integer getModuleId(HttpServletRequest req) {
String mid = req.getParameter("mid");
if (mid == null) {
return null;
}
return Integer.parseInt(mid);
}
/**
* @param req
* @return The rendering context, if appropriate params are set, or null.
*/
private static RenderingContext getRenderingContext(HttpServletRequest req) {
String c = req.getParameter("c");
if (c == null) {
return null;
}
return c.equals("1") ? RenderingContext.CONTAINER : RenderingContext.GADGET;
}
/**
* @param req
* @return The ignore cache setting, if appropriate params are set, or null.
*/
private static URI getUrl(HttpServletRequest req) {
String url = req.getParameter("url");
if (url == null) {
return null;
}
try {
return new URI(url);
} catch (URISyntaxException e) {
return null;
}
}
/**
* @param req
* @return UserPrefs, if any are set for this request.
*/
@SuppressWarnings("unchecked")
private static UserPrefs getUserPrefs(HttpServletRequest req) {
Map<String, String> prefs = new HashMap<String, String>();
Enumeration<String> paramNames = req.getParameterNames();
if (paramNames == null) {
return null;
}
while (paramNames.hasMoreElements()) {
String paramName = paramNames.nextElement();
if (paramName.startsWith(USERPREF_PARAM_PREFIX)) {
String prefName = paramName.substring(USERPREF_PARAM_PREFIX.length());
prefs.put(prefName, req.getParameter(paramName));
}
}
return new UserPrefs(prefs);
}
/**
* @param req
* @return The view, if specified, or null.
*/
private static String getView(HttpServletRequest req) {
return req.getParameter("view");
}
}
| |
/**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.reddcoin.core;
import com.google.reddcoin.script.Script;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.Map;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A transfer of coins from one address to another creates a transaction in which the outputs
* can be claimed by the recipient in the input of another transaction. You can imagine a
* transaction as being a module which is wired up to others, the inputs of one have to be wired
* to the outputs of another. The exceptions are coinbase transactions, which create new coins.
*/
public class TransactionInput extends ChildMessage implements Serializable {
public static final long NO_SEQUENCE = 0xFFFFFFFFL;
private static final long serialVersionUID = 2;
public static final byte[] EMPTY_ARRAY = new byte[0];
// Allows for altering transactions after they were broadcast. Tx replacement is currently disabled in the C++
// client so this is always the UINT_MAX.
// TODO: Document this in more detail and build features that use it.
private long sequence;
// Data needed to connect to the output of the transaction we're gathering coins from.
private TransactionOutPoint outpoint;
// The "script bytes" might not actually be a script. In coinbase transactions where new coins are minted there
// is no input transaction, so instead the scriptBytes contains some extra stuff (like a rollover nonce) that we
// don't care about much. The bytes are turned into a Script object (cached below) on demand via a getter.
private byte[] scriptBytes;
// The Script object obtained from parsing scriptBytes. Only filled in on demand and if the transaction is not
// coinbase.
transient private WeakReference<Script> scriptSig;
// A pointer to the transaction that owns this input.
private Transaction parentTransaction;
/**
* Creates an input that connects to nothing - used only in creation of coinbase transactions.
*/
public TransactionInput(NetworkParameters params, Transaction parentTransaction, byte[] scriptBytes) {
super(params);
this.scriptBytes = scriptBytes;
this.outpoint = new TransactionOutPoint(params, NO_SEQUENCE, (Transaction)null);
this.sequence = NO_SEQUENCE;
this.parentTransaction = parentTransaction;
length = 40 + (scriptBytes == null ? 1 : VarInt.sizeOf(scriptBytes.length) + scriptBytes.length);
}
public TransactionInput(NetworkParameters params, @Nullable Transaction parentTransaction, byte[] scriptBytes,
TransactionOutPoint outpoint) {
super(params);
this.scriptBytes = scriptBytes;
this.outpoint = outpoint;
this.sequence = NO_SEQUENCE;
this.parentTransaction = parentTransaction;
length = 40 + (scriptBytes == null ? 1 : VarInt.sizeOf(scriptBytes.length) + scriptBytes.length);
}
/**
* Creates an UNSIGNED input that links to the given output
*/
TransactionInput(NetworkParameters params, Transaction parentTransaction, TransactionOutput output) {
super(params);
long outputIndex = output.getIndex();
outpoint = new TransactionOutPoint(params, outputIndex, output.parentTransaction);
scriptBytes = EMPTY_ARRAY;
sequence = NO_SEQUENCE;
this.parentTransaction = parentTransaction;
length = 41;
}
/**
* Deserializes an input message. This is usually part of a transaction message.
*/
public TransactionInput(NetworkParameters params, Transaction parentTransaction,
byte[] payload, int offset) throws ProtocolException {
super(params, payload, offset);
this.parentTransaction = parentTransaction;
}
/**
* Deserializes an input message. This is usually part of a transaction message.
* @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content.
* @param offset The location of the first msg byte within the array.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization.
* If true and the backing byte array is invalidated due to modification of a field then
* the cached bytes may be repopulated and retained if the message is serialized again in the future.
* as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
* @throws ProtocolException
*/
public TransactionInput(NetworkParameters params, Transaction parentTransaction, byte[] msg, int offset,
boolean parseLazy, boolean parseRetain)
throws ProtocolException {
super(params, msg, offset, parentTransaction, parseLazy, parseRetain, UNKNOWN_LENGTH);
this.parentTransaction = parentTransaction;
}
protected void parseLite() throws ProtocolException {
int curs = cursor;
int scriptLen = (int) readVarInt(36);
length = cursor - offset + scriptLen + 4;
cursor = curs;
}
void parse() throws ProtocolException {
outpoint = new TransactionOutPoint(params, bytes, cursor, this, parseLazy, parseRetain);
cursor += outpoint.getMessageSize();
int scriptLen = (int) readVarInt();
scriptBytes = readBytes(scriptLen);
sequence = readUint32();
}
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
outpoint.bitcoinSerialize(stream);
stream.write(new VarInt(scriptBytes.length).encode());
stream.write(scriptBytes);
Utils.uint32ToByteStreamLE(sequence, stream);
}
/**
* Coinbase transactions have special inputs with hashes of zero. If this is such an input, returns true.
*/
public boolean isCoinBase() {
maybeParse();
return outpoint.getHash().equals(Sha256Hash.ZERO_HASH) &&
(outpoint.getIndex() & 0xFFFFFFFFL) == 0xFFFFFFFFL; // -1 but all is serialized to the wire as unsigned int.
}
/**
* Returns the script that is fed to the referenced output (scriptPubKey) script in order to satisfy it: usually
* contains signatures and maybe keys, but can contain arbitrary data if the output script accepts it.
*/
public Script getScriptSig() throws ScriptException {
// Transactions that generate new coins don't actually have a script. Instead this
// parameter is overloaded to be something totally different.
Script script = scriptSig == null ? null : scriptSig.get();
if (script == null) {
maybeParse();
script = new Script(scriptBytes);
scriptSig = new WeakReference<Script>(script);
return script;
}
return script;
}
/** Set the given program as the scriptSig that is supposed to satisfy the connected output script. */
public void setScriptSig(Script scriptSig) {
this.scriptSig = new WeakReference<Script>(checkNotNull(scriptSig));
// TODO: This should all be cleaned up so we have a consistent internal representation.
setScriptBytes(scriptSig.getProgram());
}
/**
* Convenience method that returns the from address of this input by parsing the scriptSig. The concept of a
* "from address" is not well defined in Bitcoin and you should not assume that senders of a transaction can
* actually receive coins on the same address they used to sign (e.g. this is not true for shared wallets).
*/
@Deprecated
public Address getFromAddress() throws ScriptException {
if (isCoinBase()) {
throw new ScriptException(
"This is a coinbase transaction which generates new coins. It does not have a from address.");
}
return getScriptSig().getFromAddress(params);
}
/**
* Sequence numbers allow participants in a multi-party transaction signing protocol to create new versions of the
* transaction independently of each other. Newer versions of a transaction can replace an existing version that's
* in nodes memory pools if the existing version is time locked. See the Contracts page on the Bitcoin wiki for
* examples of how you can use this feature to build contract protocols. Note that as of 2012 the tx replacement
* feature is disabled so sequence numbers are unusable.
*/
public long getSequenceNumber() {
maybeParse();
return sequence;
}
/**
* Sequence numbers allow participants in a multi-party transaction signing protocol to create new versions of the
* transaction independently of each other. Newer versions of a transaction can replace an existing version that's
* in nodes memory pools if the existing version is time locked. See the Contracts page on the Bitcoin wiki for
* examples of how you can use this feature to build contract protocols. Note that as of 2012 the tx replacement
* feature is disabled so sequence numbers are unusable.
*/
public void setSequenceNumber(long sequence) {
unCache();
this.sequence = sequence;
}
/**
* @return The previous output transaction reference, as an OutPoint structure. This contains the
* data needed to connect to the output of the transaction we're gathering coins from.
*/
public TransactionOutPoint getOutpoint() {
maybeParse();
return outpoint;
}
/**
* The "script bytes" might not actually be a script. In coinbase transactions where new coins are minted there
* is no input transaction, so instead the scriptBytes contains some extra stuff (like a rollover nonce) that we
* don't care about much. The bytes are turned into a Script object (cached below) on demand via a getter.
* @return the scriptBytes
*/
public byte[] getScriptBytes() {
maybeParse();
return scriptBytes;
}
/**
* @param scriptBytes the scriptBytes to set
*/
void setScriptBytes(byte[] scriptBytes) {
unCache();
this.scriptSig = null;
int oldLength = length;
this.scriptBytes = scriptBytes;
// 40 = previous_outpoint (36) + sequence (4)
int newLength = 40 + (scriptBytes == null ? 1 : VarInt.sizeOf(scriptBytes.length) + scriptBytes.length);
adjustLength(newLength - oldLength);
}
/**
* @return The Transaction that owns this input.
*/
public Transaction getParentTransaction() {
return parentTransaction;
}
/**
* Returns a human readable debug string.
*/
public String toString() {
if (isCoinBase())
return "TxIn: COINBASE";
try {
return "TxIn for [" + outpoint + "]: " + getScriptSig();
} catch (ScriptException e) {
throw new RuntimeException(e);
}
}
public enum ConnectionResult {
NO_SUCH_TX,
ALREADY_SPENT,
SUCCESS
}
// TODO: Clean all this up once TransactionOutPoint disappears.
/**
* Locates the referenced output from the given pool of transactions.
*
* @return The TransactionOutput or null if the transactions map doesn't contain the referenced tx.
*/
@Nullable
TransactionOutput getConnectedOutput(Map<Sha256Hash, Transaction> transactions) {
Transaction tx = transactions.get(outpoint.getHash());
if (tx == null)
return null;
return tx.getOutputs().get((int) outpoint.getIndex());
}
public enum ConnectMode {
DISCONNECT_ON_CONFLICT,
ABORT_ON_CONFLICT
}
/**
* Connects this input to the relevant output of the referenced transaction if it's in the given map.
* Connecting means updating the internal pointers and spent flags. If the mode is to ABORT_ON_CONFLICT then
* the spent output won't be changed, but the outpoint.fromTx pointer will still be updated.
*
* @param transactions Map of txhash->transaction.
* @param mode Whether to abort if there's a pre-existing connection or not.
* @return NO_SUCH_TX if the prevtx wasn't found, ALREADY_SPENT if there was a conflict, SUCCESS if not.
*/
public ConnectionResult connect(Map<Sha256Hash, Transaction> transactions, ConnectMode mode) {
Transaction tx = transactions.get(outpoint.getHash());
if (tx == null) {
return TransactionInput.ConnectionResult.NO_SUCH_TX;
}
return connect(tx, mode);
}
/**
* Connects this input to the relevant output of the referenced transaction.
* Connecting means updating the internal pointers and spent flags. If the mode is to ABORT_ON_CONFLICT then
* the spent output won't be changed, but the outpoint.fromTx pointer will still be updated.
*
* @param transaction The transaction to try.
* @param mode Whether to abort if there's a pre-existing connection or not.
* @return NO_SUCH_TX if transaction is not the prevtx, ALREADY_SPENT if there was a conflict, SUCCESS if not.
*/
public ConnectionResult connect(Transaction transaction, ConnectMode mode) {
if (!transaction.getHash().equals(outpoint.getHash()))
return ConnectionResult.NO_SUCH_TX;
checkElementIndex((int) outpoint.getIndex(), transaction.getOutputs().size(), "Corrupt transaction");
TransactionOutput out = transaction.getOutput((int) outpoint.getIndex());
if (!out.isAvailableForSpending()) {
if (out.parentTransaction.equals(outpoint.fromTx)) {
// Already connected.
return ConnectionResult.SUCCESS;
} else if (mode == ConnectMode.DISCONNECT_ON_CONFLICT) {
out.markAsUnspent();
} else if (mode == ConnectMode.ABORT_ON_CONFLICT) {
outpoint.fromTx = checkNotNull(out.parentTransaction);
return TransactionInput.ConnectionResult.ALREADY_SPENT;
}
}
connect(out);
return TransactionInput.ConnectionResult.SUCCESS;
}
/** Internal use only: connects this TransactionInput to the given output (updates pointers and spent flags) */
public void connect(TransactionOutput out) {
outpoint.fromTx = checkNotNull(out.parentTransaction);
out.markAsSpent(this);
}
/**
* If this input is connected, check the output is connected back to this input and release it if so, making
* it spendable once again.
*
* @return true if the disconnection took place, false if it was not connected.
*/
public boolean disconnect() {
if (outpoint.fromTx == null) return false;
TransactionOutput output = outpoint.fromTx.getOutput((int) outpoint.getIndex());
if (output.getSpentBy() == this) {
output.markAsUnspent();
outpoint.fromTx = null;
return true;
} else {
return false;
}
}
/**
* Ensure object is fully parsed before invoking java serialization. The backing byte array
* is transient so if the object has parseLazy = true and hasn't invoked checkParse yet
* then data will be lost during serialization.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
maybeParse();
out.defaultWriteObject();
}
/**
* @return true if this transaction's sequence number is set (ie it may be a part of a time-locked transaction)
*/
public boolean hasSequence() {
return sequence != NO_SEQUENCE;
}
/**
* For a connected transaction, runs the script against the connected pubkey and verifies they are correct.
* @throws ScriptException if the script did not verify.
* @throws VerificationException If the outpoint doesn't match the given output.
*/
public void verify() throws VerificationException {
final Transaction fromTx = getOutpoint().fromTx;
long spendingIndex = getOutpoint().getIndex();
checkNotNull(fromTx, "Not connected");
final TransactionOutput output = fromTx.getOutput((int) spendingIndex);
verify(output);
}
/**
* Verifies that this input can spend the given output. Note that this input must be a part of a transaction.
* Also note that the consistency of the outpoint will be checked, even if this input has not been connected.
*
* @param output the output that this input is supposed to spend.
* @throws ScriptException If the script doesn't verify.
* @throws VerificationException If the outpoint doesn't match the given output.
*/
public void verify(TransactionOutput output) throws VerificationException {
if (!getOutpoint().getHash().equals(output.parentTransaction.getHash()))
throw new VerificationException("This input does not refer to the tx containing the output.");
if (getOutpoint().getIndex() != output.getIndex())
throw new VerificationException("This input refers to a different output on the given tx.");
Script pubKey = output.getScriptPubKey();
int myIndex = parentTransaction.getInputs().indexOf(this);
getScriptSig().correctlySpends(parentTransaction, myIndex, pubKey, true);
}
/**
* Returns the connected output, assuming the input was connected with
* {@link TransactionInput#connect(TransactionOutput)} or variants at some point. If it wasn't connected, then
* this method returns null.
*/
@Nullable
public TransactionOutput getConnectedOutput() {
return getOutpoint().getConnectedOutput();
}
}
| |
/*
* Copyright 1999-2011 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.dubbo.common.serialize.support.dubbo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import com.alibaba.dubbo.common.bytecode.ClassGenerator;
import com.alibaba.dubbo.common.io.ClassDescriptorMapper;
import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream;
import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.serialize.support.java.CompactedObjectInputStream;
import com.alibaba.dubbo.common.serialize.support.java.CompactedObjectOutputStream;
import com.alibaba.dubbo.common.utils.ClassHelper;
import com.alibaba.dubbo.common.utils.IOUtils;
import com.alibaba.dubbo.common.utils.ReflectUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
/**
* Builder.
*
* @author qian.lei
*
* @param <T> type.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public abstract class Builder<T> implements GenericDataFlags
{
// Must be protected. by qian.lei
protected static Logger logger = LoggerFactory.getLogger(Builder.class);
private static final AtomicLong BUILDER_CLASS_COUNTER = new AtomicLong(0);
private static final String BUILDER_CLASS_NAME = Builder.class.getName();
private static final Map<Class<?>, Builder<?>> BuilderMap = new ConcurrentHashMap<Class<?>, Builder<?>>();
private static final Map<Class<?>, Builder<?>> nonSerializableBuilderMap = new ConcurrentHashMap<Class<?>, Builder<?>>();
private static final String FIELD_CONFIG_SUFFIX = ".fc";
private static final int MAX_FIELD_CONFIG_FILE_SIZE = 16 * 1024;
private static final Comparator<String> FNC = new Comparator<String>(){
public int compare(String n1, String n2){ return compareFieldName(n1, n2); }
};
private static final Comparator<Field> FC = new Comparator<Field>(){
public int compare(Field f1, Field f2){ return compareFieldName(f1.getName(), f2.getName()); }
};
private static final Comparator<Constructor> CC = new Comparator<Constructor>(){
public int compare(Constructor o1, Constructor o2){ return o1.getParameterTypes().length - o2.getParameterTypes().length; }
};
// class-descriptor mapper
private static final List<String> mDescList = new ArrayList<String>();
private static final Map<String, Integer> mDescMap = new ConcurrentHashMap<String, Integer>();
public static ClassDescriptorMapper DEFAULT_CLASS_DESCRIPTOR_MAPPER = new ClassDescriptorMapper(){
public String getDescriptor(int index)
{
if( index < 0 || index >= mDescList.size() )
return null;
return mDescList.get(index);
}
public int getDescriptorIndex(String desc)
{
Integer ret = mDescMap.get(desc);
return ret == null ? -1 : ret.intValue();
}
};
protected Builder(){}
abstract public Class<T> getType();
public void writeTo(T obj, OutputStream os) throws IOException
{
GenericObjectOutput out = new GenericObjectOutput(os);
writeTo(obj, out);
out.flushBuffer();
}
public T parseFrom(byte[] b) throws IOException
{
return parseFrom(new UnsafeByteArrayInputStream(b));
}
public T parseFrom(InputStream is) throws IOException
{
return parseFrom(new GenericObjectInput(is));
}
abstract public void writeTo(T obj, GenericObjectOutput out) throws IOException;
abstract public T parseFrom(GenericObjectInput in) throws IOException;
public static <T> Builder<T> register(Class<T> c, boolean isAllowNonSerializable)
{
if( c == Object.class || c.isInterface() )
return (Builder<T>)GenericBuilder;
if( c == Object[].class )
return (Builder<T>)GenericArrayBuilder;
Builder<T> b = (Builder<T>)BuilderMap.get(c);
if(null != b) return b;
boolean isSerializable = Serializable.class.isAssignableFrom(c);
if(!isAllowNonSerializable && !isSerializable) {
throw new IllegalStateException("Serialized class " + c.getName() +
" must implement java.io.Serializable (dubbo codec setting: isAllowNonSerializable = false)");
}
b = (Builder<T>)nonSerializableBuilderMap.get(c);
if(null != b) return b;
b = newBuilder(c);
if(isSerializable)
BuilderMap.put(c, b);
else
nonSerializableBuilderMap.put(c, b);
return b;
}
public static <T> Builder<T> register(Class<T> c)
{
return register(c, false);
}
public static <T> void register(Class<T> c, Builder<T> b)
{
if(Serializable.class.isAssignableFrom(c))
BuilderMap.put(c, b);
else
nonSerializableBuilderMap.put(c, b);
}
private static <T> Builder<T> newBuilder(Class<T> c)
{
if( c.isPrimitive() )
throw new RuntimeException("Can not create builder for primitive type: " + c);
if( logger.isInfoEnabled() )
logger.info("create Builder for class: " + c);
Builder<?> builder;
if( c.isArray() )
builder = newArrayBuilder(c);
else
builder = newObjectBuilder(c);
return (Builder<T>)builder;
}
private static Builder<?> newArrayBuilder(Class<?> c)
{
Class<?> cc = c.getComponentType();
if( cc.isInterface() )
return GenericArrayBuilder;
ClassLoader cl = ClassHelper.getClassLoader(c);
String cn = ReflectUtils.getName(c), ccn = ReflectUtils.getName(cc); // get class name as int[][], double[].
String bcn = BUILDER_CLASS_NAME + "$bc" + BUILDER_CLASS_COUNTER.getAndIncrement();
int ix = cn.indexOf(']');
String s1 = cn.substring(0, ix), s2 = cn.substring(ix); // if name='int[][]' then s1='int[', s2='][]'
StringBuilder cwt = new StringBuilder("public void writeTo(Object obj, ").append(GenericObjectOutput.class.getName()).append(" out) throws java.io.IOException{"); // writeTo code.
StringBuilder cpf = new StringBuilder("public Object parseFrom(").append(GenericObjectInput.class.getName()).append(" in) throws java.io.IOException{"); // parseFrom code.
cwt.append("if( $1 == null ){ $2.write0(OBJECT_NULL); return; }");
cwt.append(cn).append(" v = (").append(cn).append(")$1; int len = v.length; $2.write0(OBJECT_VALUES); $2.writeUInt(len); for(int i=0;i<len;i++){ ");
cpf.append("byte b = $1.read0(); if( b == OBJECT_NULL ) return null; if( b != OBJECT_VALUES ) throw new java.io.IOException(\"Input format error, expect OBJECT_NULL|OBJECT_VALUES, get \" + b + \".\");");
cpf.append("int len = $1.readUInt(); if( len == 0 ) return new ").append(s1).append('0').append(s2).append("; ");
cpf.append(cn).append(" ret = new ").append(s1).append("len").append(s2).append("; for(int i=0;i<len;i++){ ");
Builder<?> builder = null;
if( cc.isPrimitive() )
{
if( cc == boolean.class )
{
cwt.append("$2.writeBool(v[i]);");
cpf.append("ret[i] = $1.readBool();");
}
else if( cc == byte.class )
{
cwt.append("$2.writeByte(v[i]);");
cpf.append("ret[i] = $1.readByte();");
}
else if( cc == char.class )
{
cwt.append("$2.writeShort((short)v[i]);");
cpf.append("ret[i] = (char)$1.readShort();");
}
else if( cc == short.class )
{
cwt.append("$2.writeShort(v[i]);");
cpf.append("ret[i] = $1.readShort();");
}
else if( cc == int.class )
{
cwt.append("$2.writeInt(v[i]);");
cpf.append("ret[i] = $1.readInt();");
}
else if( cc == long.class )
{
cwt.append("$2.writeLong(v[i]);");
cpf.append("ret[i] = $1.readLong();");
}
else if( cc == float.class )
{
cwt.append("$2.writeFloat(v[i]);");
cpf.append("ret[i] = $1.readFloat();");
}
else if( cc == double.class )
{
cwt.append("$2.writeDouble(v[i]);");
cpf.append("ret[i] = $1.readDouble();");
}
}
else
{
builder = register(cc);
cwt.append("builder.writeTo(v[i], $2);");
cpf.append("ret[i] = (").append(ccn).append(")builder.parseFrom($1);");
}
cwt.append(" } }");
cpf.append(" } return ret; }");
ClassGenerator cg = ClassGenerator.newInstance(cl);
cg.setClassName(bcn);
cg.setSuperClass(Builder.class);
cg.addDefaultConstructor();
if( builder != null )
cg.addField("public static " + BUILDER_CLASS_NAME + " builder;");
cg.addMethod("public Class getType(){ return " + cn + ".class; }");
cg.addMethod(cwt.toString());
cg.addMethod(cpf.toString());
try
{
Class<?> wc = cg.toClass();
// set static field.
if( builder != null )
wc.getField("builder").set(null, builder);
return (Builder<?>)wc.newInstance();
}
catch(RuntimeException e)
{
throw e;
}
catch(Throwable e)
{
throw new RuntimeException(e.getMessage());
}
finally
{
cg.release();
}
}
private static Builder<?> newObjectBuilder(final Class<?> c)
{
if( c.isEnum() )
return newEnumBuilder(c);
if( c.isAnonymousClass() )
throw new RuntimeException("Can not instantiation anonymous class: " + c);
if( c.getEnclosingClass() != null && !Modifier.isStatic(c.getModifiers()) )
throw new RuntimeException("Can not instantiation inner and non-static class: " + c);
if( Throwable.class.isAssignableFrom(c) )
return SerializableBuilder;
ClassLoader cl = ClassHelper.getClassLoader(c);
// is same package.
boolean isp;
String cn = c.getName(), bcn;
if( c.getClassLoader() == null ) // is system class. if( cn.startsWith("java.") || cn.startsWith("javax.") || cn.startsWith("sun.") )
{
isp = false;
bcn = BUILDER_CLASS_NAME + "$bc" + BUILDER_CLASS_COUNTER.getAndIncrement();
}
else
{
isp = true;
bcn = cn + "$bc" + BUILDER_CLASS_COUNTER.getAndIncrement();
}
// is Collection, is Map, is Serializable.
boolean isc = Collection.class.isAssignableFrom(c);
boolean ism = !isc && Map.class.isAssignableFrom(c);
boolean iss = !( isc || ism ) && Serializable.class.isAssignableFrom(c);
// deal with fields.
String[] fns = null; // fix-order fields names
InputStream is = c.getResourceAsStream(c.getSimpleName() + FIELD_CONFIG_SUFFIX); // load field-config file.
if( is != null )
{
try
{
int len = is.available();
if( len > 0 )
{
if( len > MAX_FIELD_CONFIG_FILE_SIZE )
throw new RuntimeException("Load [" + c.getName() + "] field-config file error: File-size too larger");
String[] lines = IOUtils.readLines(is);
if( lines != null && lines.length > 0 )
{
List<String> list = new ArrayList<String>();
for(int i=0;i<lines.length;i++)
{
fns = lines[i].split(",");
Arrays.sort(fns, FNC);
for(int j=0;j<fns.length;j++)
list.add(fns[j]);
}
fns = list.toArray(new String[0]);
}
}
}
catch(IOException e)
{
throw new RuntimeException("Load [" + c.getName() + "] field-config file error: " + e.getMessage() );
}
finally
{
try{ is.close(); }
catch(IOException e){}
}
}
Field f, fs[];
if( fns != null )
{
fs = new Field[fns.length];
for(int i=0;i<fns.length;i++)
{
String fn = fns[i];
try
{
f = c.getDeclaredField(fn);
int mod = f.getModifiers();
if( Modifier.isStatic(mod) || (serializeIgnoreFinalModifier(c) && Modifier.isFinal(mod)) )
throw new RuntimeException("Field [" + c.getName() + "." + fn + "] is static/final field.");
if( Modifier.isTransient(mod) )
{
if( iss )
return SerializableBuilder;
throw new RuntimeException("Field [" + c.getName() + "." + fn + "] is transient field.");
}
f.setAccessible(true);
fs[i] = f;
}
catch(SecurityException e)
{
throw new RuntimeException(e.getMessage());
}
catch(NoSuchFieldException e)
{
throw new RuntimeException("Field [" + c.getName() + "." + fn + "] not found.");
}
}
}
else
{
Class<?> t = c;
List<Field> fl = new ArrayList<Field>();
do
{
fs = t.getDeclaredFields();
for( Field tf : fs )
{
int mod = tf.getModifiers();
if (Modifier.isStatic(mod)
|| (serializeIgnoreFinalModifier(c) && Modifier.isFinal(mod))
|| tf.getName().equals("this$0") // skip static or inner-class's 'this$0' field.
|| ! Modifier.isPublic(tf.getType().getModifiers()) ) //skip private inner-class field
continue;
if( Modifier.isTransient(mod) )
{
if( iss )
return SerializableBuilder;
continue;
}
tf.setAccessible(true);
fl.add(tf);
}
t = t.getSuperclass();
}
while( t != Object.class );
fs = fl.toArray(new Field[0]);
if( fs.length > 1 )
Arrays.sort(fs, FC);
}
// deal with constructors.
Constructor<?>[] cs = c.getDeclaredConstructors();
if( cs.length == 0 )
{
Class<?> t = c;
do
{
t = t.getSuperclass();
if( t == null )
throw new RuntimeException("Can not found Constructor?");
cs = c.getDeclaredConstructors();
}
while( cs.length == 0 );
}
if( cs.length > 1 )
Arrays.sort(cs, CC);
// writeObject code.
StringBuilder cwf = new StringBuilder("protected void writeObject(Object obj, ").append(GenericObjectOutput.class.getName()).append(" out) throws java.io.IOException{");
cwf.append(cn).append(" v = (").append(cn).append(")$1; ");
cwf.append("$2.writeInt(fields.length);");
// readObject code.
StringBuilder crf = new StringBuilder("protected void readObject(Object ret, ").append(GenericObjectInput.class.getName()).append(" in) throws java.io.IOException{");
crf.append("int fc = $2.readInt();");
crf.append("if( fc != ").append(fs.length).append(" ) throw new IllegalStateException(\"Deserialize Class [").append(cn).append("], field count not matched. Expect ").append(fs.length).append(" but get \" + fc +\".\");");
crf.append(cn).append(" ret = (").append(cn).append(")$1;");
// newInstance code.
StringBuilder cni = new StringBuilder("protected Object newInstance(").append(GenericObjectInput.class.getName()).append(" in){ return ");
Constructor<?> con = cs[0];
int mod = con.getModifiers();
boolean dn = Modifier.isPublic(mod) || ( isp && !Modifier.isPrivate(mod) );
if( dn )
{
cni.append("new ").append(cn).append("(");
}
else
{
con.setAccessible(true);
cni.append("constructor.newInstance(new Object[]{");
}
Class<?>[] pts = con.getParameterTypes();
for(int i=0;i<pts.length;i++)
{
if( i > 0 )
cni.append(',');
cni.append(defaultArg(pts[i]));
}
if( !dn )
cni.append("}"); // close object array.
cni.append("); }");
// get bean-style property metadata.
Map<String, PropertyMetadata> pms = propertyMetadatas(c);
List<Builder<?>> builders = new ArrayList<Builder<?>>(fs.length);
String fn, ftn; // field name, field type name.
Class<?> ft; // field type.
boolean da; // direct access.
PropertyMetadata pm;
for(int i=0;i<fs.length;i++)
{
f = fs[i];
fn = f.getName();
ft = f.getType();
ftn = ReflectUtils.getName(ft);
da = isp && ( f.getDeclaringClass() == c ) && ( Modifier.isPrivate(f.getModifiers()) == false );
if( da )
{
pm = null;
}
else
{
pm = pms.get(fn);
if( pm != null && ( pm.type != ft || pm.setter == null || pm.getter == null ) )
pm = null;
}
crf.append("if( fc == ").append(i).append(" ) return;");
if( ft.isPrimitive() )
{
if( ft == boolean.class )
{
if( da )
{
cwf.append("$2.writeBool(v.").append(fn).append(");");
crf.append("ret.").append(fn).append(" = $2.readBool();");
}
else if( pm != null )
{
cwf.append("$2.writeBool(v.").append(pm.getter).append("());");
crf.append("ret.").append(pm.setter).append("($2.readBool());");
}
else
{
cwf.append("$2.writeBool(((Boolean)fields[").append(i).append("].get($1)).booleanValue());");
crf.append("fields[").append(i).append("].set(ret, ($w)$2.readBool());");
}
}
else if( ft == byte.class )
{
if( da )
{
cwf.append("$2.writeByte(v.").append(fn).append(");");
crf.append("ret.").append(fn).append(" = $2.readByte();");
}
else if( pm != null )
{
cwf.append("$2.writeByte(v.").append(pm.getter).append("());");
crf.append("ret.").append(pm.setter).append("($2.readByte());");
}
else
{
cwf.append("$2.writeByte(((Byte)fields[").append(i).append("].get($1)).byteValue());");
crf.append("fields[").append(i).append("].set(ret, ($w)$2.readByte());");
}
}
else if( ft == char.class )
{
if( da )
{
cwf.append("$2.writeShort((short)v.").append(fn).append(");");
crf.append("ret.").append(fn).append(" = (char)$2.readShort();");
}
else if( pm != null )
{
cwf.append("$2.writeShort((short)v.").append(pm.getter).append("());");
crf.append("ret.").append(pm.setter).append("((char)$2.readShort());");
}
else
{
cwf.append("$2.writeShort((short)((Character)fields[").append(i).append("].get($1)).charValue());");
crf.append("fields[").append(i).append("].set(ret, ($w)((char)$2.readShort()));");
}
}
else if( ft == short.class )
{
if( da )
{
cwf.append("$2.writeShort(v.").append(fn).append(");");
crf.append("ret.").append(fn).append(" = $2.readShort();");
}
else if( pm != null )
{
cwf.append("$2.writeShort(v.").append(pm.getter).append("());");
crf.append("ret.").append(pm.setter).append("($2.readShort());");
}
else
{
cwf.append("$2.writeShort(((Short)fields[").append(i).append("].get($1)).shortValue());");
crf.append("fields[").append(i).append("].set(ret, ($w)$2.readShort());");
}
}
else if( ft == int.class )
{
if( da )
{
cwf.append("$2.writeInt(v.").append(fn).append(");");
crf.append("ret.").append(fn).append(" = $2.readInt();");
}
else if( pm != null )
{
cwf.append("$2.writeInt(v.").append(pm.getter).append("());");
crf.append("ret.").append(pm.setter).append("($2.readInt());");
}
else
{
cwf.append("$2.writeInt(((Integer)fields[").append(i).append("].get($1)).intValue());");
crf.append("fields[").append(i).append("].set(ret, ($w)$2.readInt());");
}
}
else if( ft == long.class )
{
if( da )
{
cwf.append("$2.writeLong(v.").append(fn).append(");");
crf.append("ret.").append(fn).append(" = $2.readLong();");
}
else if( pm != null )
{
cwf.append("$2.writeLong(v.").append(pm.getter).append("());");
crf.append("ret.").append(pm.setter).append("($2.readLong());");
}
else
{
cwf.append("$2.writeLong(((Long)fields[").append(i).append("].get($1)).longValue());");
crf.append("fields[").append(i).append("].set(ret, ($w)$2.readLong());");
}
}
else if( ft == float.class )
{
if( da )
{
cwf.append("$2.writeFloat(v.").append(fn).append(");");
crf.append("ret.").append(fn).append(" = $2.readFloat();");
}
else if( pm != null )
{
cwf.append("$2.writeFloat(v.").append(pm.getter).append("());");
crf.append("ret.").append(pm.setter).append("($2.readFloat());");
}
else
{
cwf.append("$2.writeFloat(((Float)fields[").append(i).append("].get($1)).floatValue());");
crf.append("fields[").append(i).append("].set(ret, ($w)$2.readFloat());");
}
}
else if( ft == double.class )
{
if( da )
{
cwf.append("$2.writeDouble(v.").append(fn).append(");");
crf.append("ret.").append(fn).append(" = $2.readDouble();");
}
else if( pm != null )
{
cwf.append("$2.writeDouble(v.").append(pm.getter).append("());");
crf.append("ret.").append(pm.setter).append("($2.readDouble());");
}
else
{
cwf.append("$2.writeDouble(((Double)fields[").append(i).append("].get($1)).doubleValue());");
crf.append("fields[").append(i).append("].set(ret, ($w)$2.readDouble());");
}
}
}
else if( ft == c )
{
if( da )
{
cwf.append("this.writeTo(v.").append(fn).append(", $2);");
crf.append("ret.").append(fn).append(" = (").append(ftn).append(")this.parseFrom($2);");
}
else if( pm != null )
{
cwf.append("this.writeTo(v.").append(pm.getter).append("(), $2);");
crf.append("ret.").append(pm.setter).append("((").append(ftn).append(")this.parseFrom($2));");
}
else
{
cwf.append("this.writeTo((").append(ftn).append(")fields[").append(i).append("].get($1), $2);");
crf.append("fields[").append(i).append("].set(ret, this.parseFrom($2));");
}
}
else
{
int bc = builders.size();
builders.add( register(ft) );
if( da )
{
cwf.append("builders[").append(bc).append("].writeTo(v.").append(fn).append(", $2);");
crf.append("ret.").append(fn).append(" = (").append(ftn).append(")builders[").append(bc).append("].parseFrom($2);");
}
else if( pm != null )
{
cwf.append("builders[").append(bc).append("].writeTo(v.").append(pm.getter).append("(), $2);");
crf.append("ret.").append(pm.setter).append("((").append(ftn).append(")builders[").append(bc).append("].parseFrom($2));");
}
else
{
cwf.append("builders[").append(bc).append("].writeTo((").append(ftn).append(")fields[").append(i).append("].get($1), $2);");
crf.append("fields[").append(i).append("].set(ret, builders[").append(bc).append("].parseFrom($2));");
}
}
}
// skip any fields.
crf.append("for(int i=").append(fs.length).append(";i<fc;i++) $2.skipAny();");
// collection or map
if( isc )
{
cwf.append("$2.writeInt(v.size()); for(java.util.Iterator it=v.iterator();it.hasNext();){ $2.writeObject(it.next()); }");
crf.append("int len = $2.readInt(); for(int i=0;i<len;i++) ret.add($2.readObject());");
}
else if( ism )
{
cwf.append("$2.writeInt(v.size()); for(java.util.Iterator it=v.entrySet().iterator();it.hasNext();){ java.util.Map.Entry entry = (java.util.Map.Entry)it.next(); $2.writeObject(entry.getKey()); $2.writeObject(entry.getValue()); }");
crf.append("int len = $2.readInt(); for(int i=0;i<len;i++) ret.put($2.readObject(), $2.readObject());");
}
cwf.append(" }");
crf.append(" }");
ClassGenerator cg = ClassGenerator.newInstance(cl);
cg.setClassName(bcn);
cg.setSuperClass(AbstractObjectBuilder.class);
cg.addDefaultConstructor();
cg.addField("public static java.lang.reflect.Field[] fields;");
cg.addField("public static " + BUILDER_CLASS_NAME + "[] builders;");
if( !dn )
cg.addField("public static java.lang.reflect.Constructor constructor;");
cg.addMethod("public Class getType(){ return " + cn + ".class; }");
cg.addMethod(cwf.toString());
cg.addMethod(crf.toString());
cg.addMethod(cni.toString());
try
{
Class<?> wc = cg.toClass();
// set static field
wc.getField("fields").set(null, fs);
wc.getField("builders").set(null, builders.toArray(new Builder<?>[0]));
if( !dn )
wc.getField("constructor").set(null, con);
return (Builder<?>)wc.newInstance();
}
catch(RuntimeException e)
{
throw e;
}
catch(Throwable e)
{
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
finally
{
cg.release();
}
}
private static Builder<?> newEnumBuilder(Class<?> c)
{
ClassLoader cl = ClassHelper.getClassLoader(c);
String cn = c.getName();
String bcn = BUILDER_CLASS_NAME + "$bc" + BUILDER_CLASS_COUNTER.getAndIncrement();
StringBuilder cwt = new StringBuilder("public void writeTo(Object obj, ").append(GenericObjectOutput.class.getName()).append(" out) throws java.io.IOException{"); // writeTo code.
cwt.append(cn).append(" v = (").append(cn).append(")$1;");
cwt.append("if( $1 == null ){ $2.writeUTF(null); }else{ $2.writeUTF(v.name()); } }");
StringBuilder cpf = new StringBuilder("public Object parseFrom(").append(GenericObjectInput.class.getName()).append(" in) throws java.io.IOException{"); // parseFrom code.
cpf.append("String name = $1.readUTF(); if( name == null ) return null; return (").append(cn).append(")Enum.valueOf(").append(cn).append(".class, name); }");
ClassGenerator cg = ClassGenerator.newInstance(cl);
cg.setClassName(bcn);
cg.setSuperClass(Builder.class);
cg.addDefaultConstructor();
cg.addMethod("public Class getType(){ return " + cn + ".class; }");
cg.addMethod(cwt.toString());
cg.addMethod(cpf.toString());
try
{
Class<?> wc = cg.toClass();
return (Builder<?>)wc.newInstance();
}
catch(RuntimeException e)
{
throw e;
}
catch(Throwable e)
{
throw new RuntimeException(e.getMessage(), e);
}
finally
{
cg.release();
}
}
private static Map<String, PropertyMetadata> propertyMetadatas(Class<?> c)
{
Map<String, Method> mm = new HashMap<String, Method>(); // method map.
Map<String, PropertyMetadata> ret = new HashMap<String, PropertyMetadata>(); // property metadata map.
// All public method.
for( Method m : c.getMethods() )
{
if( m.getDeclaringClass() == Object.class ) // Ignore Object's method.
continue;
mm.put(ReflectUtils.getDesc(m), m);
}
Matcher matcher;
for( Map.Entry<String,Method> entry : mm.entrySet() )
{
String desc = entry.getKey();
Method method = entry.getValue();
if( ( matcher = ReflectUtils.GETTER_METHOD_DESC_PATTERN.matcher(desc) ).matches() ||
( matcher = ReflectUtils.IS_HAS_CAN_METHOD_DESC_PATTERN.matcher(desc) ).matches() )
{
String pn = propertyName(matcher.group(1));
Class<?> pt = method.getReturnType();
PropertyMetadata pm = ret.get(pn);
if( pm == null )
{
pm = new PropertyMetadata();
pm.type = pt;
ret.put(pn, pm);
}
else
{
if( pm.type != pt )
continue;
}
pm.getter = method.getName();
}
else if( ( matcher = ReflectUtils.SETTER_METHOD_DESC_PATTERN.matcher(desc) ).matches() )
{
String pn = propertyName(matcher.group(1));
Class<?> pt = method.getParameterTypes()[0];
PropertyMetadata pm = ret.get(pn);
if( pm == null )
{
pm = new PropertyMetadata();
pm.type = pt;
ret.put(pn, pm);
}
else
{
if( pm.type != pt )
continue;
}
pm.setter = method.getName();
}
}
return ret;
}
private static String propertyName(String s)
{
return s.length() == 1 || Character.isLowerCase(s.charAt(1)) ? Character.toLowerCase(s.charAt(0)) + s.substring(1) : s;
}
private static boolean serializeIgnoreFinalModifier(Class cl)
{
// if (cl.isAssignableFrom(BigInteger.class)) return false;
// for performance
// if (cl.getName().startsWith("java")) return true;
// if (cl.getName().startsWith("javax")) return true;
return false;
}
@SuppressWarnings("unused")
private static boolean isPrimitiveOrPrimitiveArray1(Class<?> cl)
{
if (cl.isPrimitive()){
return true;
} else {
Class clazz = cl.getClass().getComponentType();
if (clazz!=null && clazz.isPrimitive()){
return true;
}
}
return false;
}
private static String defaultArg(Class<?> cl)
{
if( boolean.class == cl ) return "false";
if( int.class == cl ) return "0";
if( long.class == cl ) return "0l";
if( double.class == cl ) return "(double)0";
if( float.class == cl ) return "(float)0";
if( short.class == cl ) return "(short)0";
if( char.class == cl ) return "(char)0";
if( byte.class == cl ) return "(byte)0";
if( byte[].class == cl ) return "new byte[]{0}";
if( !cl.isPrimitive() ) return "null";
throw new UnsupportedOperationException();
}
private static int compareFieldName(String n1, String n2)
{
int l = Math.min(n1.length(), n2.length());
for(int i=0;i<l;i++)
{
int t = n1.charAt(i) - n2.charAt(i);
if( t != 0 )
return t;
}
return n1.length() - n2.length();
}
private static void addDesc(Class<?> c)
{
String desc = ReflectUtils.getDesc(c);
int index = mDescList.size();
mDescList.add(desc);
mDescMap.put(desc, index);
}
static class PropertyMetadata
{
Class<?> type;
String setter, getter;
}
public static abstract class AbstractObjectBuilder<T> extends Builder<T>
{
abstract public Class<T> getType();
public void writeTo(T obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
int ref = out.getRef(obj);
if( ref < 0 )
{
out.addRef(obj);
out.write0(OBJECT);
writeObject(obj, out);
}
else
{
out.write0(OBJECT_REF);
out.writeUInt(ref);
}
}
}
public T parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
switch( b )
{
case OBJECT:
{
T ret = newInstance(in);
in.addRef(ret);
readObject(ret, in);
return ret;
}
case OBJECT_REF:
return (T)in.getRef(in.readUInt());
case OBJECT_NULL:
return null;
default:
throw new IOException("Input format error, expect OBJECT|OBJECT_REF|OBJECT_NULL, get " + b);
}
}
abstract protected void writeObject(T obj, GenericObjectOutput out) throws IOException;
abstract protected T newInstance(GenericObjectInput in) throws IOException;
abstract protected void readObject(T ret, GenericObjectInput in) throws IOException;
}
static final Builder<Object> GenericBuilder = new Builder<Object>(){
@Override
public Class<Object> getType(){ return Object.class; }
@Override
public void writeTo(Object obj, GenericObjectOutput out) throws IOException{ out.writeObject(obj); }
@Override
public Object parseFrom(GenericObjectInput in) throws IOException{ return in.readObject(); }
};
static final Builder<Object[]> GenericArrayBuilder = new AbstractObjectBuilder<Object[]>(){
@Override
public Class<Object[]> getType(){ return Object[].class; }
@Override
protected Object[] newInstance(GenericObjectInput in) throws IOException
{
return new Object[in.readUInt()];
}
@Override
protected void readObject(Object[] ret, GenericObjectInput in) throws IOException
{
for(int i=0;i<ret.length;i++)
ret[i] = in.readObject();
}
@Override
protected void writeObject(Object[] obj, GenericObjectOutput out) throws IOException
{
out.writeUInt(obj.length);
for( Object item : obj )
out.writeObject(item);
}
};
static final Builder<Serializable> SerializableBuilder = new Builder<Serializable>(){
@Override
public Class<Serializable> getType()
{
return Serializable.class;
}
@Override
public void writeTo(Serializable obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_STREAM);
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
CompactedObjectOutputStream oos = new CompactedObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bos.close();
byte[] b = bos.toByteArray();
out.writeUInt(b.length);
out.write0(b, 0, b.length);
}
}
@Override
public Serializable parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_STREAM )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_STREAM, get " + b + ".");
UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(in.read0(in.readUInt()));
CompactedObjectInputStream ois = new CompactedObjectInputStream(bis);
try{ return (Serializable)ois.readObject(); }
catch(ClassNotFoundException e){ throw new IOException(StringUtils.toString(e)); }
}
};
static
{
addDesc(boolean[].class);
addDesc(byte[].class);
addDesc(char[].class);
addDesc(short[].class);
addDesc(int[].class);
addDesc(long[].class);
addDesc(float[].class);
addDesc(double[].class);
addDesc(Boolean.class);
addDesc(Byte.class);
addDesc(Character.class);
addDesc(Short.class);
addDesc(Integer.class);
addDesc(Long.class);
addDesc(Float.class);
addDesc(Double.class);
addDesc(String.class);
addDesc(String[].class);
addDesc(ArrayList.class);
addDesc(HashMap.class);
addDesc(HashSet.class);
addDesc(Date.class);
addDesc(java.sql.Date.class);
addDesc(java.sql.Time.class);
addDesc(java.sql.Timestamp.class);
addDesc(java.util.LinkedList.class);
addDesc(java.util.LinkedHashMap.class);
addDesc(java.util.LinkedHashSet.class);
register(byte[].class, new Builder<byte[]>(){
@Override
public Class<byte[]> getType(){ return byte[].class; }
@Override
public void writeTo(byte[] obj, GenericObjectOutput out) throws IOException{ out.writeBytes(obj); }
@Override
public byte[] parseFrom(GenericObjectInput in) throws IOException{ return in.readBytes(); }
});
register(Boolean.class, new Builder<Boolean>(){
@Override
public Class<Boolean> getType(){ return Boolean.class; }
@Override
public void writeTo(Boolean obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
out.write0(VARINT_N1);
else if( obj.booleanValue() )
out.write0(VARINT_1);
else
out.write0(VARINT_0);
}
@Override
public Boolean parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
switch( b )
{
case VARINT_N1: return null;
case VARINT_0: return Boolean.FALSE;
case VARINT_1: return Boolean.TRUE;
default: throw new IOException("Input format error, expect VARINT_N1|VARINT_0|VARINT_1, get " + b + ".");
}
}
});
register(Byte.class, new Builder<Byte>(){
@Override
public Class<Byte> getType(){ return Byte.class; }
@Override
public void writeTo(Byte obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeByte(obj.byteValue());
}
}
@Override
public Byte parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return Byte.valueOf(in.readByte());
}
});
register(Character.class, new Builder<Character>(){
@Override
public Class<Character> getType(){ return Character.class; }
@Override
public void writeTo(Character obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeShort((short)obj.charValue());
}
}
@Override
public Character parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return Character.valueOf((char)in.readShort());
}
});
register(Short.class, new Builder<Short>(){
@Override
public Class<Short> getType(){ return Short.class; }
@Override
public void writeTo(Short obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeShort(obj.shortValue());
}
}
@Override
public Short parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return Short.valueOf(in.readShort());
}
});
register(Integer.class, new Builder<Integer>(){
@Override
public Class<Integer> getType(){ return Integer.class; }
@Override
public void writeTo(Integer obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeInt(obj.intValue());
}
}
@Override
public Integer parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return Integer.valueOf(in.readInt());
}
});
register(Long.class, new Builder<Long>(){
@Override
public Class<Long> getType(){ return Long.class; }
@Override
public void writeTo(Long obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeLong(obj.longValue());
}
}
@Override
public Long parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return Long.valueOf(in.readLong());
}
});
register(Float.class, new Builder<Float>(){
@Override
public Class<Float> getType(){ return Float.class; }
@Override
public void writeTo(Float obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeFloat(obj.floatValue());
}
}
@Override
public Float parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return new Float(in.readFloat());
}
});
register(Double.class, new Builder<Double>(){
@Override
public Class<Double> getType(){ return Double.class; }
@Override
public void writeTo(Double obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeDouble(obj.doubleValue());
}
}
@Override
public Double parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return new Double(in.readDouble());
}
});
register(String.class, new Builder<String>(){
@Override
public Class<String> getType(){ return String.class; }
@Override
public String parseFrom(GenericObjectInput in) throws IOException{ return in.readUTF(); }
@Override
public void writeTo(String obj, GenericObjectOutput out) throws IOException{ out.writeUTF(obj); }
});
register(StringBuilder.class, new Builder<StringBuilder>(){
@Override
public Class<StringBuilder> getType(){ return StringBuilder.class; }
@Override
public StringBuilder parseFrom(GenericObjectInput in) throws IOException{ return new StringBuilder(in.readUTF()); }
@Override
public void writeTo(StringBuilder obj, GenericObjectOutput out) throws IOException{ out.writeUTF(obj.toString()); }
});
register(StringBuffer.class, new Builder<StringBuffer>(){
@Override
public Class<StringBuffer> getType(){ return StringBuffer.class; }
@Override
public StringBuffer parseFrom(GenericObjectInput in) throws IOException{ return new StringBuffer(in.readUTF()); }
@Override
public void writeTo(StringBuffer obj, GenericObjectOutput out) throws IOException{ out.writeUTF(obj.toString()); }
});
// java.util
register(ArrayList.class, new Builder<ArrayList>(){
@Override
public Class<ArrayList> getType(){ return ArrayList.class; }
@Override
public void writeTo(ArrayList obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUES);
out.writeUInt(obj.size());
for( Object item : obj )
out.writeObject(item);
}
}
@Override
public ArrayList parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUES )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUES, get " + b + ".");
int len = in.readUInt();
ArrayList ret = new ArrayList(len);
for(int i=0;i<len;i++)
ret.add(in.readObject());
return ret;
}
});
register(HashMap.class, new Builder<HashMap>(){
@Override
public Class<HashMap> getType(){ return HashMap.class; }
@Override
public void writeTo(HashMap obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_MAP);
out.writeUInt(obj.size());
for( Map.Entry entry : (Set<Map.Entry>)obj.entrySet() )
{
out.writeObject(entry.getKey());
out.writeObject(entry.getValue());
}
}
}
@Override
public HashMap parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_MAP )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_MAP, get " + b + ".");
int len = in.readUInt();
HashMap ret = new HashMap(len);
for(int i=0;i<len;i++)
ret.put(in.readObject(), in.readObject());
return ret;
}
});
register(HashSet.class, new Builder<HashSet>(){
@Override
public Class<HashSet> getType(){ return HashSet.class; }
@Override
public void writeTo(HashSet obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUES);
out.writeUInt(obj.size());
for( Object item : obj )
out.writeObject(item);
}
}
@Override
public HashSet parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUES )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUES, get " + b + ".");
int len = in.readUInt();
HashSet ret = new HashSet(len);
for(int i=0;i<len;i++)
ret.add(in.readObject());
return ret;
}
});
register(Date.class, new Builder<Date>(){
@Override
public Class<Date> getType(){ return Date.class; }
@Override
public void writeTo(Date obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeLong(obj.getTime());
}
}
@Override
public Date parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return new Date(in.readLong());
}
});
// java.sql
register(java.sql.Date.class, new Builder<java.sql.Date>(){
@Override
public Class<java.sql.Date> getType(){ return java.sql.Date.class; }
@Override
public void writeTo(java.sql.Date obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeLong(obj.getTime());
}
}
@Override
public java.sql.Date parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return new java.sql.Date(in.readLong());
}
});
register(java.sql.Timestamp.class, new Builder<java.sql.Timestamp>(){
@Override
public Class<java.sql.Timestamp> getType(){ return java.sql.Timestamp.class; }
@Override
public void writeTo(java.sql.Timestamp obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeLong(obj.getTime());
}
}
@Override
public java.sql.Timestamp parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return new java.sql.Timestamp(in.readLong());
}
});
register(java.sql.Time.class, new Builder<java.sql.Time>(){
@Override
public Class<java.sql.Time> getType(){ return java.sql.Time.class; }
@Override
public void writeTo(java.sql.Time obj, GenericObjectOutput out) throws IOException
{
if( obj == null )
{
out.write0(OBJECT_NULL);
}
else
{
out.write0(OBJECT_VALUE);
out.writeLong(obj.getTime());
}
}
@Override
public java.sql.Time parseFrom(GenericObjectInput in) throws IOException
{
byte b = in.read0();
if( b == OBJECT_NULL )
return null;
if( b != OBJECT_VALUE )
throw new IOException("Input format error, expect OBJECT_NULL|OBJECT_VALUE, get " + b + ".");
return new java.sql.Time(in.readLong());
}
});
}
}
| |
/**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.core.gui.components.form.flexible.impl.elements.richText;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.controllers.linkchooser.CustomLinkTreeModel;
import org.olat.core.dispatcher.impl.StaticMediaDispatcher;
import org.olat.core.dispatcher.mapper.Mapper;
import org.olat.core.dispatcher.mapper.MapperService;
import org.olat.core.gui.components.form.flexible.impl.elements.richText.plugins.TinyMCECustomPlugin;
import org.olat.core.gui.components.form.flexible.impl.elements.richText.plugins.TinyMCECustomPluginFactory;
import org.olat.core.gui.control.Disposable;
import org.olat.core.gui.render.StringOutput;
import org.olat.core.gui.themes.Theme;
import org.olat.core.helpers.Settings;
import org.olat.core.logging.OLog;
import org.olat.core.logging.Tracing;
import org.olat.core.util.Formatter;
import org.olat.core.util.UserSession;
import org.olat.core.util.WebappHelper;
import org.olat.core.util.i18n.I18nManager;
import org.olat.core.util.vfs.LocalFolderImpl;
import org.olat.core.util.vfs.VFSContainer;
import org.olat.core.util.vfs.VFSContainerMapper;
import org.olat.core.util.vfs.VFSManager;
/**
* Description:<br>
*
* This configuration object is used to configure the features of the TinyMCE
* HTML editor. Use the addXYZConfiguration() methods to add some default
* settings. You can also manually tweak the configuration, make sure you
* understand how Tiny works. See http://wiki.moxiecode.com for more information
*
* <P>
* Initial Date: 21.04.2009 <br>
*
* @author gnaegi
*/
public class RichTextConfiguration implements Disposable {
private static final OLog log = Tracing.createLoggerFor(RichTextConfiguration.class);
private static final String MODE = "mode";
private static final String MODE_VALUE_EXACT = "exact";
private static final String ELEMENTS = "elements";
// Doctype and language
private static final String LANGUAGE = "language";
// Layout and theme
private static final String CONTENT_CSS = "content_css";
private static final String CONVERT_URLS = "convert_urls";
private static final String IMPORTCSS_APPEND = "importcss_append";
private static final String IMPORT_SELECTOR_CONVERTER = "importcss_selector_converter";
private static final String IMPORT_SELECTOR_CONVERTER_VALUE_REMOVE_EMOTICONS ="function(selector) { if (selector.indexOf('img.b_emoticons') != -1) {return false;} else { return this.convertSelectorToFormat(selector); }}";
private static final String IMPORTCSS_GROUPS = "importcss_groups";
private static final String IMPORTCSS_GROUPS_VALUE_MENU = "[{title: 'Paragraph', filter: /^(p)\\./},{title: 'Div', filter: /^(div|p)\\./},{title: 'Table', filter: /^(table|th|td|tr)\\./},{title: 'Url', filter: /^(a)\\./},{title: 'Style'}]";
private static final String HEIGHT = "height";
// Window appearance
private static final String DIALOG_TYPE = "dialog_type";
private static final String DIALOG_TYPE_VALUE_MODAL = "modal";
// Non-Editable plugin
private static final String NONEDITABLE_NONEDITABLE_CLASS = "noneditable_noneditable_class";
private static final String NONEDITABLE_NONEDITABLE_CLASS_VALUE_MCENONEDITABLE = "mceNonEditable";
// Fullscreen plugin
private static final String FULLSCREEN_NEW_WINDOW = "fullscreen_new_window";
// Other plugins
private static final String TABFOCUS_SETTINGS = "tabfocus_elements";
private static final String TABFOCUS_SETTINGS_PREV_NEXT = ":prev,:next";
// Valid elements
private static final String EXTENDED_VALID_ELEMENTS = "extended_valid_elements";
private static final String EXTENDED_VALID_ELEMENTS_VALUE_FULL = "script[src,type,defer],form[*],input[*],a[*],p[*],#comment[*],img[*],iframe[*],map[*],area[*]";
private static final String INVALID_ELEMENTS = "invalid_elements";
private static final String INVALID_ELEMENTS_FORM_MINIMALISTIC_VALUE_UNSAVE = "iframe,script,@[on*],object,embed";
private static final String INVALID_ELEMENTS_FORM_SIMPLE_VALUE_UNSAVE = "iframe,script,@[on*],object,embed";
private static final String INVALID_ELEMENTS_FORM_FULL_VALUE_UNSAVE = "iframe,script,@[on*]";
public static final String INVALID_ELEMENTS_FORM_FULL_VALUE_UNSAVE_WITH_SCRIPT = "iframe,@[on*]";
private static final String INVALID_ELEMENTS_FILE_FULL_VALUE_UNSAVE = "";
// Other optional configurations, optional
private static final String FORCED_ROOT_BLOCK = "forced_root_block";
private static final String FORCED_ROOT_BLOCK_VALUE_NOROOT = "";
private static final String DOCUMENT_BASE_URL = "document_base_url";
private static final String PASTE_DATA_IMAGES = "paste_data_images";
//
// Generic boolean true / false values
private static final String VALUE_FALSE = "false";
// Callbacks
private static final String ONCHANGE_CALLBACK = "onchange_callback";
private static final String ONCHANGE_CALLBACK_VALUE_TEXT_AREA_ON_CHANGE = "BTinyHelper.triggerOnChangeOnFormElement";
private static final String FILE_BROWSER_CALLBACK = "file_browser_callback";
private static final String FILE_BROWSER_CALLBACK_VALUE_LINK_BROWSER = "BTinyHelper.openLinkBrowser";
private static final String ONINIT_CALLBACK_VALUE_START_DIRTY_OBSERVER = "BTinyHelper.startFormDirtyObserver";
private static final String URLCONVERTER_CALLBACK = "urlconverter_callback";
private static final String URLCONVERTER_CALLBACK_VALUE_BRASATO_URL_CONVERTER = "BTinyHelper.linkConverter";
private Map<String, String> quotedConfigValues = new HashMap<String, String>();
private Map<String, String> nonQuotedConfigValues = new HashMap<String, String>();
private List<String> oninit = new ArrayList<String>();
// Supported image and media suffixes
private static final String[] IMAGE_SUFFIXES_VALUES = { "jpg", "gif", "jpeg", "png" };
private static final String[] MEDIA_SUFFIXES_VALUES = { "swf", "dcr", "mov", "qt", "mpg", "mp3", "mp4", "mpeg", "avi", "wmv", "wm", "asf",
"asx", "wmx", "wvx", "rm", "ra", "ram" };
private static final String[] FLASH_PLAYER_SUFFIXES_VALUES = {"flv","f4v","mp3","mp4","aac","m4v","m4a"};
private String[] linkBrowserImageSuffixes;
private String[] linkBrowserMediaSuffixes;
private String[] linkBrowserFlashPlayerSuffixes;
private VFSContainer linkBrowserBaseContainer;
private String linkBrowserUploadRelPath;
private String linkBrowserRelativeFilePath;
private CustomLinkTreeModel linkBrowserCustomTreeModel;
// DOM ID of the flexi form element
private String domID;
private Mapper contentMapper;
private TinyConfig tinyConfig;
/**
* Constructor, only used by RichText element itself. Use
* richtTextElement.getEditorConfiguration() to acess this object
*
* @param domID The ID of the flexi element in the browser DOM
* @param rootFormDispatchId The dispatch ID of the root form that deals with the submit button
*/
RichTextConfiguration(String domID, String rootFormDispatchId) {
this.domID = domID;
// use exact mode that only applies to this DOM element
setQuotedConfigValue(MODE, MODE_VALUE_EXACT);
setQuotedConfigValue(ELEMENTS, domID);
// set the on change handler to delegate to flexi element on change handler
setQuotedConfigValue(ONCHANGE_CALLBACK, ONCHANGE_CALLBACK_VALUE_TEXT_AREA_ON_CHANGE);
// set custom url converter to deal with framework and content urls properly
setNonQuotedConfigValue(URLCONVERTER_CALLBACK, URLCONVERTER_CALLBACK_VALUE_BRASATO_URL_CONVERTER);
setNonQuotedConfigValue("allow_script_urls", "true");
// use modal windows, all OLAT workflows are implemented to work this way
setModalWindowsEnabled(true, true);
// Start observing of diry richt text element and trigger calling of setFlexiFormDirty() method
// This check is initialized after the editor has fully loaded
addOnInitCallbackFunction(ONINIT_CALLBACK_VALUE_START_DIRTY_OBSERVER + "('" + rootFormDispatchId + "','" + domID + "')");
addOnInitCallbackFunction("tinyMCE.get('" + domID + "').focus()");
}
/**
* Method to add the standard configuration for the form based minimal
* editor
*
* @param usess
* @param externalToolbar
* @param guiTheme
*/
public void setConfigProfileFormEditorMinimalistic(UserSession usess, Theme guiTheme) {
setConfigBasics(usess, guiTheme);
// Add additional plugins
TinyMCECustomPluginFactory customPluginFactory = CoreSpringFactory.getImpl(TinyMCECustomPluginFactory.class);
List<TinyMCECustomPlugin> enabledCustomPlugins = customPluginFactory.getCustomPlugionsForProfile();
for (TinyMCECustomPlugin tinyMCECustomPlugin : enabledCustomPlugins) {
setCustomPluginEnabled(tinyMCECustomPlugin);
}
// Don't allow javascript or iframes
setQuotedConfigValue(INVALID_ELEMENTS, INVALID_ELEMENTS_FORM_MINIMALISTIC_VALUE_UNSAVE);
tinyConfig = TinyConfig.minimalisticConfig;
}
/**
* Method to add the standard configuration for the form based simple and
* full editor
*
* @param fullProfile
* true: use full profile; false: use simple profile
* @param usess
* @param externalToolbar
* @param guiTheme
* @param baseContainer
* @param customLinkTreeModel
*/
public void setConfigProfileFormEditor(boolean fullProfile, UserSession usess, Theme guiTheme, VFSContainer baseContainer, CustomLinkTreeModel customLinkTreeModel) {
setConfigBasics(usess, guiTheme);
TinyMCECustomPluginFactory customPluginFactory = CoreSpringFactory.getImpl(TinyMCECustomPluginFactory.class);
List<TinyMCECustomPlugin> enabledCustomPlugins = customPluginFactory.getCustomPlugionsForProfile();
for (TinyMCECustomPlugin tinyMCECustomPlugin : enabledCustomPlugins) {
setCustomPluginEnabled(tinyMCECustomPlugin);
}
if (fullProfile) {
// Don't allow javascript or iframes
setQuotedConfigValue(INVALID_ELEMENTS, INVALID_ELEMENTS_FORM_FULL_VALUE_UNSAVE);
tinyConfig = TinyConfig.editorFullConfig;
} else {
// Don't allow javascript or iframes, if the file browser is there allow also media elements (the full values)
setQuotedConfigValue(INVALID_ELEMENTS, (baseContainer == null ? INVALID_ELEMENTS_FORM_SIMPLE_VALUE_UNSAVE : INVALID_ELEMENTS_FORM_FULL_VALUE_UNSAVE));
tinyConfig = TinyConfig.editorConfig;
}
// Setup file and link browser
if (baseContainer != null) {
tinyConfig = tinyConfig.enableImageAndMedia();
setFileBrowserCallback(baseContainer, customLinkTreeModel, IMAGE_SUFFIXES_VALUES, MEDIA_SUFFIXES_VALUES, FLASH_PLAYER_SUFFIXES_VALUES);
// since in form editor mode and not in file mode we use null as relFilePath
setDocumentMediaBase(baseContainer, null, usess);
}
}
/**
* Method to add the standard configuration for the file based full editor
*
* @param usess
* @param externalToolbar
* @param guiTheme
* @param baseContainer
* @param relFilePath
* @param customLinkTreeModel
*/
public void setConfigProfileFileEditor(UserSession usess, Theme guiTheme, VFSContainer baseContainer, String relFilePath, CustomLinkTreeModel customLinkTreeModel) {
setConfigBasics(usess, guiTheme);
// Line 1
setFullscreenEnabled(true, false, 3);
setInsertDateTimeEnabled(true, usess.getLocale(), 3);
// Plugins without buttons
setNoneditableContentEnabled(true, null);
TinyMCECustomPluginFactory customPluginFactory = CoreSpringFactory.getImpl(TinyMCECustomPluginFactory.class);
List<TinyMCECustomPlugin> enabledCustomPlugins = customPluginFactory.getCustomPlugionsForProfile();
for (TinyMCECustomPlugin tinyMCECustomPlugin : enabledCustomPlugins) {
setCustomPluginEnabled(tinyMCECustomPlugin);
}
// Allow editing of all kind of HTML elements and attributes
setQuotedConfigValue(EXTENDED_VALID_ELEMENTS, EXTENDED_VALID_ELEMENTS_VALUE_FULL);
setQuotedConfigValue(INVALID_ELEMENTS, INVALID_ELEMENTS_FILE_FULL_VALUE_UNSAVE);
setNonQuotedConfigValue(PASTE_DATA_IMAGES, "true");
// Setup file and link browser
if (baseContainer != null) {
setFileBrowserCallback(baseContainer, customLinkTreeModel, IMAGE_SUFFIXES_VALUES, MEDIA_SUFFIXES_VALUES, FLASH_PLAYER_SUFFIXES_VALUES);
setDocumentMediaBase(baseContainer, relFilePath, usess);
}
tinyConfig = TinyConfig.fileEditorConfig;
}
/**
* Internal helper to generate the common configurations which are used by
* each profile
*
* @param usess
* @param externalToolbar
* @param guiTheme
*/
private void setConfigBasics(UserSession usess, Theme guiTheme) {
// Use users current language
Locale loc = I18nManager.getInstance().getCurrentThreadLocale();
setLanguage(loc);
// Use theme content css
setContentCSSFromTheme(guiTheme);
// Plugins without buttons
setNoneditableContentEnabled(true, null);
setTabFocusEnabled(true);
}
/**
* Add a function name that has to be executed after initialization. <br>
* E.g: myFunctionName, (alert('loading successfull')) <br>
* Don't add something like this: function() {alert('loading successfull')},
* use the following notation instead: (alert('loading successfull'))
*
* @param functionName
*/
public void addOnInitCallbackFunction(String functionName) {
if(functionName != null) {
oninit.add(functionName);
}
}
protected List<String> getOnInit() {
return oninit;
}
/**
* Enable the tabfocus plugin
*
* if enabled its possible to enter/leave the tinyMCE-editor with TAB-key.
* drawback is, that you cannot enter tabs in the editor itself or navigate over buttons!
* see http://bugs.olat.org/jira/browse/OLAT-6242
* @param tabFocusEnabled
*/
private void setTabFocusEnabled(boolean tabFocusEnabled){
if (tabFocusEnabled){
setQuotedConfigValue(TABFOCUS_SETTINGS, TABFOCUS_SETTINGS_PREV_NEXT);
}
}
/**
* Configure the tinymce windowing system
*
* @param modalWindowsEnabled
* true: use modal windows; false: use non-modal windows
* @param inlinePopupsEnabled
* true: use inline popups; false: use browser window popup
* windows
*/
private void setModalWindowsEnabled(boolean modalWindowsEnabled, boolean inlinePopupsEnabled) {
// in both cases opt in, default values are set to non-inline windows that
// are not modal
if (modalWindowsEnabled) {
setQuotedConfigValue(DIALOG_TYPE, DIALOG_TYPE_VALUE_MODAL);
}
}
/**
* Set the language for editor interface. If no translation can be found,
* the system fallbacks to EN
*
* @param loc
*/
private void setLanguage(Locale loc) {
// tiny does not support country or variant codes, only language code
String langKey = loc.getLanguage();
String path = "/static/js/tinymce4/tinymce/langs/" + langKey + ".js";
String realPath = WebappHelper.getContextRealPath(path);
if(realPath == null || !(new File(realPath).exists())) {
langKey = "en";
}
setQuotedConfigValue(LANGUAGE, langKey);
}
/**
* Enable or disable areas in the editor content that can't be modified at
* all. The areas are identified with the nonEditableCSSClass.
*
* @param noneditableContentEnabled
* true: use non-editable areas; false: all areas are editable
* @param nonEditableCSSClass
* the class that identifies the non-editable fields or NULL to
* use the default value 'mceNonEditable'
*/
private void setNoneditableContentEnabled(boolean noneditableContentEnabled, String nonEditableCSSClass) {
if (noneditableContentEnabled) {
if (nonEditableCSSClass != null && !nonEditableCSSClass.equals(NONEDITABLE_NONEDITABLE_CLASS_VALUE_MCENONEDITABLE)) {
// Add non editable class but only when it differs from the default name
setQuotedConfigValue(NONEDITABLE_NONEDITABLE_CLASS, nonEditableCSSClass);
}
}
}
public void disableMedia() {
tinyConfig = tinyConfig.disableMedia();
}
public void disableMathEditor() {
tinyConfig = tinyConfig.disableMathEditor();
}
/**
* Enable / disable the full-screen plugin
*
* @param fullScreenEnabled
* true: plugin enabled; false: plugin disabled
* @param inNewWindowEnabled
* true: fullscreen opens in new window; false: fullscreen opens
* in same window.
* @param row
* The row where to place the plugin buttons
*/
private void setFullscreenEnabled(boolean fullScreenEnabled, boolean inNewWindowEnabled, int row) {
if (fullScreenEnabled) {
// enabled if needed, disabled by default
if (inNewWindowEnabled) setNonQuotedConfigValue(FULLSCREEN_NEW_WINDOW, VALUE_FALSE);
}
}
/**
* Enable / disable the date and time insert plugin
*
* @param insertDateTimeEnabled
* true: plugin enabled; false: plugin disabled
* @param locale
* the locale used to format the date and time
* @param row
* The row where to place the plugin buttons
*/
private void setInsertDateTimeEnabled(boolean insertDateTimeEnabled, Locale locale, int row) {
if (insertDateTimeEnabled) {
// use date format defined in org.olat.core package
Formatter formatter = Formatter.getInstance(locale);
String dateFormat = formatter.getSimpleDatePatternForDate();
setQuotedConfigValue("insertdatetime_dateformat", dateFormat);
setNonQuotedConfigValue("insertdatetime_formats", "['" + dateFormat + "','%H:%M:%S']");
}
}
/**
* Enable / disable a TinyMCECustomPlugin plugin
*
* @param customPluginEnabled true: plugin enabled; false: plugin disabled
* @param customPlugin the plugin
* @param profil
* The profile in which context the plugin is used
*/
private void setCustomPluginEnabled(TinyMCECustomPlugin customPlugin) {
// Add plugin specific parameters
Map<String,String> params = customPlugin.getPluginParameters();
if (params != null) {
for (Entry<String, String> param : params.entrySet()) {
// don't use pluginName var, don't add the '-' char for params
String paramName = customPlugin.getPluginName() + "_" + param.getKey();
String value = param.getValue();
setQuotedConfigValue(paramName, value);
}
}
}
/**
* Set the path to content css files used to format the content.
*
* @param cssPath
* path to CSS separated by comma or NULL to not use any specific
* CSS files
*/
private void setContentCSS(String cssPath) {
if (cssPath != null) {
quotedConfigValues.put(CONTENT_CSS, cssPath);
} else {
if (quotedConfigValues.containsKey(CONTENT_CSS)) quotedConfigValues.remove(CONTENT_CSS);
}
}
/**
* Set the content CSS form the given theme. This will add the content.css
* from the default themen and override it with the current theme
* content.css
*
* @param theme
*/
public void setContentCSSFromTheme(Theme theme) {
// Always use default content css, then add the one from the theme
if (theme.getIdentifyer().equals("openolat")) {
setContentCSS(theme.getBaseURI() + "all/content.css");
} else {
StringOutput cssFiles = new StringOutput();
StaticMediaDispatcher.renderStaticURI(cssFiles, "themes/openolat/all/content.css");
cssFiles.append(",");
cssFiles.append(theme.getBaseURI()).append("all/content.css");
setContentCSS(cssFiles.toString());
}
}
/**
* Set the forced root element that is entered into the edit area when the
* area is empty. By default this is a <p> element
*
* @param rootElement
public void setForcedRootElement(String rootElement) {
setQuotedConfigValue(FORCED_ROOT_BLOCK, rootElement);
}*/
/**
* Disable the standard root element if no such wrapper element should be
* created at all
*/
public void disableRootParagraphElement() {
setQuotedConfigValue(FORCED_ROOT_BLOCK, FORCED_ROOT_BLOCK_VALUE_NOROOT);
}
/**
* Set the file browser callback for the given vfs container and link tree
* model
*
* @param vfsContainer
* The vfs container from which the files can be choosen
* @param customLinkTreeModel
* an optional custom link tree model
* @param supportedImageSuffixes
* Array of allowed image suffixes (jpg, png etc.)
* @param supportedMediaSuffixes
* Array of allowed media suffixes (mov, wav etc.)
*/
private void setFileBrowserCallback(VFSContainer vfsContainer, CustomLinkTreeModel customLinkTreeModel, String[] supportedImageSuffixes, String[] supportedMediaSuffixes, String[] supportedFlashPlayerSuffixes) {
// Add dom ID variable using prototype curry method
setNonQuotedConfigValue(FILE_BROWSER_CALLBACK, FILE_BROWSER_CALLBACK_VALUE_LINK_BROWSER + ".curry('" + domID + "')");
linkBrowserImageSuffixes = supportedImageSuffixes;
linkBrowserMediaSuffixes = supportedMediaSuffixes;
linkBrowserFlashPlayerSuffixes = supportedFlashPlayerSuffixes;
linkBrowserBaseContainer = vfsContainer;
linkBrowserCustomTreeModel = customLinkTreeModel;
}
/**
* Set an optional path relative to the vfs container of the file browser
* callback that is used as the upload destination when a user uploads a
* file and you don't whant the file to be uploaded into the vfs container
* itself but rather in another directory, e.g. a special media directory.
*
* @param linkBrowserUploadRelPath
*/
public void setFileBrowserUploadRelPath(String linkBrowserUploadRelPath) {
this.linkBrowserUploadRelPath = linkBrowserUploadRelPath;
}
/**
* Set the documents media base that is used to deliver media files
* referenced by the content.
*
* @param documentBaseContainer
* the vfs container that contains the media files
* @param relFilePath
* The file path of the HTML file relative to the
* documentBaseContainer
* @param usess
* The user session
*/
private void setDocumentMediaBase(final VFSContainer documentBaseContainer, String relFilePath, UserSession usess) {
linkBrowserRelativeFilePath = relFilePath;
// get a usersession-local mapper for the file storage (and tinymce's references to images and such)
contentMapper = new VFSContainerMapper(documentBaseContainer);
// Register mapper for this user. This mapper is cleaned up in the
// dispose method (RichTextElementImpl will clean it up)
String uri;
// Register mapper as cacheable
String mapperID = VFSManager.getRealPath(documentBaseContainer);
if (mapperID == null) {
// Can't cache mapper, no cacheable context available
uri = CoreSpringFactory.getImpl(MapperService.class).register(usess, contentMapper);
} else {
// Add classname to the file path to remove conflicts with other
// usages of the same file path
mapperID = this.getClass().getSimpleName() + ":" + mapperID;
uri = CoreSpringFactory.getImpl(MapperService.class).register(usess, mapperID, contentMapper);
}
if (relFilePath != null) {
// remove filename, path must end with slash
int lastSlash = relFilePath.lastIndexOf("/");
if (lastSlash == -1) {
relFilePath = "";
} else if (lastSlash + 1 < relFilePath.length()) {
relFilePath = relFilePath.substring(0, lastSlash + 1);
} else {
String containerPath = documentBaseContainer.getName();
// try to get more information if it's a local folder impl
if (documentBaseContainer instanceof LocalFolderImpl) {
LocalFolderImpl folder = (LocalFolderImpl) documentBaseContainer;
containerPath = folder.getBasefile().getAbsolutePath();
}
log.warn("Could not parse relative file path::" + relFilePath + " in container::" + containerPath);
}
} else {
relFilePath = "";
// set empty relative file path to prevent nullpointers later on
linkBrowserRelativeFilePath = relFilePath;
}
String fulluri = uri + "/" + relFilePath;
setQuotedConfigValue(DOCUMENT_BASE_URL, fulluri);
}
/**
* Set a tiny configuration value that must be quoted with double quotes
*
* @param key
* The configuration key
* @param value
* The configuration value
*/
private void setQuotedConfigValue(String key, String value) {
// remove non-quoted config values with same key
if (nonQuotedConfigValues.containsKey(key)) nonQuotedConfigValues.remove(key);
// add or overwrite new value
quotedConfigValues.put(key, value);
}
public void setInvalidElements(String elements) {
setQuotedConfigValue(RichTextConfiguration.INVALID_ELEMENTS, elements);
}
public void setExtendedValidElements(String elements) {
setQuotedConfigValue(RichTextConfiguration.EXTENDED_VALID_ELEMENTS, elements);
}
public void enableCode() {
tinyConfig = tinyConfig.enableCode();
}
public void enableStyleSelection() {
//setQuotedConfigValue(RichTextConfiguration.THEME_ADVANCED_BUTTONS1_ADD, RichTextConfiguration.SEPARATOR_BUTTON + "," + RichTextConfiguration.STYLESELECT_BUTTON);
}
/**
* Set a tiny configuration value that must not be quoted with quotes, e.g.
* JS function references or boolean values
*
* @param key
* The configuration key
* @param value
* The configuration value
*/
private void setNonQuotedConfigValue(String key, String value) {
// remove quoted config values with same key
if (quotedConfigValues.containsKey(key)) quotedConfigValues.remove(key);
// add or overwrite new value
nonQuotedConfigValues.put(key, value);
}
public void enableEditorHeight() {
setNonQuotedConfigValue(RichTextConfiguration.HEIGHT, "b_initialEditorHeight()");
}
/**
* Get the image suffixes that are supported
*
* @return
*/
public String[] getLinkBrowserImageSuffixes() {
return linkBrowserImageSuffixes;
}
/**
* Get the media suffixes that are supported
*
* @return
*/
public String[] getLinkBrowserMediaSuffixes() {
return linkBrowserMediaSuffixes;
}
/**
* Get the formats supported by the flash player
* @return
*/
public String[] getLinkBrowserFlashPlayerSuffixes() {
return linkBrowserFlashPlayerSuffixes;
}
/**
* Get the vfs base container for the file browser
*
* @return
*/
public VFSContainer getLinkBrowserBaseContainer() {
return linkBrowserBaseContainer;
}
/**
* Get the upload dir relative to the file browser
* @return
*/
public String getLinkBrowserUploadRelPath() {
return linkBrowserUploadRelPath;
}
/**
* Get the relative file path in relation to the browser base container or
* an empty string when on same level as base container (e.g. in form and
* not file mode) or NULL when the link browser and base container are not
* set at all
*
* @return
*/
public String getLinkBrowserRelativeFilePath() {
return linkBrowserRelativeFilePath;
}
/**
* Get the optional custom link browser tree model
* @return the model or NULL if not defined
*/
public CustomLinkTreeModel getLinkBrowserCustomLinkTreeModel() {
return linkBrowserCustomTreeModel;
}
protected void appendConfigToTinyJSArray_4(StringOutput out) {
// Now add the quoted values
Map<String,String> copyValues = new HashMap<String,String>(quotedConfigValues);
// Now add the non-quoted values (e.g. true, false or functions)
Map<String,String> copyNonValues = new HashMap<String,String>(nonQuotedConfigValues);
String converter = copyNonValues.get(URLCONVERTER_CALLBACK);
if(converter != null) {
copyNonValues.put(CONVERT_URLS, "true");
}
String contentCss = copyValues.remove(CONTENT_CSS);
if(contentCss != null) {
// add styles from content css and add them to format menu
copyNonValues.put(IMPORTCSS_APPEND, "true");
copyValues.put("content_css", Settings.createServerURI() + contentCss);
// filter emoticons classes from content css
copyNonValues.put(IMPORT_SELECTOR_CONVERTER, IMPORT_SELECTOR_CONVERTER_VALUE_REMOVE_EMOTICONS);
// group imported css classes to paragraph, div, table and style menu
copyNonValues.put(IMPORTCSS_GROUPS, IMPORTCSS_GROUPS_VALUE_MENU);
}
//new with menu
StringOutput tinyMenuSb = new StringOutput();
tinyMenuSb.append("plugins: '").append(tinyConfig.getPlugins()).append("',\n")
.append("image_advtab:true,\n")
.append("statusbar:true,\n")
.append("menubar:").append(tinyConfig.hasMenu()).append(",\n");
if (tinyConfig.getTool1() != null) {
tinyMenuSb.append("toolbar1: '").append(tinyConfig.getTool1()).append("',\n");
}
if(tinyConfig.hasMenu()) {
tinyMenuSb.append("menu:{\n");
boolean first = true;
for (String menuItem: tinyConfig.getMenu()) {
if(!first) tinyMenuSb.append("\n,");
if(first) first = false;
tinyMenuSb.append(menuItem);
}
tinyMenuSb.append("\n},\n");
}
for (Map.Entry<String, String> entry : copyValues.entrySet()) {
tinyMenuSb.append(entry.getKey()).append(": \"").append(entry.getValue()).append("\",\n");
}
for (Map.Entry<String, String> entry : copyNonValues.entrySet()) {
tinyMenuSb.append(entry.getKey()).append(": ").append(entry.getValue()).append(",\n");
}
out.append(tinyMenuSb);
}
/**
* @see org.olat.core.gui.control.Disposable#dispose()
*/
public void dispose() {
if (contentMapper != null) {
CoreSpringFactory.getImpl(MapperService.class).cleanUp(Collections.singletonList(contentMapper));
contentMapper = null;
}
}
}
| |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.introduceParameter;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiLocalVariable;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameter;
import com.intellij.refactoring.IntroduceParameterRefactoring;
import com.intellij.refactoring.JavaRefactoringSettings;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.ui.TypeSelectorManager;
import com.intellij.ui.NonFocusableCheckBox;
import com.intellij.ui.StateRestoringCheckBox;
import com.intellij.util.ui.JBUI;
import gnu.trove.TIntArrayList;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public abstract class IntroduceParameterSettingsUI {
protected final boolean myIsInvokedOnDeclaration;
protected final boolean myHasInitializer;
protected StateRestoringCheckBox myCbDeleteLocalVariable;
protected StateRestoringCheckBox myCbUseInitializer;
protected JRadioButton myReplaceFieldsWithGettersNoneRadio;
protected JRadioButton myReplaceFieldsWithGettersInaccessibleRadio;
protected JRadioButton myReplaceFieldsWithGettersAllRadio;
protected final ButtonGroup myReplaceFieldsWithGettersButtonGroup = new ButtonGroup();
protected final PsiParameter[] myParametersToRemove;
protected final boolean[] myParametersToRemoveChecked;
protected final boolean myIsLocalVariable;
protected JCheckBox myCbReplaceAllOccurences;
protected JCheckBox myCbGenerateDelegate;
public IntroduceParameterSettingsUI(PsiLocalVariable onLocalVariable,
PsiExpression onExpression,
PsiMethod methodToReplaceIn,
TIntArrayList parametersToRemove) {
myHasInitializer = onLocalVariable != null && onLocalVariable.getInitializer() != null;
myIsInvokedOnDeclaration = onExpression == null;
final PsiParameter[] parameters = methodToReplaceIn.getParameterList().getParameters();
myParametersToRemove = new PsiParameter[parameters.length];
myParametersToRemoveChecked = new boolean[parameters.length];
parametersToRemove.forEach(paramNum -> {
myParametersToRemove[paramNum] = parameters[paramNum];
return true;
});
myIsLocalVariable = onLocalVariable != null;
}
protected boolean isDeleteLocalVariable() {
return myIsInvokedOnDeclaration || myCbDeleteLocalVariable != null && myCbDeleteLocalVariable.isSelected();
}
protected boolean isUseInitializer() {
if(myIsInvokedOnDeclaration)
return myHasInitializer;
return myCbUseInitializer != null && myCbUseInitializer.isSelected();
}
protected int getReplaceFieldsWithGetters() {
if(myReplaceFieldsWithGettersAllRadio != null && myReplaceFieldsWithGettersAllRadio.isSelected()) {
return IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_ALL;
}
else if(myReplaceFieldsWithGettersInaccessibleRadio != null
&& myReplaceFieldsWithGettersInaccessibleRadio.isSelected()) {
return IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE;
}
else if(myReplaceFieldsWithGettersNoneRadio != null && myReplaceFieldsWithGettersNoneRadio.isSelected()) {
return IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE;
}
return IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE;
}
public boolean isReplaceAllOccurences() {
return myIsInvokedOnDeclaration || myCbReplaceAllOccurences != null && myCbReplaceAllOccurences.isSelected();
}
public boolean isGenerateDelegate() {
return myCbGenerateDelegate != null && myCbGenerateDelegate.isSelected();
}
protected JPanel createReplaceFieldsWithGettersPanel() {
JPanel radioButtonPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.insets = JBUI.insets(4, 8);
gbConstraints.weighty = 1;
gbConstraints.weightx = 1;
gbConstraints.gridy = 0;
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.anchor = GridBagConstraints.WEST;
radioButtonPanel.add(
new JLabel(RefactoringBundle.message("replace.fields.used.in.expressions.with.their.getters")), gbConstraints);
myReplaceFieldsWithGettersNoneRadio = new JRadioButton();
myReplaceFieldsWithGettersNoneRadio.setText(RefactoringBundle.message("do.not.replace"));
myReplaceFieldsWithGettersInaccessibleRadio = new JRadioButton();
myReplaceFieldsWithGettersInaccessibleRadio.setText(RefactoringBundle.message("replace.fields.inaccessible.in.usage.context"));
myReplaceFieldsWithGettersAllRadio = new JRadioButton();
myReplaceFieldsWithGettersAllRadio.setText(RefactoringBundle.message("replace.all.fields"));
gbConstraints.gridy++;
radioButtonPanel.add(myReplaceFieldsWithGettersNoneRadio, gbConstraints);
gbConstraints.gridy++;
radioButtonPanel.add(myReplaceFieldsWithGettersInaccessibleRadio, gbConstraints);
gbConstraints.gridy++;
radioButtonPanel.add(myReplaceFieldsWithGettersAllRadio, gbConstraints);
final int currentSetting = JavaRefactoringSettings.getInstance().INTRODUCE_PARAMETER_REPLACE_FIELDS_WITH_GETTERS;
myReplaceFieldsWithGettersButtonGroup.add(myReplaceFieldsWithGettersNoneRadio);
myReplaceFieldsWithGettersButtonGroup.add(myReplaceFieldsWithGettersInaccessibleRadio);
myReplaceFieldsWithGettersButtonGroup.add(myReplaceFieldsWithGettersAllRadio);
if(currentSetting == IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_ALL) {
myReplaceFieldsWithGettersAllRadio.setSelected(true);
}
else if(currentSetting == IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE) {
myReplaceFieldsWithGettersInaccessibleRadio.setSelected(true);
}
else if(currentSetting == IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE) {
myReplaceFieldsWithGettersNoneRadio.setSelected(true);
}
return radioButtonPanel;
}
protected void saveSettings(JavaRefactoringSettings settings) {
if(myCbDeleteLocalVariable != null) {
settings.INTRODUCE_PARAMETER_DELETE_LOCAL_VARIABLE =
myCbDeleteLocalVariable.isSelectedWhenSelectable();
}
if (myCbUseInitializer != null) {
settings.INTRODUCE_PARAMETER_USE_INITIALIZER = myCbUseInitializer.isSelectedWhenSelectable();
}
}
protected TIntArrayList getParametersToRemove() {
TIntArrayList parameters = new TIntArrayList();
for (int i = 0; i < myParametersToRemoveChecked.length; i++) {
if (myParametersToRemoveChecked[i]) {
parameters.add(i);
}
}
return parameters;
}
protected void updateControls(JCheckBox[] removeParamsCb) {
if (myCbReplaceAllOccurences != null) {
for (JCheckBox box : removeParamsCb) {
if (box != null) {
box.setEnabled(myCbReplaceAllOccurences.isSelected());
box.setSelected(myCbReplaceAllOccurences.isSelected());
}
}
if (myCbReplaceAllOccurences.isSelected()) {
if (myCbDeleteLocalVariable != null) {
myCbDeleteLocalVariable.makeSelectable();
}
}
else {
if (myCbDeleteLocalVariable != null) {
myCbDeleteLocalVariable.makeUnselectable(false);
}
}
}
}
protected void updateTypeSelector() {
if (myCbReplaceAllOccurences != null) {
getTypeSelectionManager().setAllOccurrences(myCbReplaceAllOccurences.isSelected());
}
else {
getTypeSelectionManager().setAllOccurrences(myIsInvokedOnDeclaration);
}
}
protected abstract TypeSelectorManager getTypeSelectionManager();
protected void createRemoveParamsPanel(GridBagConstraints gbConstraints, JPanel panel) {
final JCheckBox[] removeParamsCb = new JCheckBox[myParametersToRemove.length];
for (int i = 0; i < myParametersToRemove.length; i++) {
PsiParameter parameter = myParametersToRemove[i];
if (parameter == null) continue;
final NonFocusableCheckBox cb = new NonFocusableCheckBox(RefactoringBundle.message("remove.parameter.0.no.longer.used",
parameter.getName()));
removeParamsCb[i] = cb;
cb.setSelected(true);
gbConstraints.gridy++;
panel.add(cb, gbConstraints);
final int i1 = i;
cb.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
myParametersToRemoveChecked[i1] = cb.isSelected();
}
});
myParametersToRemoveChecked[i] = true;
}
updateControls(removeParamsCb);
if (myCbReplaceAllOccurences != null) {
myCbReplaceAllOccurences.addItemListener(
new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
updateControls(removeParamsCb);
}
}
);
}
}
public boolean isParamToRemove(PsiParameter param) {
if (myCbReplaceAllOccurences != null && !myCbReplaceAllOccurences.isSelected()) {
return false;
}
if (param.isVarArgs()) {
return myParametersToRemove[myParametersToRemove.length - 1] != null;
}
final int parameterIndex = ((PsiMethod)param.getDeclarationScope()).getParameterList().getParameterIndex(param);
return myParametersToRemove[parameterIndex] != null;
}
protected void createLocalVariablePanel(GridBagConstraints gbConstraints, JPanel panel, JavaRefactoringSettings settings) {
if(myIsLocalVariable && !myIsInvokedOnDeclaration) {
myCbDeleteLocalVariable = new StateRestoringCheckBox();
myCbDeleteLocalVariable.setText(RefactoringBundle.message("delete.variable.declaration"));
myCbDeleteLocalVariable.setFocusable(false);
gbConstraints.gridy++;
panel.add(myCbDeleteLocalVariable, gbConstraints);
myCbDeleteLocalVariable.setSelected(settings.INTRODUCE_PARAMETER_DELETE_LOCAL_VARIABLE);
gbConstraints.insets = JBUI.insets(0, 0, 4, 8);
if(myHasInitializer) {
myCbUseInitializer = new StateRestoringCheckBox();
myCbUseInitializer.setText(RefactoringBundle.message("use.variable.initializer.to.initialize.parameter"));
myCbUseInitializer.setSelected(settings.INTRODUCE_PARAMETER_USE_INITIALIZER);
myCbUseInitializer.setFocusable(false);
gbConstraints.gridy++;
panel.add(myCbUseInitializer, gbConstraints);
}
}
}
protected void createDelegateCb(GridBagConstraints gbConstraints, JPanel panel) {
myCbGenerateDelegate = new NonFocusableCheckBox(RefactoringBundle.message("delegation.panel.delegate.via.overloading.method"));
panel.add(myCbGenerateDelegate, gbConstraints);
}
protected void createOccurrencesCb(GridBagConstraints gbConstraints, JPanel panel, final int occurenceNumber) {
myCbReplaceAllOccurences = new NonFocusableCheckBox();
myCbReplaceAllOccurences.setText(RefactoringBundle.message("replace.all.occurences", occurenceNumber));
panel.add(myCbReplaceAllOccurences, gbConstraints);
myCbReplaceAllOccurences.setSelected(false);
}
public void setReplaceAllOccurrences(boolean replaceAll) {
if (myCbReplaceAllOccurences != null) {
myCbReplaceAllOccurences.setSelected(replaceAll);
}
}
}
| |
package com.example.brayan.uptchat;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ListView listView;
ListView listViewGroup;
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
Context context;
BackgroundTask backgroundTask;
BackgroundTask2 backgroundTask2;
List itemsUser = new ArrayList();
UsuariosAdapter usuariosAdapter;
List itemsGr = new ArrayList();
GruposAdapter gruposAdapter;
EditText editTextNewPassword;
TextView textViewNick;
String idUser;
String idGroup;
ArrayList<String> list_idUsers;
int cont;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
// setSupportActionBar(myToolbar);
context=this;
Resources res = getResources();
TabHost tabs=(TabHost)findViewById(android.R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec=tabs.newTabSpec("mitab1");
spec.setContent(R.id.tab1);
spec.setIndicator("",
res.getDrawable(R.drawable.ic_account_circle_black_24dp));
tabs.addTab(spec);
spec=tabs.newTabSpec("mitab2");
spec.setContent(R.id.tab2);
spec.setIndicator("",
res.getDrawable(R.drawable.ic_people_black_24dp));
tabs.addTab(spec);
spec=tabs.newTabSpec("mitab3");
spec.setContent(R.id.tab3);
spec.setIndicator("",
res.getDrawable(R.drawable.ic_border_color_black_24dp));
tabs.addTab(spec);
tabs.setCurrentTab(0);
backgroundTask = new BackgroundTask(context);
backgroundTask.execute();
//itemsUser.clear();
tabs.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
// Toast.makeText(context,tabId, Toast.LENGTH_SHORT).show();
switch (tabId){
case "mitab1":
itemsUser.clear();
backgroundTask = new BackgroundTask(context);
backgroundTask.execute();
break;
case "mitab2":
itemsGr.clear();
backgroundTask2 = new BackgroundTask2(context);
backgroundTask2.execute();
break;
}
}
});
listView = (ListView) findViewById(R.id.listView);
usuariosAdapter = new UsuariosAdapter(this, itemsUser);
listView.setAdapter(usuariosAdapter);
list_idUsers = new ArrayList<>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
view.setSelected(true); //****new
Usuario user = (Usuario) listView.getAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, MensajeActivity.class );
intent.putExtra("id",user.getId());
intent.putExtra("nick",user.getNick());
intent.putExtra("tipo","usuario");
startActivity(intent);
}
});
listViewGroup= (ListView) findViewById(R.id.listViewGrupos);
gruposAdapter = new GruposAdapter(this, itemsGr);
listViewGroup.setAdapter(gruposAdapter);
listViewGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Grupo grupo = (Grupo) listViewGroup.getAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, MensajeActivity.class );
intent.putExtra("id",grupo.getId());
intent.putExtra("nick",grupo.getNombre());
intent.putExtra("tipo","grupo");
startActivity(intent);
}
});
//aqui bakcgrTAask
SharedPreferences sharedPreferences = getSharedPreferences("dataSession", Context.MODE_PRIVATE);
idUser = sharedPreferences.getString("idUserSession", "");
String nickUser = sharedPreferences.getString("nickSession", "");
idGroup = sharedPreferences.getString("idGrupoSession", "");
String nombreGrupo = sharedPreferences.getString("nombreGrupoSession", "");
editTextNewPassword = (EditText) findViewById(R.id.editextPassword);
textViewNick = (TextView) findViewById(R.id.txtNickEdit);
textViewNick.setText(nickUser);
textViewNick.setTextColor(Color.rgb(63,44,43));
textViewNick.setTextSize(24);
}
public void goCrearGrupo(View view) {
Intent intent = new Intent(MainActivity.this, RegistroGrupoActivity.class );
startActivity(intent);
}
class BackgroundTask extends AsyncTask<Void,Void,String> {
Context ctx;
String URLconsulta="";
BackgroundTask(Context ctx){
this.ctx=ctx;
}
@Override
protected void onPreExecute() {
URLconsulta="http://"+getString(R.string.ipBase)+"/uptchat/index.php/chat/listarUsuarios";
}
@Override
protected String doInBackground(Void... params) {
try {
URL url=new URL(URLconsulta);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder=new StringBuilder();
while((JSON_STRING=bufferedReader.readLine())!=null){
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
try {
jsonObject=new JSONObject(result);
jsonArray=jsonObject.getJSONArray("usuarios");
for (int i=0; i < jsonArray.length();i++ ){
JSONObject JSO = jsonArray.getJSONObject(i);
itemsUser.add(new Usuario(JSO.getString("idusuario"),JSO.getString("nick")));
}
usuariosAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
class BackgroundTask2 extends AsyncTask<Void,Void,String> {
Context ctx;
String URLconsulta="";
BackgroundTask2(Context ctx){
this.ctx=ctx;
}
@Override
protected void onPreExecute() {
URLconsulta="http://"+getString(R.string.ipBase)+"/uptchat/index.php/chat/listarGrupos?idusuario="+String.valueOf(idUser);
}
@Override
protected String doInBackground(Void... params) {
try {
URL url=new URL(URLconsulta);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder=new StringBuilder();
while((JSON_STRING=bufferedReader.readLine())!=null){
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
try {
jsonObject=new JSONObject(result);
jsonArray=jsonObject.getJSONArray("grupos");
for (int i=0; i < jsonArray.length();i++ ){
JSONObject JSO = jsonArray.getJSONObject(i);
itemsGr.add(new Grupo(JSO.getString("idgrupo"),JSO.getString("nombre")));
}
gruposAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// e.printStackTrace();
// Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
private void guardarDato(){
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, String.valueOf("http://"+getString(R.string.ipBase)+"/uptchat/index.php/chat/editarPerfil"),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> map = new HashMap<>();
map.put("id",String.valueOf(idUser));
map.put("password",editTextNewPassword.getText().toString());
return map;
}
};
requestQueue.add(request);
}
public void cambiarPassword(View view) {
guardarDato();
}
}
| |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.shell;
import alluxio.AlluxioURI;
import alluxio.Configuration;
import alluxio.Constants;
import alluxio.PropertyKey;
import alluxio.cli.AlluxioShell;
import alluxio.client.file.FileSystem;
import alluxio.client.file.URIStatus;
import alluxio.exception.AlluxioException;
import alluxio.util.io.PathUtils;
import alluxio.util.network.NetworkAddressUtils;
import alluxio.util.network.NetworkAddressUtils.ServiceType;
import com.google.common.collect.Lists;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import javax.annotation.concurrent.ThreadSafe;
/**
* Class for convenience methods used by {@link AlluxioShell}.
*/
@ThreadSafe
public final class AlluxioShellUtils {
private AlluxioShellUtils() {} // prevent instantiation
/**
* Removes {@link Constants#HEADER} / {@link Constants#HEADER_FT} and hostname:port information
* from a path, leaving only the local file path.
*
* @param path the path to obtain the local path from
* @return the local path in string format
* @throws IOException if the given path is not valid
*/
public static String getFilePath(String path) throws IOException {
path = validatePath(path);
if (path.startsWith(Constants.HEADER)) {
path = path.substring(Constants.HEADER.length());
} else if (path.startsWith(Constants.HEADER_FT)) {
path = path.substring(Constants.HEADER_FT.length());
}
return path.substring(path.indexOf(AlluxioURI.SEPARATOR));
}
/**
* Validates the path, verifying that it contains the {@link Constants#HEADER} or
* {@link Constants#HEADER_FT} and a hostname:port specified.
*
* @param path the path to be verified
* @return the verified path in a form like alluxio://host:port/dir. If only the "/dir" or "dir"
* part is provided, the host and port are retrieved from property,
* alluxio.master.hostname and alluxio.master.port, respectively.
* @throws IOException if the given path is not valid
*/
public static String validatePath(String path) throws IOException {
if (path.startsWith(Constants.HEADER) || path.startsWith(Constants.HEADER_FT)) {
if (!path.contains(":")) {
throw new IOException("Invalid Path: " + path + ". Use " + Constants.HEADER
+ "host:port/ ," + Constants.HEADER_FT + "host:port/" + " , or /file");
} else {
return path;
}
} else {
String hostname = NetworkAddressUtils.getConnectHost(ServiceType.MASTER_RPC);
int port = Configuration.getInt(PropertyKey.MASTER_RPC_PORT);
if (Configuration.getBoolean(PropertyKey.ZOOKEEPER_ENABLED)) {
return PathUtils.concatPath(Constants.HEADER_FT + hostname + ":" + port, path);
}
return PathUtils.concatPath(Constants.HEADER + hostname + ":" + port, path);
}
}
/**
* Gets all the {@link AlluxioURI}s that match inputURI. If the path is a regular path, the
* returned list only contains the corresponding URI; Else if the path contains wildcards, the
* returned list contains all the matched URIs It supports any number of wildcards in inputURI
*
* @param alluxioClient the client used to fetch information of Alluxio files
* @param inputURI the input URI (could contain wildcards)
* @return a list of {@link AlluxioURI}s that matches the inputURI
* @throws IOException if any filesystem errors are encountered when expanding paths with
* wildcards
*/
public static List<AlluxioURI> getAlluxioURIs(FileSystem alluxioClient, AlluxioURI inputURI)
throws IOException {
if (!inputURI.getPath().contains(AlluxioURI.WILDCARD)) {
return Lists.newArrayList(inputURI);
} else {
String inputPath = inputURI.getPath();
AlluxioURI parentURI = new AlluxioURI(inputURI.getScheme(), inputURI.getAuthority(),
inputPath.substring(0, inputPath.indexOf(AlluxioURI.WILDCARD) + 1),
inputURI.getQueryMap()).getParent();
return getAlluxioURIs(alluxioClient, inputURI, parentURI);
}
}
/**
* The utility function used to implement getAlluxioURIs.
*
* Basically, it recursively iterates through the directory from the parent directory of inputURI
* (e.g., for input "/a/b/*", it will start from "/a/b") until it finds all the matches;
* It does not go into a directory if the prefix mismatches
* (e.g., for input "/a/b/*", it won't go inside directory "/a/c")
*
* @param alluxioClient the client used to fetch metadata of Alluxio files
* @param inputURI the input URI (could contain wildcards)
* @param parentDir the {@link AlluxioURI} of the directory in which we are searching matched
* files
* @return a list of {@link AlluxioURI}s of the files that match the inputURI in parentDir
* @throws IOException if any filesystem errors are encountered when expanding paths with
* wildcards
*/
private static List<AlluxioURI> getAlluxioURIs(FileSystem alluxioClient, AlluxioURI inputURI,
AlluxioURI parentDir) throws IOException {
List<AlluxioURI> res = new LinkedList<>();
List<URIStatus> statuses;
try {
statuses = alluxioClient.listStatus(parentDir);
} catch (AlluxioException e) {
throw new IOException(e);
}
for (URIStatus status : statuses) {
AlluxioURI fileURI =
new AlluxioURI(inputURI.getScheme(), inputURI.getAuthority(), status.getPath());
if (match(fileURI, inputURI)) { // if it matches
res.add(fileURI);
} else {
if (status.isFolder()) { // if it is a folder, we do it recursively
AlluxioURI dirURI =
new AlluxioURI(inputURI.getScheme(), inputURI.getAuthority(), status.getPath());
String prefix = inputURI.getLeadingPath(dirURI.getDepth());
if (prefix != null && match(dirURI, new AlluxioURI(prefix))) {
res.addAll(getAlluxioURIs(alluxioClient, inputURI, dirURI));
}
}
}
}
return res;
}
/**
* Gets the files (on the local filesystem) that match the given input path.
* If the path is a regular path, the returned list only contains the corresponding file;
* Else if the path contains wildcards, the returned list contains all the matched Files.
*
* @param inputPath The input file path (could contain wildcards)
* @return a list of files that matches inputPath
*/
public static List<File> getFiles(String inputPath) {
File file = new File(inputPath);
if (!inputPath.contains("*")) {
List<File> res = new LinkedList<>();
if (file.exists()) {
res.add(file);
}
return res;
} else {
String prefix = inputPath.substring(0, inputPath.indexOf(AlluxioURI.WILDCARD) + 1);
String parent = new File(prefix).getParent();
return getFiles(inputPath, parent);
}
}
/**
* The utility function used to implement getFiles.
* It follows the same algorithm as {@link #getAlluxioURIs}.
*
* @param inputPath the input file path (could contain wildcards)
* @param parent the directory in which we are searching matched files
* @return a list of files that matches the input path in the parent directory
*/
private static List<File> getFiles(String inputPath, String parent) {
List<File> res = new LinkedList<>();
File pFile = new File(parent);
if (!pFile.exists() || !pFile.isDirectory()) {
return res;
}
if (pFile.isDirectory() && pFile.canRead()) {
File[] fileList = pFile.listFiles();
if (fileList == null) {
return res;
}
for (File file : fileList) {
if (match(file.getPath(), inputPath)) { // if it matches
res.add(file);
} else {
if (file.isDirectory()) { // if it is a folder, we do it recursively
AlluxioURI dirURI = new AlluxioURI(file.getPath());
String prefix = new AlluxioURI(inputPath).getLeadingPath(dirURI.getDepth());
if (prefix != null && match(dirURI, new AlluxioURI(prefix))) {
res.addAll(getFiles(inputPath, dirURI.getPath()));
}
}
}
}
}
return res;
}
/**
* The characters that have special regex semantics.
*/
private static final Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
/**
* Escapes the special characters in a given string.
*
* @param str input string
* @return the string with special characters escaped
*/
private static String escape(String str) {
return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}
/**
* Replaces the wildcards with Java's regex semantics.
*/
private static String replaceWildcards(String text) {
return escape(text).replace("\\*", ".*");
}
/**
* Returns whether or not fileURI matches the patternURI.
*
* @param fileURI the {@link AlluxioURI} of a particular file
* @param patternURI the URI that can contain wildcards
* @return true if matches; false if not
*/
private static boolean match(AlluxioURI fileURI, AlluxioURI patternURI) {
return escape(fileURI.getPath()).matches(replaceWildcards(patternURI.getPath()));
}
/**
* Returns whether or not filePath matches patternPath.
*
* @param filePath path of a given file
* @param patternPath path that can contain wildcards
* @return true if matches; false if not
*/
protected static boolean match(String filePath, String patternPath) {
return match(new AlluxioURI(filePath), new AlluxioURI(patternPath));
}
}
| |
/*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
This software is provided by RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS or contributors be liable for any direct, indirect,
incidental, special, exemplary, or consequential damages (including, but not
limited to, procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even if
advised of the possibility of such damage.
*******************************************************************************/
/*
* Created on May 4, 2005
*/
package org.mpisws.p2p.testing.transportlayer.replay;
import rice.environment.logging.Logger;
import rice.p2p.commonapi.*;
import rice.p2p.scribe.Scribe;
import rice.p2p.scribe.ScribeClient;
import rice.p2p.scribe.ScribeContent;
import rice.p2p.scribe.ScribeImpl;
import rice.p2p.scribe.Topic;
import rice.pastry.commonapi.PastryIdFactory;
/**
* We implement the Application interface to receive regular timed messages (see lesson5).
* We implement the ScribeClient interface to receive scribe messages (called ScribeContent).
*
* @author Jeff Hoye
*/
public class MyScribeClient implements ScribeClient, Application {
/**
* The message sequence number. Will be incremented after each send.
*/
int seqNum = 0;
/**
* This task kicks off publishing and anycasting.
* We hold it around in case we ever want to cancel the publishTask.
*/
CancellableTask publishTask;
/**
* My handle to a scribe impl.
*/
Scribe myScribe;
/**
* The only topic this appl is subscribing to.
*/
Topic myTopic;
Node node;
/**
* The Endpoint represents the underlieing node. By making calls on the
* Endpoint, it assures that the message will be delivered to a MyApp on whichever
* node the message is intended for.
*/
protected Endpoint endpoint;
protected Logger logger;
/**
* The constructor for this scribe client. It will construct the ScribeApplication.
*
* @param node the PastryNode
*/
public MyScribeClient(Node node) {
this.node = node;
logger = node.getEnvironment().getLogManager().getLogger(MyScribeClient.class, null);
// you should recognize this from lesson 3
this.endpoint = node.buildEndpoint(this, "myinstance");
// construct Scribe
myScribe = new ScribeImpl(node,"myScribeInstance");
// construct the topic
myTopic = new Topic(new PastryIdFactory(node.getEnvironment()), "example topic");
// System.out.println("myTopic = "+myTopic);
// now we can receive messages
endpoint.register();
}
/**
* Subscribes to myTopic.
*/
public void subscribe() {
myScribe.subscribe(myTopic, this);
}
/**
* Starts the publish task.
*/
public void startPublishTask() {
publishTask = endpoint.scheduleMessage(new PublishContent(), 5000, 5000);
}
/**
* Part of the Application interface. Will receive PublishContent every so often.
*/
public void deliver(Id id, Message message) {
if (message instanceof PublishContent) {
sendMulticast();
sendAnycast();
}
}
/**
* Sends the multicast message.
*/
public void sendMulticast() {
System.out.println("Node "+endpoint.getLocalNodeHandle()+" broadcasting "+seqNum);
MyScribeContent myMessage = new MyScribeContent(endpoint.getLocalNodeHandle(), seqNum);
myScribe.publish(myTopic, myMessage);
seqNum++;
}
/**
* Called whenever we receive a published message.
*/
public void deliver(Topic topic, ScribeContent content) {
logger.log("MyScribeClient.deliver("+topic+","+content+")");
if (((MyScribeContent)content).from == null) {
new Exception("Stack Trace").printStackTrace();
}
}
/**
* Sends an anycast message.
*/
public void sendAnycast() {
System.out.println("Node "+endpoint.getLocalNodeHandle()+" anycasting "+seqNum);
MyScribeContent myMessage = new MyScribeContent(endpoint.getLocalNodeHandle(), seqNum);
myScribe.anycast(myTopic, myMessage);
seqNum++;
}
/**
* Called when we receive an anycast. If we return
* false, it will be delivered elsewhere. Returning true
* stops the message here.
*/
public boolean anycast(Topic topic, ScribeContent content) {
boolean returnValue = myScribe.getEnvironment().getRandomSource().nextInt(3) == 0;
System.out.println("MyScribeClient.anycast("+topic+","+content+"):"+returnValue);
return returnValue;
}
public void childAdded(Topic topic, NodeHandle child) {
// System.out.println("MyScribeClient.childAdded("+topic+","+child+")");
}
public void childRemoved(Topic topic, NodeHandle child) {
// System.out.println("MyScribeClient.childRemoved("+topic+","+child+")");
}
public void subscribeFailed(Topic topic) {
// System.out.println("MyScribeClient.childFailed("+topic+")");
}
public boolean forward(RouteMessage message) {
return true;
}
public void update(NodeHandle handle, boolean joined) {
}
class PublishContent implements Message {
public int getPriority() {
return MAX_PRIORITY;
}
}
/************ Some passthrough accessors for the myScribe *************/
public boolean isRoot() {
return myScribe.isRoot(myTopic);
}
public NodeHandle getParent() {
// NOTE: Was just added to the Scribe interface. May need to cast myScribe to a
// ScribeImpl if using 1.4.1_01 or older.
return ((ScribeImpl)myScribe).getParent(myTopic);
//return myScribe.getParent(myTopic);
}
public NodeHandle[] getChildren() {
return myScribe.getChildren(myTopic);
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.query;
import com.carrotsearch.hppc.ObjectFloatOpenHashMap;
import com.google.common.collect.Lists;
import org.apache.lucene.queryparser.classic.MapperQueryParser;
import org.apache.lucene.queryparser.classic.QueryParserSettings;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.util.LocaleUtils;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.analysis.NamedAnalyzer;
import org.elasticsearch.index.query.support.QueryParsers;
import org.joda.time.DateTimeZone;
import java.io.IOException;
import java.util.Locale;
import static org.elasticsearch.common.lucene.search.Queries.fixNegativeQueryIfNeeded;
/**
*
*/
public class QueryStringQueryParser implements QueryParser {
public static final String NAME = "query_string";
private static final ParseField FUZZINESS = Fuzziness.FIELD.withDeprecation("fuzzy_min_sim");
private final boolean defaultAnalyzeWildcard;
private final boolean defaultAllowLeadingWildcard;
@Inject
public QueryStringQueryParser(Settings settings) {
this.defaultAnalyzeWildcard = settings.getAsBoolean("indices.query.query_string.analyze_wildcard", QueryParserSettings.DEFAULT_ANALYZE_WILDCARD);
this.defaultAllowLeadingWildcard = settings.getAsBoolean("indices.query.query_string.allowLeadingWildcard", QueryParserSettings.DEFAULT_ALLOW_LEADING_WILDCARD);
}
@Override
public String[] names() {
return new String[]{NAME, Strings.toCamelCase(NAME)};
}
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
String queryName = null;
QueryParserSettings qpSettings = new QueryParserSettings();
qpSettings.defaultField(parseContext.defaultField());
qpSettings.lenient(parseContext.queryStringLenient());
qpSettings.analyzeWildcard(defaultAnalyzeWildcard);
qpSettings.allowLeadingWildcard(defaultAllowLeadingWildcard);
qpSettings.locale(Locale.ROOT);
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
if ("fields".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
String fField = null;
float fBoost = -1;
char[] text = parser.textCharacters();
int end = parser.textOffset() + parser.textLength();
for (int i = parser.textOffset(); i < end; i++) {
if (text[i] == '^') {
int relativeLocation = i - parser.textOffset();
fField = new String(text, parser.textOffset(), relativeLocation);
fBoost = Float.parseFloat(new String(text, i + 1, parser.textLength() - relativeLocation - 1));
break;
}
}
if (fField == null) {
fField = parser.text();
}
if (qpSettings.fields() == null) {
qpSettings.fields(Lists.<String>newArrayList());
}
if (Regex.isSimpleMatchPattern(fField)) {
for (String field : parseContext.mapperService().simpleMatchToIndexNames(fField)) {
qpSettings.fields().add(field);
if (fBoost != -1) {
if (qpSettings.boosts() == null) {
qpSettings.boosts(new ObjectFloatOpenHashMap<String>());
}
qpSettings.boosts().put(field, fBoost);
}
}
} else {
qpSettings.fields().add(fField);
if (fBoost != -1) {
if (qpSettings.boosts() == null) {
qpSettings.boosts(new ObjectFloatOpenHashMap<String>());
}
qpSettings.boosts().put(fField, fBoost);
}
}
}
} else {
throw new QueryParsingException(parseContext.index(), "[query_string] query does not support [" + currentFieldName + "]");
}
} else if (token.isValue()) {
if ("query".equals(currentFieldName)) {
qpSettings.queryString(parser.text());
} else if ("default_field".equals(currentFieldName) || "defaultField".equals(currentFieldName)) {
qpSettings.defaultField(parser.text());
} else if ("default_operator".equals(currentFieldName) || "defaultOperator".equals(currentFieldName)) {
String op = parser.text();
if ("or".equalsIgnoreCase(op)) {
qpSettings.defaultOperator(org.apache.lucene.queryparser.classic.QueryParser.Operator.OR);
} else if ("and".equalsIgnoreCase(op)) {
qpSettings.defaultOperator(org.apache.lucene.queryparser.classic.QueryParser.Operator.AND);
} else {
throw new QueryParsingException(parseContext.index(), "Query default operator [" + op + "] is not allowed");
}
} else if ("analyzer".equals(currentFieldName)) {
NamedAnalyzer analyzer = parseContext.analysisService().analyzer(parser.text());
if (analyzer == null) {
throw new QueryParsingException(parseContext.index(), "[query_string] analyzer [" + parser.text() + "] not found");
}
qpSettings.forcedAnalyzer(analyzer);
} else if ("quote_analyzer".equals(currentFieldName) || "quoteAnalyzer".equals(currentFieldName)) {
NamedAnalyzer analyzer = parseContext.analysisService().analyzer(parser.text());
if (analyzer == null) {
throw new QueryParsingException(parseContext.index(), "[query_string] quote_analyzer [" + parser.text() + "] not found");
}
qpSettings.forcedQuoteAnalyzer(analyzer);
} else if ("allow_leading_wildcard".equals(currentFieldName) || "allowLeadingWildcard".equals(currentFieldName)) {
qpSettings.allowLeadingWildcard(parser.booleanValue());
} else if ("auto_generate_phrase_queries".equals(currentFieldName) || "autoGeneratePhraseQueries".equals(currentFieldName)) {
qpSettings.autoGeneratePhraseQueries(parser.booleanValue());
} else if ("max_determinized_states".equals(currentFieldName) || "maxDeterminizedStates".equals(currentFieldName)) {
qpSettings.maxDeterminizedStates(parser.intValue());
} else if ("lowercase_expanded_terms".equals(currentFieldName) || "lowercaseExpandedTerms".equals(currentFieldName)) {
qpSettings.lowercaseExpandedTerms(parser.booleanValue());
} else if ("enable_position_increments".equals(currentFieldName) || "enablePositionIncrements".equals(currentFieldName)) {
qpSettings.enablePositionIncrements(parser.booleanValue());
} else if ("escape".equals(currentFieldName)) {
qpSettings.escape(parser.booleanValue());
} else if ("use_dis_max".equals(currentFieldName) || "useDisMax".equals(currentFieldName)) {
qpSettings.useDisMax(parser.booleanValue());
} else if ("fuzzy_prefix_length".equals(currentFieldName) || "fuzzyPrefixLength".equals(currentFieldName)) {
qpSettings.fuzzyPrefixLength(parser.intValue());
} else if ("fuzzy_max_expansions".equals(currentFieldName) || "fuzzyMaxExpansions".equals(currentFieldName)) {
qpSettings.fuzzyMaxExpansions(parser.intValue());
} else if ("fuzzy_rewrite".equals(currentFieldName) || "fuzzyRewrite".equals(currentFieldName)) {
qpSettings.fuzzyRewriteMethod(QueryParsers.parseRewriteMethod(parser.textOrNull()));
} else if ("phrase_slop".equals(currentFieldName) || "phraseSlop".equals(currentFieldName)) {
qpSettings.phraseSlop(parser.intValue());
} else if (FUZZINESS.match(currentFieldName, parseContext.parseFlags())) {
qpSettings.fuzzyMinSim(Fuzziness.parse(parser).asSimilarity());
} else if ("boost".equals(currentFieldName)) {
qpSettings.boost(parser.floatValue());
} else if ("tie_breaker".equals(currentFieldName) || "tieBreaker".equals(currentFieldName)) {
qpSettings.tieBreaker(parser.floatValue());
} else if ("analyze_wildcard".equals(currentFieldName) || "analyzeWildcard".equals(currentFieldName)) {
qpSettings.analyzeWildcard(parser.booleanValue());
} else if ("rewrite".equals(currentFieldName)) {
qpSettings.rewriteMethod(QueryParsers.parseRewriteMethod(parser.textOrNull()));
} else if ("minimum_should_match".equals(currentFieldName) || "minimumShouldMatch".equals(currentFieldName)) {
qpSettings.minimumShouldMatch(parser.textOrNull());
} else if ("quote_field_suffix".equals(currentFieldName) || "quoteFieldSuffix".equals(currentFieldName)) {
qpSettings.quoteFieldSuffix(parser.textOrNull());
} else if ("lenient".equalsIgnoreCase(currentFieldName)) {
qpSettings.lenient(parser.booleanValue());
} else if ("locale".equals(currentFieldName)) {
String localeStr = parser.text();
qpSettings.locale(LocaleUtils.parse(localeStr));
} else if ("time_zone".equals(currentFieldName)) {
try {
qpSettings.timeZone(DateTimeZone.forID(parser.text()));
} catch (IllegalArgumentException e) {
throw new QueryParsingException(parseContext.index(), "[query_string] time_zone [" + parser.text() + "] is unknown");
}
} else if ("_name".equals(currentFieldName)) {
queryName = parser.text();
} else {
throw new QueryParsingException(parseContext.index(), "[query_string] query does not support [" + currentFieldName + "]");
}
}
}
if (qpSettings.queryString() == null) {
throw new QueryParsingException(parseContext.index(), "query_string must be provided with a [query]");
}
qpSettings.defaultAnalyzer(parseContext.mapperService().searchAnalyzer());
qpSettings.defaultQuoteAnalyzer(parseContext.mapperService().searchQuoteAnalyzer());
if (qpSettings.escape()) {
qpSettings.queryString(org.apache.lucene.queryparser.classic.QueryParser.escape(qpSettings.queryString()));
}
qpSettings.queryTypes(parseContext.queryTypes());
Query query = parseContext.queryParserCache().get(qpSettings);
if (query != null) {
if (queryName != null) {
parseContext.addNamedQuery(queryName, query);
}
return query;
}
MapperQueryParser queryParser = parseContext.queryParser(qpSettings);
try {
query = queryParser.parse(qpSettings.queryString());
if (query == null) {
return null;
}
if (qpSettings.boost() != QueryParserSettings.DEFAULT_BOOST) {
query.setBoost(query.getBoost() * qpSettings.boost());
}
query = fixNegativeQueryIfNeeded(query);
if (query instanceof BooleanQuery) {
Queries.applyMinimumShouldMatch((BooleanQuery) query, qpSettings.minimumShouldMatch());
}
parseContext.queryParserCache().put(qpSettings, query);
if (queryName != null) {
parseContext.addNamedQuery(queryName, query);
}
return query;
} catch (org.apache.lucene.queryparser.classic.ParseException e) {
throw new QueryParsingException(parseContext.index(), "Failed to parse query [" + qpSettings.queryString() + "]", e);
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.mapper;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESSingleNodeTestCase;
import org.elasticsearch.test.InternalSettingsPlugin;
import org.elasticsearch.test.geo.RandomGeoGenerator;
import org.hamcrest.CoreMatchers;
import java.io.IOException;
import java.util.Collection;
import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE;
import static org.elasticsearch.geometry.utils.Geohash.stringEncode;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.mapper.AbstractGeometryFieldMapper.Names.IGNORE_MALFORMED;
import static org.elasticsearch.index.mapper.AbstractGeometryFieldMapper.Names.IGNORE_Z_VALUE;
import static org.elasticsearch.index.mapper.AbstractPointGeometryFieldMapper.Names.NULL_VALUE;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
public class GeoPointFieldMapperTests extends ESSingleNodeTestCase {
@Override
protected Collection<Class<? extends Plugin>> getPlugins() {
return pluginList(InternalSettingsPlugin.class);
}
public void testGeoHashValue() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point");
String mapping = Strings.toString(xContentBuilder.endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.field("point", stringEncode(1.3, 1.2))
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("point"), notNullValue());
}
public void testWKT() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point");
String mapping = Strings.toString(xContentBuilder.endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.field("point", "POINT (2 3)")
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("point"), notNullValue());
}
public void testLatLonValuesStored() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point");
String mapping = Strings.toString(xContentBuilder.field("store", true).endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.startObject("point").field("lat", 1.2).field("lon", 1.3).endObject()
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("point"), notNullValue());
}
public void testArrayLatLonValues() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point").field("doc_values", false);
String mapping = Strings.toString(xContentBuilder.field("store", true).endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.startArray("point")
.startObject().field("lat", 1.2).field("lon", 1.3).endObject()
.startObject().field("lat", 1.4).field("lon", 1.5).endObject()
.endArray()
.endObject()),
XContentType.JSON));
// doc values are enabled by default, but in this test we disable them; we should only have 2 points
assertThat(doc.rootDoc().getFields("point"), notNullValue());
assertThat(doc.rootDoc().getFields("point").length, equalTo(4));
}
public void testLatLonInOneValue() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point");
String mapping = Strings.toString(xContentBuilder.endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.field("point", "1.2,1.3")
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("point"), notNullValue());
}
public void testLatLonStringWithZValue() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point")
.field(IGNORE_Z_VALUE.getPreferredName(), true);
String mapping = Strings.toString(xContentBuilder.endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.field("point", "1.2,1.3,10.0")
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("point"), notNullValue());
}
public void testLatLonStringWithZValueException() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point")
.field(IGNORE_Z_VALUE.getPreferredName(), false);
String mapping = Strings.toString(xContentBuilder.endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
SourceToParse source = new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.field("point", "1.2,1.3,10.0")
.endObject()),
XContentType.JSON);
Exception e = expectThrows(MapperParsingException.class, () -> defaultMapper.parse(source));
assertThat(e.getCause().getMessage(), containsString("but [ignore_z_value] parameter is [false]"));
}
public void testLatLonInOneValueStored() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point");
String mapping = Strings.toString(xContentBuilder.field("store", true).endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.field("point", "1.2,1.3")
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("point"), notNullValue());
}
public void testLatLonInOneValueArray() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point").field("doc_values", false);
String mapping = Strings.toString(xContentBuilder.field("store", true).endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.startArray("point")
.value("1.2,1.3")
.value("1.4,1.5")
.endArray()
.endObject()),
XContentType.JSON));
// doc values are enabled by default, but in this test we disable them; we should only have 2 points
assertThat(doc.rootDoc().getFields("point"), notNullValue());
assertThat(doc.rootDoc().getFields("point").length, equalTo(4));
}
public void testLonLatArray() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point");
String mapping = Strings.toString(xContentBuilder.endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.startArray("point").value(1.3).value(1.2).endArray()
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("point"), notNullValue());
}
public void testLonLatArrayDynamic() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startArray("dynamic_templates").startObject().startObject("point").field("match", "point*")
.startObject("mapping").field("type", "geo_point");
String mapping = Strings.toString(xContentBuilder.endObject().endObject().endObject().endArray().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.startArray("point").value(1.3).value(1.2).endArray()
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("point"), notNullValue());
}
public void testLonLatArrayStored() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point");
String mapping = Strings.toString(xContentBuilder.field("store", true).endObject().endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.startArray("point").value(1.3).value(1.2).endArray()
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("point"), notNullValue());
assertThat(doc.rootDoc().getFields("point").length, equalTo(3));
}
public void testLonLatArrayArrayStored() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("point").field("type", "geo_point");
String mapping = Strings.toString(xContentBuilder.field("store", true)
.field("doc_values", false).endObject().endObject()
.endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.startArray("point")
.startArray().value(1.3).value(1.2).endArray()
.startArray().value(1.5).value(1.4).endArray()
.endArray()
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getFields("point"), notNullValue());
assertThat(doc.rootDoc().getFields("point").length, CoreMatchers.equalTo(4));
}
/**
* Test that accept_z_value parameter correctly parses
*/
public void testIgnoreZValue() throws IOException {
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type1")
.startObject("properties").startObject("location")
.field("type", "geo_point")
.field(IGNORE_Z_VALUE.getPreferredName(), "true")
.endObject().endObject()
.endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type1", new CompressedXContent(mapping));
Mapper fieldMapper = defaultMapper.mappers().getMapper("location");
assertThat(fieldMapper, instanceOf(GeoPointFieldMapper.class));
boolean ignoreZValue = ((GeoPointFieldMapper)fieldMapper).ignoreZValue().value();
assertThat(ignoreZValue, equalTo(true));
// explicit false accept_z_value test
mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type1")
.startObject("properties").startObject("location")
.field("type", "geo_point")
.field(IGNORE_Z_VALUE.getPreferredName(), "false")
.endObject().endObject()
.endObject().endObject());
defaultMapper = createIndex("test2").mapperService().documentMapperParser().parse("type1", new CompressedXContent(mapping));
fieldMapper = defaultMapper.mappers().getMapper("location");
assertThat(fieldMapper, instanceOf(GeoPointFieldMapper.class));
ignoreZValue = ((GeoPointFieldMapper)fieldMapper).ignoreZValue().value();
assertThat(ignoreZValue, equalTo(false));
}
public void testMultiField() throws Exception {
int numDocs = randomIntBetween(10, 100);
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject()
.startObject("properties").startObject("location")
.field("type", "geo_point")
.startObject("fields")
.startObject("geohash").field("type", "keyword").endObject() // test geohash as keyword
.startObject("latlon").field("type", "keyword").endObject() // test geohash as string
.endObject()
.endObject().endObject().endObject());
CreateIndexRequestBuilder mappingRequest = client().admin().indices().prepareCreate("test")
.setMapping(mapping);
mappingRequest.execute().actionGet();
// create index and add random test points
client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet();
for (int i=0; i<numDocs; ++i) {
final GeoPoint pt = RandomGeoGenerator.randomPoint(random());
client().prepareIndex("test").setSource(jsonBuilder().startObject()
.startObject("location").field("lat", pt.lat())
.field("lon", pt.lon()).endObject().endObject()).setRefreshPolicy(IMMEDIATE).get();
}
// TODO these tests are bogus and need to be Fix
// query by geohash subfield
SearchResponse searchResponse = client().prepareSearch().addStoredField("location.geohash")
.setQuery(matchAllQuery()).execute().actionGet();
assertEquals(numDocs, searchResponse.getHits().getTotalHits().value);
// query by latlon subfield
searchResponse = client().prepareSearch().addStoredField("location.latlon").setQuery(matchAllQuery()).execute().actionGet();
assertEquals(numDocs, searchResponse.getHits().getTotalHits().value);
}
public void testEmptyName() throws Exception {
// after 5.x
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("").field("type", "geo_point").endObject().endObject()
.endObject().endObject());
DocumentMapperParser parser = createIndex("test").mapperService().documentMapperParser();
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> parser.parse("type", new CompressedXContent(mapping))
);
assertThat(e.getMessage(), containsString("name cannot be empty string"));
}
public void testNullValue() throws Exception {
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("location")
.field("type", "geo_point")
.field(NULL_VALUE.getPreferredName(), "1,2")
.endObject().endObject()
.endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
Mapper fieldMapper = defaultMapper.mappers().getMapper("location");
assertThat(fieldMapper, instanceOf(GeoPointFieldMapper.class));
Object nullValue = ((GeoPointFieldMapper) fieldMapper).fieldType().nullValue();
assertThat(nullValue, equalTo(new GeoPoint(1, 2)));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.nullField("location")
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("location"), notNullValue());
BytesRef defaultValue = doc.rootDoc().getBinaryValue("location");
doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.field("location", "1, 2")
.endObject()),
XContentType.JSON));
// Shouldn't matter if we specify the value explicitly or use null value
assertThat(defaultValue, equalTo(doc.rootDoc().getBinaryValue("location")));
doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.field("location", "3, 4")
.endObject()),
XContentType.JSON));
// Shouldn't matter if we specify the value explicitly or use null value
assertThat(defaultValue, not(equalTo(doc.rootDoc().getBinaryValue("location"))));
}
/**
* Test the fix for a bug that would read the value of field "ignore_z_value" for "ignore_malformed"
* when setting the "null_value" field. See PR https://github.com/elastic/elasticsearch/pull/49645
*/
public void testNullValueWithIgnoreMalformed() throws Exception {
// Set ignore_z_value = false and ignore_malformed = true and test that a malformed point for null_value is normalized.
String mapping = Strings.toString(XContentFactory.jsonBuilder()
.startObject().startObject("type")
.startObject("properties").startObject("location")
.field("type", "geo_point")
.field(IGNORE_Z_VALUE.getPreferredName(), false)
.field(IGNORE_MALFORMED.getPreferredName(), true)
.field(NULL_VALUE.getPreferredName(), "91,181")
.endObject().endObject()
.endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
Mapper fieldMapper = defaultMapper.mappers().getMapper("location");
assertThat(fieldMapper, instanceOf(GeoPointFieldMapper.class));
Object nullValue = ((GeoPointFieldMapper) fieldMapper).fieldType().nullValue();
// geo_point [91, 181] should have been normalized to [89, 1]
assertThat(nullValue, equalTo(new GeoPoint(89, 1)));
}
public void testInvalidGeohashIgnored() throws Exception {
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("location")
.field("type", "geo_point")
.field("ignore_malformed", "true")
.endObject()
.endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
ParsedDocument doc = defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.field("location", "1234.333")
.endObject()),
XContentType.JSON));
assertThat(doc.rootDoc().getField("location"), nullValue());
}
public void testInvalidGeohashNotIgnored() throws Exception {
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("location")
.field("type", "geo_point")
.endObject()
.endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
MapperParsingException ex = expectThrows(MapperParsingException.class,
() -> defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.field("location", "1234.333")
.endObject()),
XContentType.JSON)));
assertThat(ex.getMessage(), equalTo("failed to parse field [location] of type [geo_point]"));
assertThat(ex.getRootCause().getMessage(), equalTo("unsupported symbol [.] in geohash [1234.333]"));
}
public void testInvalidGeopointValuesIgnored() throws Exception {
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("location")
.field("type", "geo_point")
.field("ignore_malformed", "true")
.endObject()
.endObject().endObject().endObject());
DocumentMapper defaultMapper = createIndex("test").mapperService().documentMapperParser()
.parse("type", new CompressedXContent(mapping));
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("location", "1234.333").endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("lat", "-").field("lon", 1.3).endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("lat", 1.3).field("lon", "-").endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("location", "-,1.3").endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("location", "1.3,-").endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("lat", "NaN").field("lon", "NaN").endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("lat", 12).field("lon", "NaN").endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("lat", "NaN").field("lon", 10).endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("location", "NaN,NaN").endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("location", "10,NaN").endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("location", "NaN,12").endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().startObject("location").nullField("lat").field("lon", 1).endObject().endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
assertThat(defaultMapper.parse(new SourceToParse("test", "1",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().startObject("location").nullField("lat").nullField("lon").endObject().endObject()
), XContentType.JSON)).rootDoc().getField("location"), nullValue());
}
}
| |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source.tree.injected;
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.injected.editor.DocumentWindow;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.injected.editor.VirtualFileWindow;
import com.intellij.lang.ASTNode;
import com.intellij.lang.Language;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.lang.injection.MultiHostRegistrar;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.BooleanRunnable;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.PsiDocumentManagerBase;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.source.DummyHolder;
import com.intellij.psi.injection.ReferenceInjector;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.*;
import com.intellij.reference.SoftReference;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.DeprecatedMethodException;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ConcurrentList;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* @deprecated Use {@link InjectedLanguageManager} instead
*/
@Deprecated
public class InjectedLanguageUtil {
public static final Key<IElementType> INJECTED_FRAGMENT_TYPE = Key.create("INJECTED_FRAGMENT_TYPE");
public static final Key<Boolean> FRANKENSTEIN_INJECTION = InjectedLanguageManager.FRANKENSTEIN_INJECTION;
@NotNull
static PsiElement loadTree(@NotNull PsiElement host, @NotNull PsiFile containingFile) {
if (containingFile instanceof DummyHolder) {
PsiElement context = containingFile.getContext();
if (context != null) {
PsiFile topFile = context.getContainingFile();
topFile.getNode(); //load tree
TextRange textRange = host.getTextRange().shiftRight(context.getTextRange().getStartOffset());
PsiElement inLoadedTree =
PsiTreeUtil.findElementOfClassAtRange(topFile, textRange.getStartOffset(), textRange.getEndOffset(), host.getClass());
if (inLoadedTree != null) {
host = inLoadedTree;
}
}
}
return host;
}
private static final Key<List<TokenInfo>> HIGHLIGHT_TOKENS = Key.create("HIGHLIGHT_TOKENS");
public static List<TokenInfo> getHighlightTokens(@NotNull PsiFile file) {
return file.getUserData(HIGHLIGHT_TOKENS);
}
public static class TokenInfo {
@NotNull public final IElementType type;
@NotNull public final ProperTextRange rangeInsideInjectionHost;
public final int shredIndex;
public final TextAttributes attributes;
public TokenInfo(@NotNull IElementType type,
@NotNull ProperTextRange rangeInsideInjectionHost,
int shredIndex,
@NotNull TextAttributes attributes) {
this.type = type;
this.rangeInsideInjectionHost = rangeInsideInjectionHost;
this.shredIndex = shredIndex;
this.attributes = attributes;
}
}
static void setHighlightTokens(@NotNull PsiFile file, @NotNull List<TokenInfo> tokens) {
file.putUserData(HIGHLIGHT_TOKENS, tokens);
}
public static Place getShreds(@NotNull PsiFile injectedFile) {
FileViewProvider viewProvider = injectedFile.getViewProvider();
return getShreds(viewProvider);
}
public static Place getShreds(@NotNull FileViewProvider viewProvider) {
if (!(viewProvider instanceof InjectedFileViewProvider)) return null;
InjectedFileViewProvider myFileViewProvider = (InjectedFileViewProvider)viewProvider;
return getShreds(myFileViewProvider.getDocument());
}
@NotNull
private static Place getShreds(@NotNull DocumentWindow document) {
return ((DocumentWindowImpl)document).getShreds();
}
public static void enumerate(@NotNull DocumentWindow documentWindow,
@NotNull PsiFile hostPsiFile,
@NotNull PsiLanguageInjectionHost.InjectedPsiVisitor visitor) {
Segment[] ranges = documentWindow.getHostRanges();
Segment rangeMarker = ranges.length > 0 ? ranges[0] : null;
PsiElement element = rangeMarker == null ? null : hostPsiFile.findElementAt(rangeMarker.getStartOffset());
if (element != null) {
enumerate(element, hostPsiFile, true, visitor);
}
}
/**
* @deprecated use {@link InjectedLanguageManager#enumerate(PsiElement, PsiLanguageInjectionHost.InjectedPsiVisitor)} instead
*/
@Deprecated
public static boolean enumerate(@NotNull PsiElement host, @NotNull PsiLanguageInjectionHost.InjectedPsiVisitor visitor) {
PsiFile containingFile = host.getContainingFile();
PsiUtilCore.ensureValid(containingFile);
return enumerate(host, containingFile, true, visitor);
}
/**
* @deprecated use {@link InjectedLanguageManager#enumerateEx(PsiElement, PsiFile, boolean, PsiLanguageInjectionHost.InjectedPsiVisitor)} instead
*/
@Deprecated
public static boolean enumerate(@NotNull PsiElement host,
@NotNull PsiFile containingFile,
boolean probeUp,
@NotNull PsiLanguageInjectionHost.InjectedPsiVisitor visitor) {
//do not inject into nonphysical files except during completion
if (!containingFile.isPhysical() && containingFile.getOriginalFile() == containingFile) {
final PsiElement context = InjectedLanguageManager.getInstance(containingFile.getProject()).getInjectionHost(containingFile);
if (context == null) return false;
final PsiFile file = context.getContainingFile();
if (file == null || !file.isPhysical() && file.getOriginalFile() == file) return false;
}
if (containingFile.getViewProvider() instanceof InjectedFileViewProvider) return false; // no injection inside injection
PsiElement inTree = loadTree(host, containingFile);
if (inTree != host) {
host = inTree;
containingFile = host.getContainingFile();
}
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(containingFile.getProject());
Document document = documentManager.getDocument(containingFile);
if (document == null || documentManager.isCommitted(document)) {
probeElementsUp(host, containingFile, probeUp, visitor);
}
return true;
}
/**
* Invocation of this method on uncommitted {@code file} can lead to unexpected results, including throwing an exception!
*/
@Contract("null,_->null;!null,_->!null")
public static Editor getEditorForInjectedLanguageNoCommit(@Nullable Editor editor, @Nullable PsiFile file) {
if (editor == null || file == null || editor instanceof EditorWindow) return editor;
int offset = editor.getCaretModel().getOffset();
return getEditorForInjectedLanguageNoCommit(editor, file, offset);
}
/**
* This is a quick check, that can be performed before committing document and invoking
* {@link #getEditorForInjectedLanguageNoCommit(Editor, Caret, PsiFile)} or other methods here, which don't work
* for uncommitted documents.
*/
static boolean mightHaveInjectedFragmentAtCaret(@NotNull Project project, @NotNull Document hostDocument, int hostOffset) {
PsiFile hostPsiFile = PsiDocumentManager.getInstance(project).getCachedPsiFile(hostDocument);
if (hostPsiFile == null || !hostPsiFile.isValid()) return false;
List<DocumentWindow> documents = InjectedLanguageManager.getInstance(project).getCachedInjectedDocumentsInRange(hostPsiFile, TextRange.create(hostOffset, hostOffset));
for (DocumentWindow document : documents) {
if (document.isValid() && document.getHostRange(hostOffset) != null) return true;
}
return false;
}
/**
* Invocation of this method on uncommitted {@code file} can lead to unexpected results, including throwing an exception!
*/
public static Editor getEditorForInjectedLanguageNoCommit(@Nullable Editor editor, @Nullable Caret caret, @Nullable PsiFile file) {
if (editor == null || file == null || editor instanceof EditorWindow || caret == null) return editor;
PsiFile injectedFile = findInjectedPsiNoCommit(file, caret.getOffset());
return getInjectedEditorForInjectedFile(editor, caret, injectedFile);
}
/**
* Invocation of this method on uncommitted {@code file} can lead to unexpected results, including throwing an exception!
*/
public static Caret getCaretForInjectedLanguageNoCommit(@Nullable Caret caret, @Nullable PsiFile file) {
if (caret == null || file == null || caret instanceof InjectedCaret) return caret;
PsiFile injectedFile = findInjectedPsiNoCommit(file, caret.getOffset());
Editor injectedEditor = getInjectedEditorForInjectedFile(caret.getEditor(), injectedFile);
if (!(injectedEditor instanceof EditorWindow)) {
return caret;
}
for (Caret injectedCaret : injectedEditor.getCaretModel().getAllCarets()) {
if (((InjectedCaret)injectedCaret).getDelegate() == caret) {
return injectedCaret;
}
}
return null;
}
/**
* Finds injected language in expression
*
* @param expression where to find
* @param classToFind class that represents language we look for
* @param <T> class that represents language we look for
* @return instance of class that represents language we look for or null of not found
*/
@Nullable
@SuppressWarnings("unchecked") // We check types dynamically (using isAssignableFrom)
public static <T extends PsiFileBase> T findInjectedFile(@NotNull final PsiElement expression,
@NotNull final Class<T> classToFind) {
final List<Pair<PsiElement, TextRange>> files =
InjectedLanguageManager.getInstance(expression.getProject()).getInjectedPsiFiles(expression);
if (files == null) {
return null;
}
for (final Pair<PsiElement, TextRange> fileInfo : files) {
final PsiElement injectedFile = fileInfo.first;
if (classToFind.isAssignableFrom(injectedFile.getClass())) {
return (T)injectedFile;
}
}
return null;
}
/**
* Invocation of this method on uncommitted {@code file} can lead to unexpected results, including throwing an exception!
*/
@Contract("null,_,_->null;!null,_,_->!null")
public static Editor getEditorForInjectedLanguageNoCommit(@Nullable Editor editor, @Nullable PsiFile file, final int offset) {
if (editor == null || file == null || editor instanceof EditorWindow) return editor;
PsiFile injectedFile = findInjectedPsiNoCommit(file, offset);
return getInjectedEditorForInjectedFile(editor, injectedFile);
}
@NotNull
public static Editor getInjectedEditorForInjectedFile(@NotNull Editor hostEditor, @Nullable final PsiFile injectedFile) {
return getInjectedEditorForInjectedFile(hostEditor, hostEditor.getCaretModel().getCurrentCaret(), injectedFile);
}
/**
* @param hostCaret if not {@code null}, take into account caret's selection (in case it's not contained completely in injected fragment,
* return host editor)
*/
@NotNull
public static Editor getInjectedEditorForInjectedFile(@NotNull Editor hostEditor,
@Nullable Caret hostCaret,
@Nullable final PsiFile injectedFile) {
if (injectedFile == null || hostEditor instanceof EditorWindow || hostEditor.isDisposed()) return hostEditor;
Project project = hostEditor.getProject();
if (project == null) project = injectedFile.getProject();
Document document = PsiDocumentManager.getInstance(project).getDocument(injectedFile);
if (!(document instanceof DocumentWindowImpl)) return hostEditor;
DocumentWindowImpl documentWindow = (DocumentWindowImpl)document;
if (hostCaret != null && hostCaret.hasSelection()) {
int selstart = hostCaret.getSelectionStart();
if (selstart != -1) {
int selend = Math.max(selstart, hostCaret.getSelectionEnd());
if (!documentWindow.containsRange(selstart, selend)) {
// selection spreads out the injected editor range
return hostEditor;
}
}
}
if (!documentWindow.isValid()) {
return hostEditor; // since the moment we got hold of injectedFile and this moment call, document may have been dirtied
}
return EditorWindowImpl.create(documentWindow, (EditorImpl)hostEditor, injectedFile);
}
/**
* Invocation of this method on uncommitted {@code host} can lead to unexpected results, including throwing an exception!
*/
@Nullable
public static PsiFile findInjectedPsiNoCommit(@NotNull PsiFile host, int offset) {
PsiElement injected = InjectedLanguageManager.getInstance(host.getProject()).findInjectedElementAt(host, offset);
return injected == null ? null : injected.getContainingFile();
}
/**
* Invocation of this method on uncommitted {@code file} can lead to unexpected results, including throwing an exception!
*/
// consider injected elements
public static PsiElement findElementAtNoCommit(@NotNull PsiFile file, int offset) {
FileViewProvider viewProvider = file.getViewProvider();
Trinity<PsiElement, PsiElement, Language> result = null;
if (!(viewProvider instanceof InjectedFileViewProvider)) {
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject());
result = tryOffset(file, offset, documentManager);
PsiElement injected = result.first;
if (injected != null) {
return injected;
}
}
Language baseLanguage = viewProvider.getBaseLanguage();
if (result != null && baseLanguage == result.third) {
return result.second; // already queried
}
return viewProvider.findElementAt(offset, baseLanguage);
}
// list of injected fragments injected into this psi element (can be several if some crazy injector calls startInjecting()/doneInjecting()/startInjecting()/doneInjecting())
private static final Key<Getter<InjectionResult>> INJECTED_PSI = Key.create("INJECTED_PSI");
private static void probeElementsUp(@NotNull PsiElement element,
@NotNull PsiFile hostPsiFile,
boolean probeUp,
@NotNull PsiLanguageInjectionHost.InjectedPsiVisitor visitor) {
element = skipNonInjectablePsi(element, probeUp);
if (element == null) return;
InjectedLanguageManagerImpl injectedManager = InjectedLanguageManagerImpl.getInstanceImpl(hostPsiFile.getProject());
InjectionResult result = null;
PsiElement current;
for (current = element; current != null && current != hostPsiFile && !(current instanceof PsiDirectory); ) {
ProgressManager.checkCanceled();
if ("EL".equals(current.getLanguage().getID())) break;
result = SoftReference.deref(current.getUserData(INJECTED_PSI));
if (result == null || !result.isModCountUpToDate(hostPsiFile) || !result.isValid()) {
result = injectedManager.processInPlaceInjectorsFor(hostPsiFile, current);
}
current = current.getParent();
if (result != null) {
if (result.files != null) {
for (PsiFile injectedPsiFile : result.files) {
Place place = getShreds(injectedPsiFile);
if (place.isValid()) {
// check that injections found intersect with queried element
boolean intersects = intersects(element, place);
if (intersects) {
visitor.visit(injectedPsiFile, place);
}
}
}
}
if (result.references != null && visitor instanceof InjectedReferenceVisitor) {
InjectedReferenceVisitor refVisitor = (InjectedReferenceVisitor)visitor;
for (Pair<ReferenceInjector, Place> pair : result.references) {
Place place = pair.getSecond();
if (place.isValid()) {
// check that injections found intersect with queried element
boolean intersects = intersects(element, place);
if (intersects) {
ReferenceInjector injector = pair.getFirst();
refVisitor.visitInjectedReference(injector, place);
}
}
}
}
break; // found injection, stop
}
if (!probeUp) {
break;
}
}
if (element != current && (probeUp || result != null)) {
cacheResults(element, current, hostPsiFile, result);
}
}
private static void cacheResults(@NotNull PsiElement from, @Nullable PsiElement upUntil, @NotNull PsiFile hostFile, @Nullable InjectionResult result) {
Getter<InjectionResult> cachedRef = result == null || result.isEmpty() ? getEmptyInjectionResult(hostFile) : new SoftReference<>(result);
for (PsiElement e = from; e != upUntil && e != null; e = e.getParent()) {
ProgressManager.checkCanceled();
e.putUserData(INJECTED_PSI, cachedRef);
}
}
@NotNull
private static InjectionResult getEmptyInjectionResult(@NotNull PsiFile host) {
return CachedValuesManager.getCachedValue(host, () ->
CachedValueProvider.Result.createSingleDependency(new InjectionResult(host, null, null),
PsiModificationTracker.MODIFICATION_COUNT));
}
/**
* We can only inject into injection hosts or their ancestors, so if we're sure there are no PsiLanguageInjectionHost descendants,
* we can skip that PSI safely.
*/
@Nullable
private static PsiElement skipNonInjectablePsi(@NotNull PsiElement element, boolean probeUp) {
if (!stopLookingForInjection(element) && element.getFirstChild() == null) {
if (!probeUp) return null;
element = element.getParent();
while (element != null && !stopLookingForInjection(element) && element.getFirstChild() == element.getLastChild()) {
element = element.getParent();
}
}
return element;
}
private static boolean stopLookingForInjection(@NotNull PsiElement element) {
return element instanceof PsiFileSystemItem || element instanceof PsiLanguageInjectionHost;
}
private static boolean intersects(@NotNull PsiElement hostElement, @NotNull Place place) {
TextRange hostElementRange = hostElement.getTextRange();
boolean intersects = false;
for (PsiLanguageInjectionHost.Shred shred : place) {
PsiLanguageInjectionHost shredHost = shred.getHost();
if (shredHost != null && shredHost.getTextRange().intersects(hostElementRange)) {
intersects = true;
break;
}
}
return intersects;
}
/**
* Invocation of this method on uncommitted {@code hostFile} can lead to unexpected results, including throwing an exception!
*/
static PsiElement findInjectedElementNoCommit(@NotNull PsiFile hostFile, final int offset) {
if (hostFile instanceof PsiCompiledElement) return null;
Project project = hostFile.getProject();
if (InjectedLanguageManager.getInstance(project).isInjectedFragment(hostFile)) return null;
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
Trinity<PsiElement, PsiElement, Language> result = tryOffset(hostFile, offset, documentManager);
return result.first;
}
// returns (injected psi, leaf element at the offset, language of the leaf element)
// since findElementAt() is expensive, we trying to reuse its result
@NotNull
private static Trinity<PsiElement, PsiElement, Language> tryOffset(@NotNull PsiFile hostFile,
final int offset,
@NotNull PsiDocumentManager documentManager) {
FileViewProvider provider = hostFile.getViewProvider();
Language leafLanguage = null;
PsiElement leafElement = null;
for (Language language : provider.getLanguages()) {
PsiElement element = provider.findElementAt(offset, language);
if (element != null) {
if (leafLanguage == null) {
leafLanguage = language;
leafElement = element;
}
PsiElement injected = findInside(element, hostFile, offset, documentManager);
if (injected != null) return Trinity.create(injected, element, language);
}
// maybe we are at the border between two psi elements, then try to find injection at the end of the left element
if (offset != 0 && (element == null || element.getTextRange().getStartOffset() == offset)) {
PsiElement leftElement = provider.findElementAt(offset - 1, language);
if (leftElement != null && leftElement.getTextRange().getEndOffset() == offset) {
PsiElement injected = findInside(leftElement, hostFile, offset, documentManager);
if (injected != null) return Trinity.create(injected, element, language);
}
}
}
return Trinity.create(null, leafElement, leafLanguage);
}
private static PsiElement findInside(@NotNull PsiElement element,
@NotNull PsiFile hostFile,
final int hostOffset,
@NotNull final PsiDocumentManager documentManager) {
final Ref<PsiElement> out = new Ref<>();
enumerate(element, hostFile, true, (injectedPsi, places) -> {
for (PsiLanguageInjectionHost.Shred place : places) {
TextRange hostRange = place.getHost().getTextRange();
if (hostRange.cutOut(place.getRangeInsideHost()).grown(1).contains(hostOffset)) {
DocumentWindowImpl document = (DocumentWindowImpl)documentManager.getCachedDocument(injectedPsi);
if (document == null) return;
int injectedOffset = document.hostToInjected(hostOffset);
PsiElement injElement = injectedPsi.findElementAt(injectedOffset);
out.set(injElement == null ? injectedPsi : injElement);
}
}
});
return out.get();
}
private static final Key<List<DocumentWindow>> INJECTED_DOCS_KEY = Key.create("INJECTED_DOCS_KEY");
/**
* @deprecated use {@link InjectedLanguageManager#getCachedInjectedDocumentsInRange(PsiFile, TextRange)} instead
*/
@NotNull
@Deprecated
public static ConcurrentList<DocumentWindow> getCachedInjectedDocuments(@NotNull PsiFile hostPsiFile) {
// modification of cachedInjectedDocuments must be under InjectedLanguageManagerImpl.ourInjectionPsiLock only
List<DocumentWindow> injected = hostPsiFile.getUserData(INJECTED_DOCS_KEY);
if (injected == null) {
injected = ((UserDataHolderEx)hostPsiFile).putUserDataIfAbsent(INJECTED_DOCS_KEY, ContainerUtil.createConcurrentList());
}
return (ConcurrentList<DocumentWindow>)injected;
}
@NotNull
static List<DocumentWindow> getCachedInjectedDocumentsInRange(@NotNull PsiFile hostPsiFile, @NotNull TextRange range) {
List<DocumentWindow> injected = getCachedInjectedDocuments(hostPsiFile);
return ContainerUtil.filter(injected, inj-> Arrays.stream(inj.getHostRanges()).anyMatch(range::intersects));
}
static void clearCachedInjectedFragmentsForFile(@NotNull PsiFile file) {
file.putUserData(INJECTED_DOCS_KEY, null);
}
static void clearCaches(@NotNull PsiFile injected, @NotNull DocumentWindowImpl documentWindow) {
VirtualFileWindowImpl virtualFile = (VirtualFileWindowImpl)injected.getVirtualFile();
PsiManagerEx psiManagerEx = (PsiManagerEx)injected.getManager();
if (psiManagerEx.getProject().isDisposed()) return;
DebugUtil.performPsiModification("injected clearCaches", () ->
psiManagerEx.getFileManager().setViewProvider(virtualFile, null));
VirtualFile delegate = virtualFile.getDelegate();
if (!delegate.isValid()) return;
FileViewProvider viewProvider = psiManagerEx.getFileManager().findCachedViewProvider(delegate);
if (viewProvider == null) return;
for (PsiFile hostFile : ((AbstractFileViewProvider)viewProvider).getCachedPsiFiles()) {
// modification of cachedInjectedDocuments must be under InjectedLanguageManagerImpl.ourInjectionPsiLock
synchronized (InjectedLanguageManagerImpl.ourInjectionPsiLock) {
List<DocumentWindow> cachedInjectedDocuments = getCachedInjectedDocuments(hostFile);
for (int i = cachedInjectedDocuments.size() - 1; i >= 0; i--) {
DocumentWindow cachedInjectedDocument = cachedInjectedDocuments.get(i);
if (cachedInjectedDocument == documentWindow) {
cachedInjectedDocuments.remove(i);
}
}
}
}
}
public static Editor openEditorFor(@NotNull PsiFile file, @NotNull Project project) {
Document document = PsiDocumentManager.getInstance(project).getDocument(file);
// may return editor injected in current selection in the host editor, not for the file passed as argument
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) {
return null;
}
if (virtualFile instanceof VirtualFileWindow) {
virtualFile = ((VirtualFileWindow)virtualFile).getDelegate();
}
Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, virtualFile, -1), false);
if (editor == null || editor instanceof EditorWindow || editor.isDisposed()) return editor;
if (document instanceof DocumentWindowImpl) {
return EditorWindowImpl.create((DocumentWindowImpl)document, (EditorImpl)editor, file);
}
return editor;
}
/**
* @deprecated use {@link InjectedLanguageManager#getTopLevelFile(PsiElement)} instead
*/
@Deprecated
public static PsiFile getTopLevelFile(@NotNull PsiElement element) {
PsiFile containingFile = element.getContainingFile();
if (containingFile == null) return null;
if (containingFile.getViewProvider() instanceof InjectedFileViewProvider) {
PsiElement host = InjectedLanguageManager.getInstance(containingFile.getProject()).getInjectionHost(containingFile);
if (host != null) containingFile = host.getContainingFile();
}
return containingFile;
}
@NotNull
public static Editor getTopLevelEditor(@NotNull Editor editor) {
return editor instanceof EditorWindow ? ((EditorWindow)editor).getDelegate() : editor;
}
public static boolean isInInjectedLanguagePrefixSuffix(@NotNull final PsiElement element) {
PsiFile injectedFile = element.getContainingFile();
if (injectedFile == null) return false;
Project project = injectedFile.getProject();
InjectedLanguageManager languageManager = InjectedLanguageManager.getInstance(project);
if (!languageManager.isInjectedFragment(injectedFile)) return false;
TextRange elementRange = element.getTextRange();
List<TextRange> edibles = languageManager.intersectWithAllEditableFragments(injectedFile, elementRange);
int combinedEdiblesLength = edibles.stream().mapToInt(TextRange::getLength).sum();
return combinedEdiblesLength != elementRange.getLength();
}
public static int hostToInjectedUnescaped(DocumentWindow window, int hostOffset) {
Place shreds = ((DocumentWindowImpl)window).getShreds();
Segment hostRangeMarker = shreds.get(0).getHostRangeMarker();
if (hostRangeMarker == null || hostOffset < hostRangeMarker.getStartOffset()) {
return shreds.get(0).getPrefix().length();
}
StringBuilder chars = new StringBuilder();
int unescaped = 0;
for (int i = 0; i < shreds.size(); i++, chars.setLength(0)) {
PsiLanguageInjectionHost.Shred shred = shreds.get(i);
int prefixLength = shred.getPrefix().length();
int suffixLength = shred.getSuffix().length();
PsiLanguageInjectionHost host = shred.getHost();
TextRange rangeInsideHost = shred.getRangeInsideHost();
LiteralTextEscaper<? extends PsiLanguageInjectionHost> escaper = host == null ? null : host.createLiteralTextEscaper();
unescaped += prefixLength;
Segment currentRange = shred.getHostRangeMarker();
if (currentRange == null) continue;
Segment nextRange = i == shreds.size() - 1 ? null : shreds.get(i + 1).getHostRangeMarker();
if (nextRange == null || hostOffset < nextRange.getStartOffset()) {
hostOffset = Math.min(hostOffset, currentRange.getEndOffset());
int inHost = hostOffset - currentRange.getStartOffset();
if (escaper != null && escaper.decode(rangeInsideHost, chars)) {
int found = ObjectUtils.binarySearch(
0, inHost, index -> Comparing.compare(escaper.getOffsetInHost(index, TextRange.create(0, host.getTextLength())), inHost));
return unescaped + (found >= 0 ? found : -found - 1);
}
return unescaped + inHost;
}
if (escaper != null && escaper.decode(rangeInsideHost, chars)) {
unescaped += chars.length();
}
else {
unescaped += currentRange.getEndOffset() - currentRange.getStartOffset();
}
unescaped += suffixLength;
}
return unescaped - shreds.get(shreds.size() - 1).getSuffix().length();
}
/**
* @deprecated Use {@link InjectedLanguageManager#getInjectedPsiFiles(PsiElement)} != null instead
*/
@Deprecated
public static boolean hasInjections(@NotNull PsiLanguageInjectionHost host) {
if (!host.isPhysical()) return false;
final Ref<Boolean> result = Ref.create(false);
enumerate(host, (injectedPsi, places) -> result.set(true));
return result.get().booleanValue();
}
public static String getUnescapedText(@NotNull PsiFile file, @Nullable final PsiElement startElement, @Nullable final PsiElement endElement) {
final InjectedLanguageManager manager = InjectedLanguageManager.getInstance(file.getProject());
if (manager.getInjectionHost(file) == null) {
return file.getText().substring(startElement == null ? 0 : startElement.getTextRange().getStartOffset(),
endElement == null ? file.getTextLength() : endElement.getTextRange().getStartOffset());
}
final StringBuilder sb = new StringBuilder();
file.accept(new PsiRecursiveElementWalkingVisitor() {
Boolean myState = startElement == null ? Boolean.TRUE : null;
@Override
public void visitElement(@NotNull PsiElement element) {
if (element == startElement) myState = Boolean.TRUE;
if (element == endElement) myState = Boolean.FALSE;
if (Boolean.FALSE == myState) return;
if (Boolean.TRUE == myState && element.getFirstChild() == null) {
sb.append(getUnescapedLeafText(element, false));
}
else {
super.visitElement(element);
}
}
});
return sb.toString();
}
@Nullable
public static String getUnescapedLeafText(PsiElement element, boolean strict) {
String unescaped = element.getCopyableUserData(LeafPatcher.UNESCAPED_TEXT);
if (unescaped != null) {
return unescaped;
}
if (!strict && element.getFirstChild() == null) {
return element.getText();
}
return null;
}
@Nullable
public static DocumentWindow getDocumentWindow(@NotNull PsiElement element) {
PsiFile file = element.getContainingFile();
if (file == null) return null;
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile instanceof VirtualFileWindow) return ((VirtualFileWindow)virtualFile).getDocumentWindow();
return null;
}
public static boolean isHighlightInjectionBackground(@Nullable PsiLanguageInjectionHost host) {
return !(host instanceof InjectionBackgroundSuppressor);
}
public static int getInjectedStart(@NotNull List<? extends PsiLanguageInjectionHost.Shred> places) {
PsiLanguageInjectionHost.Shred shred = places.get(0);
PsiLanguageInjectionHost host = shred.getHost();
assert host != null;
return shred.getRangeInsideHost().getStartOffset() + host.getTextRange().getStartOffset();
}
@Nullable
public static PsiElement findElementInInjected(@NotNull PsiLanguageInjectionHost injectionHost, final int offset) {
final Ref<PsiElement> ref = Ref.create();
enumerate(injectionHost, (injectedPsi, places) -> ref.set(injectedPsi.findElementAt(offset - getInjectedStart(places))));
return ref.get();
}
@Nullable
public static PsiLanguageInjectionHost findInjectionHost(@Nullable PsiElement psi) {
if (psi == null) return null;
PsiFile containingFile = psi.getContainingFile().getOriginalFile(); // * formatting
PsiElement fileContext = containingFile.getContext(); // * quick-edit-handler
if (fileContext instanceof PsiLanguageInjectionHost) return (PsiLanguageInjectionHost)fileContext;
Place shreds = getShreds(containingFile.getViewProvider()); // * injection-registrar
if (shreds == null) {
VirtualFile virtualFile = PsiUtilCore.getVirtualFile(containingFile);
if (virtualFile instanceof LightVirtualFile) {
virtualFile = ((LightVirtualFile)virtualFile).getOriginalFile(); // * dynamic files-from-text
}
if (virtualFile instanceof VirtualFileWindow) {
shreds = getShreds(((VirtualFileWindow)virtualFile).getDocumentWindow());
}
}
return shreds != null ? shreds.getHostPointer().getElement() : null;
}
@Nullable
public static PsiLanguageInjectionHost findInjectionHost(@Nullable VirtualFile virtualFile) {
return virtualFile instanceof VirtualFileWindow ?
getShreds(((VirtualFileWindow)virtualFile).getDocumentWindow()).getHostPointer().getElement() : null;
}
public static <T> void putInjectedFileUserData(@NotNull PsiElement element,
@NotNull Language language,
@NotNull Key<T> key,
@Nullable T value) {
PsiFile file = getCachedInjectedFileWithLanguage(element, language);
if (file != null) {
file.putUserData(key, value);
}
}
/**
* @deprecated use {@link #putInjectedFileUserData(PsiElement, Language, Key, Object)} instead
*/
@Deprecated
public static <T> void putInjectedFileUserData(MultiHostRegistrar registrar, Key<T> key, T value) {
DeprecatedMethodException.report("use putInjectedFileUserData(PsiElement, Language, Key, Object)} instead");
InjectionResult result = ((InjectionRegistrarImpl)registrar).getInjectedResult();
if (result != null && result.files != null) {
List<? extends PsiFile> files = result.files;
PsiFile file = files.get(files.size() - 1);
file.putUserData(key, value);
}
}
@Nullable
public static PsiFile getCachedInjectedFileWithLanguage(@NotNull PsiElement element, @NotNull Language language) {
if (!element.isValid()) return null;
PsiFile containingFile = element.getContainingFile();
if (containingFile == null || !containingFile.isValid()) return null;
return InjectedLanguageManager.getInstance(containingFile.getProject())
.getCachedInjectedDocumentsInRange(containingFile, element.getTextRange())
.stream()
.map(documentWindow -> PsiDocumentManager.getInstance(containingFile.getProject()).getPsiFile(documentWindow))
.filter(file -> file != null && file.getLanguage() == LanguageSubstitutors.getInstance()
.substituteLanguage(language, file.getVirtualFile(), file.getProject()))
.max(Comparator.comparingInt(PsiElement::getTextLength))
.orElse(null);
}
/**
* Start injecting the reference in {@code language} in this place.
* Unlike {@link MultiHostRegistrar#startInjecting(Language)} this method doesn't inject the full blown file in the other language.
* Instead, it just marks some range as a reference in some language.
* For example, you can inject file reference into string literal.
* After that, it won't be highlighted as an injected fragment but still can be subject to e.g. "Goto declaraion" action.
*/
public static void injectReference(@NotNull MultiHostRegistrar registrar,
@NotNull Language language,
@NotNull String prefix,
@NotNull String suffix,
@NotNull PsiLanguageInjectionHost host,
@NotNull TextRange rangeInsideHost) {
((InjectionRegistrarImpl)registrar).injectReference(language, prefix, suffix, host, rangeInsideHost);
}
// null means failed to reparse
public static BooleanRunnable reparse(@NotNull PsiFile injectedPsiFile,
@NotNull DocumentWindow injectedDocument,
@NotNull PsiFile hostPsiFile,
@NotNull Document hostDocument,
@NotNull FileViewProvider hostViewProvider,
@NotNull ProgressIndicator indicator,
@NotNull ASTNode oldRoot,
@NotNull ASTNode newRoot,
@NotNull PsiDocumentManagerBase documentManager) {
Language language = injectedPsiFile.getLanguage();
InjectedFileViewProvider provider = (InjectedFileViewProvider)injectedPsiFile.getViewProvider();
VirtualFile oldInjectedVFile = provider.getVirtualFile();
VirtualFile hostVirtualFile = hostViewProvider.getVirtualFile();
BooleanRunnable runnable = InjectionRegistrarImpl
.reparse(language, (DocumentWindowImpl)injectedDocument, injectedPsiFile, (VirtualFileWindow)oldInjectedVFile, hostVirtualFile, hostPsiFile,
(DocumentEx)hostDocument,
indicator, oldRoot, newRoot, documentManager);
if (runnable == null) {
EditorWindowImpl.disposeEditorFor(injectedDocument);
}
return runnable;
}
}
| |
package com.bramblellc.yoda.activities;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bramblellc.yoda.R;
import com.bramblellc.yoda.services.ActionConstants;
import com.bramblellc.yoda.services.NewsIntentService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Locale;
public class Landing extends Activity {
private IntentFilter intentFilter;
private LandingBroadcastReceiver receiver;
private RelativeLayout news1;
private RelativeLayout news2;
private RelativeLayout news3;
private RelativeLayout news4;
private RelativeLayout news5;
private TextView title1;
private TextView title2;
private TextView title3;
private TextView title4;
private TextView title5;
private TextView text1;
private TextView text2;
private TextView text3;
private TextView text4;
private TextView text5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.landing_layout);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
boolean finish = getIntent().getBooleanExtra("finish", false);
if (finish) {
Intent intent = new Intent(this, AccountPortal.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // To clean up all activities
startActivity(intent);
finish();
return;
}
intentFilter = new IntentFilter(ActionConstants.NEWS_ACTION);
receiver = new LandingBroadcastReceiver();
news1 = (RelativeLayout) findViewById(R.id.news1);
news2 = (RelativeLayout) findViewById(R.id.news2);
news3 = (RelativeLayout) findViewById(R.id.news3);
news4 = (RelativeLayout) findViewById(R.id.news4);
news5 = (RelativeLayout) findViewById(R.id.news5);
title1 = (TextView) findViewById(R.id.title1);
title2 = (TextView) findViewById(R.id.title2);
title3 = (TextView) findViewById(R.id.title3);
title4 = (TextView) findViewById(R.id.title4);
title5 = (TextView) findViewById(R.id.title5);
text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
text3 = (TextView) findViewById(R.id.text3);
text4 = (TextView) findViewById(R.id.text4);
text5 = (TextView) findViewById(R.id.text5);
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);
Intent localIntent = new Intent(this, NewsIntentService.class);
startService(localIntent);
}
public void settingsPressed(View v){
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
finish();
}
public void alertsPressed(View v) {
Intent intent = new Intent(this, Alerts.class);
startActivity(intent);
finish();
}
private class LandingBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean successful = intent.getBooleanExtra("successful", false);
if (!successful) {
Toast.makeText(Landing.this, ":(", Toast.LENGTH_SHORT).show();
}
else {
try {
String content = intent.getStringExtra("content");
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("news");
String len = Locale.getDefault().getLanguage();
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println(i);
JSONObject item = jsonArray.getJSONObject(i);
JSONArray posts = item.getJSONArray("posts");
JSONObject post1 = (JSONObject) posts.get(0);
JSONObject post2 = (JSONObject) posts.get(1);
boolean postone = false;
if (len.equals(post1.getString("lang"))) {
postone = true;
}
if (i == 0) {
if (postone) {
title1.setText(post1.getString("title"));
text1.setText(post1.getString("body"));
}
else {
title1.setText(post2.getString("title"));
text1.setText(post2.getString("body"));
}
news1.setVisibility(View.VISIBLE);
}
else if (i == 1) {
if (postone) {
title2.setText(post1.getString("title"));
text2.setText(post1.getString("body"));
}
else {
title2.setText(post2.getString("title"));
text2.setText(post2.getString("body"));
}
news2.setVisibility(View.VISIBLE);
}
else if (i == 2) {
if (postone) {
title3.setText(post1.getString("title"));
text3.setText(post1.getString("body"));
}
else {
title3.setText(post2.getString("title"));
text3.setText(post2.getString("body"));
}
news3.setVisibility(View.VISIBLE);
}
else if (i == 3) {
if (postone) {
title4.setText(post1.getString("title"));
text4.setText(post1.getString("body"));
}
else {
title4.setText(post2.getString("title"));
text4.setText(post2.getString("body"));
}
news4.setVisibility(View.VISIBLE);
}
else {
if (postone) {
title5.setText(post1.getString("title"));
text5.setText(post1.getString("body"));
}
else {
title5.setText(post2.getString("title"));
text5.setText(post2.getString("body"));
}
news5.setVisibility(View.VISIBLE);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
LocalBroadcastManager.getInstance(Landing.this).unregisterReceiver(receiver);
}
}
public void btn1(View view) {
Intent intent = new Intent(this, News.class);
intent.putExtra("title",title1.getText().toString());
intent.putExtra("text",text1.getText().toString());
startActivity(intent);
finish();
}
public void btn2(View view) {
Intent intent = new Intent(this, News.class);
intent.putExtra("title",title2.getText().toString());
intent.putExtra("text",text2.getText().toString());
startActivity(intent);
finish();
}
public void btn3(View view) {
Intent intent = new Intent(this, News.class);
intent.putExtra("title",title3.getText().toString());
intent.putExtra("text",text3.getText().toString());
startActivity(intent);
finish();
}
public void btn4(View view) {
Intent intent = new Intent(this, News.class);
intent.putExtra("title",title4.getText().toString());
intent.putExtra("text",text4.getText().toString());
startActivity(intent);
finish();
}
public void btn5(View view) {
Intent intent = new Intent(this, News.class);
intent.putExtra("title",title5.getText().toString());
intent.putExtra("text",text5.getText().toString());
startActivity(intent);
finish();
}
}
| |
/*
* Copyright (C) 2015 Christopher Friedt <chrisfriedt@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sliderule.stats;
/**
* <p><b>Student's <i>t</i>-Distribution</b></p>
*
* <p>This class provides a time-efficient means for querying values and
* inverse values from the
* <a href="http://en.wikipedia.org/wiki/Cumulative_distribution_function">cumulative distribution function (CDF)</a>
* of
* <a href="http://en.wikipedia.org/wiki/Student%27s_t-distribution">Student's <i>t</i>-distribution</a>.
* Also provided is a method to find the {@link #bounds} for a given
* <a href="http://en.wikipedia.org/wiki/Confidence_interval">confidence interval</a>
* as well as a method to {@link #test} sample statistics - i.e. perform
* <a href="http://en.wikipedia.org/wiki/Student's_t-test">Student's <i>t</i>-test</a>.</p>
*
* <p>Note, the {@link #test} is not sufficient to show that the random
* variable approximately described by sample statistics is actually
* {@link Normal}.
* For that purpose, Please see {@link ChiSquared}.
* </p>
* @author <a href="mailto:chrisfriedt@gmail.com">Christopher Friedt</a>
* @see
* <ul>
* <li>Wikipedia: <a href="http://en.wikipedia.org/wiki/Student%27s_t-distribution">Student's t-distribution</a></li>
* <li>Chapra, Steven C., and Canale, Raymond P. Numerical Methods for Engineers, 4th Ed. Toronto: McGraw-Hill, 2002. pp 435. Print.</li>
* <li>DeGroot, Morris H., and Schervish, Mark J. Probability and Statistics, 3rd Ed. Toronto: Addison-Wesley, 2002. pp. 404-416,776-777. Print.</li>
* </ul>
*/
public final class StudentsT {
// produced via Matlab's tinv function
private static final double xp[] = { 0.55, 0.60, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95, 0.975, 0.99, 0.995, };
private static final double xtable[][] = {
{ 0.158384, 0.324920, 0.509525, 0.726543, 1.000000, 1.376382, 1.962611, 3.077684, 6.313752, 12.706205, 31.820516, 63.656741, },
{ 0.142134, 0.288675, 0.444750, 0.617213, 0.816497, 1.060660, 1.386207, 1.885618, 2.919986, 4.302653, 6.964557, 9.924843, },
{ 0.136598, 0.276671, 0.424202, 0.584390, 0.764892, 0.978472, 1.249778, 1.637744, 2.353363, 3.182446, 4.540703, 5.840909, },
{ 0.133830, 0.270722, 0.414163, 0.568649, 0.740697, 0.940965, 1.189567, 1.533206, 2.131847, 2.776445, 3.746947, 4.604095, },
{ 0.132175, 0.267181, 0.408229, 0.559430, 0.726687, 0.919544, 1.155767, 1.475884, 2.015048, 2.570582, 3.364930, 4.032143, },
{ 0.131076, 0.264835, 0.404313, 0.553381, 0.717558, 0.905703, 1.134157, 1.439756, 1.943180, 2.446912, 3.142668, 3.707428, },
{ 0.130293, 0.263167, 0.401538, 0.549110, 0.711142, 0.896030, 1.119159, 1.414924, 1.894579, 2.364624, 2.997952, 3.499483, },
{ 0.129707, 0.261921, 0.399469, 0.545934, 0.706387, 0.888890, 1.108145, 1.396815, 1.859548, 2.306004, 2.896459, 3.355387, },
{ 0.129253, 0.260955, 0.397868, 0.543480, 0.702722, 0.883404, 1.099716, 1.383029, 1.833113, 2.262157, 2.821438, 3.249836, },
{ 0.128890, 0.260185, 0.396591, 0.541528, 0.699812, 0.879058, 1.093058, 1.372184, 1.812461, 2.228139, 2.763769, 3.169273, },
{ 0.128594, 0.259556, 0.395551, 0.539938, 0.697445, 0.875530, 1.087666, 1.363430, 1.795885, 2.200985, 2.718079, 3.105807, },
{ 0.128347, 0.259033, 0.394686, 0.538618, 0.695483, 0.872609, 1.083211, 1.356217, 1.782288, 2.178813, 2.680998, 3.054540, },
{ 0.128139, 0.258591, 0.393955, 0.537504, 0.693829, 0.870152, 1.079469, 1.350171, 1.770933, 2.160369, 2.650309, 3.012276, },
{ 0.127961, 0.258213, 0.393331, 0.536552, 0.692417, 0.868055, 1.076280, 1.345030, 1.761310, 2.144787, 2.624494, 2.976843, },
{ 0.127806, 0.257885, 0.392790, 0.535729, 0.691197, 0.866245, 1.073531, 1.340606, 1.753050, 2.131450, 2.602480, 2.946713, },
{ 0.127671, 0.257599, 0.392318, 0.535010, 0.690132, 0.864667, 1.071137, 1.336757, 1.745884, 2.119905, 2.583487, 2.920782, },
{ 0.127552, 0.257347, 0.391902, 0.534377, 0.689195, 0.863279, 1.069033, 1.333379, 1.739607, 2.109816, 2.566934, 2.898231, },
{ 0.127447, 0.257123, 0.391533, 0.533816, 0.688364, 0.862049, 1.067170, 1.330391, 1.734064, 2.100922, 2.552380, 2.878440, },
{ 0.127352, 0.256923, 0.391202, 0.533314, 0.687621, 0.860951, 1.065507, 1.327728, 1.729133, 2.093024, 2.539483, 2.860935, },
{ 0.127267, 0.256743, 0.390906, 0.532863, 0.686954, 0.859964, 1.064016, 1.325341, 1.724718, 2.085963, 2.527977, 2.845340, },
{ 0.127190, 0.256580, 0.390637, 0.532455, 0.686352, 0.859074, 1.062670, 1.323188, 1.720743, 2.079614, 2.517648, 2.831360, },
{ 0.127120, 0.256432, 0.390394, 0.532085, 0.685805, 0.858266, 1.061449, 1.321237, 1.717144, 2.073873, 2.508325, 2.818756, },
{ 0.127056, 0.256297, 0.390171, 0.531747, 0.685306, 0.857530, 1.060337, 1.319460, 1.713872, 2.068658, 2.499867, 2.807336, },
{ 0.126998, 0.256173, 0.389967, 0.531438, 0.684850, 0.856855, 1.059319, 1.317836, 1.710882, 2.063899, 2.492159, 2.796940, },
{ 0.126944, 0.256060, 0.389780, 0.531154, 0.684430, 0.856236, 1.058384, 1.316345, 1.708141, 2.059539, 2.485107, 2.787436, },
{ 0.126895, 0.255955, 0.389607, 0.530892, 0.684043, 0.855665, 1.057523, 1.314972, 1.705618, 2.055529, 2.478630, 2.778715, },
{ 0.126849, 0.255858, 0.389448, 0.530649, 0.683685, 0.855137, 1.056727, 1.313703, 1.703288, 2.051831, 2.472660, 2.770683, },
{ 0.126806, 0.255768, 0.389299, 0.530424, 0.683353, 0.854647, 1.055989, 1.312527, 1.701131, 2.048407, 2.467140, 2.763262, },
{ 0.126767, 0.255684, 0.389161, 0.530214, 0.683044, 0.854192, 1.055302, 1.311434, 1.699127, 2.045230, 2.462021, 2.756386, },
{ 0.126730, 0.255605, 0.389032, 0.530019, 0.682756, 0.853767, 1.054662, 1.310415, 1.697261, 2.042272, 2.457262, 2.749996, },
{ 0.126695, 0.255532, 0.388912, 0.529836, 0.682486, 0.853370, 1.054064, 1.309464, 1.695519, 2.039513, 2.452824, 2.744042, },
{ 0.126663, 0.255464, 0.388799, 0.529665, 0.682234, 0.852998, 1.053504, 1.308573, 1.693889, 2.036933, 2.448678, 2.738481, },
{ 0.126632, 0.255399, 0.388693, 0.529504, 0.681997, 0.852649, 1.052979, 1.307737, 1.692360, 2.034515, 2.444794, 2.733277, },
{ 0.126603, 0.255339, 0.388593, 0.529353, 0.681774, 0.852321, 1.052485, 1.306952, 1.690924, 2.032245, 2.441150, 2.728394, },
{ 0.126576, 0.255281, 0.388499, 0.529211, 0.681564, 0.852012, 1.052019, 1.306212, 1.689572, 2.030108, 2.437723, 2.723806, },
{ 0.126551, 0.255227, 0.388410, 0.529076, 0.681366, 0.851720, 1.051580, 1.305514, 1.688298, 2.028094, 2.434494, 2.719485, },
{ 0.126527, 0.255176, 0.388326, 0.528949, 0.681178, 0.851444, 1.051165, 1.304854, 1.687094, 2.026192, 2.431447, 2.715409, },
{ 0.126504, 0.255128, 0.388247, 0.528828, 0.681001, 0.851183, 1.050772, 1.304230, 1.685954, 2.024394, 2.428568, 2.711558, },
{ 0.126482, 0.255082, 0.388171, 0.528714, 0.680833, 0.850935, 1.050399, 1.303639, 1.684875, 2.022691, 2.425841, 2.707913, },
{ 0.126462, 0.255039, 0.388100, 0.528606, 0.680673, 0.850700, 1.050046, 1.303077, 1.683851, 2.021075, 2.423257, 2.704459, },
{ 0.126442, 0.254997, 0.388032, 0.528502, 0.680521, 0.850476, 1.049710, 1.302543, 1.682878, 2.019541, 2.420803, 2.701181, },
{ 0.126423, 0.254958, 0.387967, 0.528404, 0.680376, 0.850263, 1.049390, 1.302035, 1.681952, 2.018082, 2.418470, 2.698066, },
{ 0.126406, 0.254920, 0.387905, 0.528311, 0.680238, 0.850060, 1.049085, 1.301552, 1.681071, 2.016692, 2.416250, 2.695102, },
{ 0.126389, 0.254884, 0.387846, 0.528221, 0.680107, 0.849867, 1.048794, 1.301090, 1.680230, 2.015368, 2.414134, 2.692278, },
{ 0.126373, 0.254850, 0.387790, 0.528136, 0.679981, 0.849682, 1.048516, 1.300649, 1.679427, 2.014103, 2.412116, 2.689585, },
{ 0.126357, 0.254817, 0.387736, 0.528054, 0.679861, 0.849505, 1.048250, 1.300228, 1.678660, 2.012896, 2.410188, 2.687013, },
{ 0.126342, 0.254786, 0.387684, 0.527976, 0.679746, 0.849336, 1.047996, 1.299825, 1.677927, 2.011741, 2.408345, 2.684556, },
{ 0.126328, 0.254756, 0.387635, 0.527901, 0.679635, 0.849174, 1.047752, 1.299439, 1.677224, 2.010635, 2.406581, 2.682204, },
{ 0.126314, 0.254727, 0.387587, 0.527829, 0.679530, 0.849018, 1.047519, 1.299069, 1.676551, 2.009575, 2.404892, 2.679952, },
{ 0.126301, 0.254699, 0.387542, 0.527760, 0.679428, 0.848869, 1.047295, 1.298714, 1.675905, 2.008559, 2.403272, 2.677793, },
{ 0.126289, 0.254673, 0.387498, 0.527694, 0.679331, 0.848726, 1.047080, 1.298373, 1.675285, 2.007584, 2.401718, 2.675722, },
{ 0.126277, 0.254647, 0.387456, 0.527631, 0.679237, 0.848588, 1.046873, 1.298045, 1.674689, 2.006647, 2.400225, 2.673734, },
{ 0.126265, 0.254623, 0.387416, 0.527569, 0.679147, 0.848456, 1.046674, 1.297730, 1.674116, 2.005746, 2.398790, 2.671823, },
{ 0.126254, 0.254599, 0.387377, 0.527510, 0.679060, 0.848328, 1.046483, 1.297426, 1.673565, 2.004879, 2.397410, 2.669985, },
{ 0.126243, 0.254576, 0.387339, 0.527454, 0.678977, 0.848205, 1.046298, 1.297134, 1.673034, 2.004045, 2.396081, 2.668216, },
{ 0.126233, 0.254554, 0.387303, 0.527399, 0.678896, 0.848087, 1.046120, 1.296853, 1.672522, 2.003241, 2.394801, 2.666512, },
{ 0.126222, 0.254533, 0.387268, 0.527346, 0.678818, 0.847973, 1.045949, 1.296581, 1.672029, 2.002465, 2.393568, 2.664870, },
{ 0.126213, 0.254512, 0.387234, 0.527295, 0.678743, 0.847862, 1.045783, 1.296319, 1.671553, 2.001717, 2.392377, 2.663287, },
{ 0.126203, 0.254493, 0.387202, 0.527246, 0.678671, 0.847756, 1.045623, 1.296066, 1.671093, 2.000995, 2.391229, 2.661759, },
{ 0.126194, 0.254473, 0.387170, 0.527198, 0.678601, 0.847653, 1.045469, 1.295821, 1.670649, 2.000298, 2.390119, 2.660283, },
{ 0.126186, 0.254455, 0.387140, 0.527152, 0.678533, 0.847553, 1.045320, 1.295585, 1.670219, 1.999624, 2.389047, 2.658857, },
{ 0.126177, 0.254437, 0.387111, 0.527108, 0.678467, 0.847457, 1.045175, 1.295356, 1.669804, 1.998972, 2.388011, 2.657479, },
{ 0.126169, 0.254420, 0.387082, 0.527064, 0.678404, 0.847364, 1.045035, 1.295134, 1.669402, 1.998341, 2.387008, 2.656145, },
{ 0.126161, 0.254403, 0.387054, 0.527023, 0.678342, 0.847274, 1.044900, 1.294920, 1.669013, 1.997730, 2.386037, 2.654854, },
{ 0.126153, 0.254387, 0.387028, 0.526982, 0.678283, 0.847186, 1.044768, 1.294712, 1.668636, 1.997138, 2.385097, 2.653604, },
{ 0.126146, 0.254371, 0.387002, 0.526943, 0.678225, 0.847101, 1.044641, 1.294511, 1.668271, 1.996564, 2.384186, 2.652394, },
{ 0.126139, 0.254355, 0.386977, 0.526905, 0.678169, 0.847019, 1.044518, 1.294315, 1.667916, 1.996008, 2.383302, 2.651220, },
{ 0.126132, 0.254341, 0.386952, 0.526868, 0.678115, 0.846939, 1.044398, 1.294126, 1.667572, 1.995469, 2.382446, 2.650081, },
{ 0.126125, 0.254326, 0.386928, 0.526832, 0.678062, 0.846862, 1.044281, 1.293942, 1.667239, 1.994945, 2.381615, 2.648977, },
{ 0.126118, 0.254312, 0.386905, 0.526797, 0.678011, 0.846786, 1.044169, 1.293763, 1.666914, 1.994437, 2.380807, 2.647905, },
{ 0.126112, 0.254299, 0.386883, 0.526763, 0.677961, 0.846713, 1.044059, 1.293589, 1.666600, 1.993943, 2.380024, 2.646863, },
{ 0.126105, 0.254285, 0.386861, 0.526730, 0.677912, 0.846642, 1.043952, 1.293421, 1.666294, 1.993464, 2.379262, 2.645852, },
{ 0.126099, 0.254272, 0.386840, 0.526698, 0.677865, 0.846573, 1.043848, 1.293256, 1.665996, 1.992997, 2.378522, 2.644869, },
{ 0.126093, 0.254260, 0.386819, 0.526667, 0.677820, 0.846506, 1.043747, 1.293097, 1.665707, 1.992543, 2.377802, 2.643913, },
{ 0.126088, 0.254248, 0.386799, 0.526637, 0.677775, 0.846440, 1.043649, 1.292941, 1.665425, 1.992102, 2.377102, 2.642983, },
{ 0.126082, 0.254236, 0.386780, 0.526607, 0.677732, 0.846376, 1.043554, 1.292790, 1.665151, 1.991673, 2.376420, 2.642078, },
{ 0.126076, 0.254224, 0.386761, 0.526578, 0.677689, 0.846314, 1.043461, 1.292643, 1.664885, 1.991254, 2.375757, 2.641198, },
{ 0.126071, 0.254213, 0.386742, 0.526550, 0.677648, 0.846254, 1.043370, 1.292500, 1.664625, 1.990847, 2.375111, 2.640340, },
{ 0.126066, 0.254202, 0.386724, 0.526523, 0.677608, 0.846195, 1.043282, 1.292360, 1.664371, 1.990450, 2.374482, 2.639505, },
{ 0.126061, 0.254191, 0.386707, 0.526497, 0.677569, 0.846137, 1.043195, 1.292224, 1.664125, 1.990063, 2.373868, 2.638691, },
{ 0.126056, 0.254181, 0.386690, 0.526471, 0.677531, 0.846081, 1.043111, 1.292091, 1.663884, 1.989686, 2.373270, 2.637897, },
{ 0.126051, 0.254171, 0.386673, 0.526445, 0.677493, 0.846027, 1.043029, 1.291961, 1.663649, 1.989319, 2.372687, 2.637123, },
{ 0.126046, 0.254161, 0.386657, 0.526421, 0.677457, 0.845973, 1.042949, 1.291835, 1.663420, 1.988960, 2.372119, 2.636369, },
{ 0.126042, 0.254151, 0.386641, 0.526396, 0.677422, 0.845921, 1.042871, 1.291711, 1.663197, 1.988610, 2.371564, 2.635632, },
{ 0.126037, 0.254142, 0.386625, 0.526373, 0.677387, 0.845870, 1.042795, 1.291591, 1.662978, 1.988268, 2.371022, 2.634914, },
{ 0.126033, 0.254132, 0.386610, 0.526350, 0.677353, 0.845821, 1.042721, 1.291473, 1.662765, 1.987934, 2.370493, 2.634212, },
{ 0.126029, 0.254123, 0.386595, 0.526327, 0.677320, 0.845772, 1.042648, 1.291358, 1.662557, 1.987608, 2.369977, 2.633527, },
{ 0.126025, 0.254114, 0.386580, 0.526305, 0.677288, 0.845725, 1.042577, 1.291246, 1.662354, 1.987290, 2.369472, 2.632858, },
{ 0.126020, 0.254106, 0.386566, 0.526284, 0.677256, 0.845679, 1.042508, 1.291136, 1.662155, 1.986979, 2.368979, 2.632204, },
{ 0.126016, 0.254097, 0.386552, 0.526263, 0.677225, 0.845633, 1.042440, 1.291029, 1.661961, 1.986675, 2.368497, 2.631565, },
{ 0.126013, 0.254089, 0.386539, 0.526242, 0.677195, 0.845589, 1.042373, 1.290924, 1.661771, 1.986377, 2.368026, 2.630940, },
{ 0.126009, 0.254081, 0.386526, 0.526222, 0.677166, 0.845546, 1.042308, 1.290821, 1.661585, 1.986086, 2.367566, 2.630330, },
{ 0.126005, 0.254073, 0.386513, 0.526203, 0.677137, 0.845503, 1.042245, 1.290721, 1.661404, 1.985802, 2.367115, 2.629732, },
{ 0.126001, 0.254065, 0.386500, 0.526184, 0.677109, 0.845462, 1.042183, 1.290623, 1.661226, 1.985523, 2.366674, 2.629148, },
{ 0.125998, 0.254058, 0.386487, 0.526165, 0.677081, 0.845421, 1.042122, 1.290527, 1.661052, 1.985251, 2.366243, 2.628576, },
{ 0.125994, 0.254050, 0.386475, 0.526146, 0.677054, 0.845381, 1.042062, 1.290432, 1.660881, 1.984984, 2.365821, 2.628016, },
{ 0.125991, 0.254043, 0.386463, 0.526128, 0.677027, 0.845343, 1.042004, 1.290340, 1.660715, 1.984723, 2.365407, 2.627468, },
{ 0.125987, 0.254036, 0.386452, 0.526111, 0.677001, 0.845304, 1.041947, 1.290250, 1.660551, 1.984467, 2.365002, 2.626931, },
{ 0.125984, 0.254029, 0.386440, 0.526093, 0.676976, 0.845267, 1.041891, 1.290161, 1.660391, 1.984217, 2.364606, 2.626405, },
{ 0.125981, 0.254022, 0.386429, 0.526076, 0.676951, 0.845230, 1.041836, 1.290075, 1.660234, 1.983972, 2.364217, 2.625891, },
{ 0.125978, 0.254015, 0.386418, 0.526060, 0.676927, 0.845195, 1.041782, 1.289990, 1.660081, 1.983731, 2.363837, 2.625386, },
{ 0.125975, 0.254009, 0.386407, 0.526043, 0.676903, 0.845159, 1.041729, 1.289907, 1.659930, 1.983495, 2.363464, 2.624891, },
{ 0.125972, 0.254002, 0.386397, 0.526027, 0.676879, 0.845125, 1.041678, 1.289825, 1.659782, 1.983264, 2.363098, 2.624407, },
{ 0.125969, 0.253996, 0.386386, 0.526012, 0.676856, 0.845091, 1.041627, 1.289745, 1.659637, 1.983038, 2.362739, 2.623932, },
{ 0.125966, 0.253990, 0.386376, 0.525996, 0.676833, 0.845058, 1.041577, 1.289666, 1.659495, 1.982815, 2.362388, 2.623465, },
{ 0.125963, 0.253984, 0.386366, 0.525981, 0.676811, 0.845025, 1.041529, 1.289589, 1.659356, 1.982597, 2.362043, 2.623008, },
{ 0.125960, 0.253978, 0.386356, 0.525966, 0.676790, 0.844993, 1.041481, 1.289514, 1.659219, 1.982383, 2.361704, 2.622560, },
{ 0.125957, 0.253972, 0.386347, 0.525952, 0.676768, 0.844962, 1.041434, 1.289439, 1.659085, 1.982173, 2.361372, 2.622120, },
{ 0.125954, 0.253966, 0.386337, 0.525938, 0.676747, 0.844931, 1.041388, 1.289367, 1.658953, 1.981967, 2.361046, 2.621688, },
{ 0.125952, 0.253961, 0.386328, 0.525924, 0.676727, 0.844901, 1.041342, 1.289295, 1.658824, 1.981765, 2.360726, 2.621265, },
{ 0.125949, 0.253955, 0.386319, 0.525910, 0.676706, 0.844871, 1.041298, 1.289225, 1.658697, 1.981567, 2.360412, 2.620849, },
{ 0.125947, 0.253950, 0.386310, 0.525896, 0.676687, 0.844842, 1.041254, 1.289156, 1.658573, 1.981372, 2.360104, 2.620440, },
{ 0.125944, 0.253944, 0.386301, 0.525883, 0.676667, 0.844814, 1.041212, 1.289088, 1.658450, 1.981180, 2.359801, 2.620039, },
{ 0.125942, 0.253939, 0.386293, 0.525870, 0.676648, 0.844786, 1.041169, 1.289022, 1.658330, 1.980992, 2.359504, 2.619645, },
{ 0.125939, 0.253934, 0.386284, 0.525857, 0.676629, 0.844758, 1.041128, 1.288957, 1.658212, 1.980808, 2.359212, 2.619258, },
{ 0.125937, 0.253929, 0.386276, 0.525845, 0.676611, 0.844731, 1.041087, 1.288892, 1.658096, 1.980626, 2.358924, 2.618878, },
{ 0.125934, 0.253924, 0.386268, 0.525832, 0.676592, 0.844704, 1.041047, 1.288829, 1.657982, 1.980448, 2.358642, 2.618504, },
{ 0.125932, 0.253919, 0.386260, 0.525820, 0.676575, 0.844678, 1.041008, 1.288767, 1.657870, 1.980272, 2.358365, 2.618137, },
{ 0.125930, 0.253914, 0.386252, 0.525808, 0.676557, 0.844652, 1.040970, 1.288706, 1.657759, 1.980100, 2.358093, 2.617776, },
{ 0.125928, 0.253910, 0.386244, 0.525796, 0.676540, 0.844627, 1.040932, 1.288646, 1.657651, 1.979930, 2.357825, 2.617421, },
};
private StudentsT() {}
/**
* Evaluate the cumulative distribution function of the {@link StudentsT}
* distribution.
* @param n sample size such that there are {@code n-1} degrees of freedom. {@code 2 <= n}
* @param x value of random variable {@code X}
* @return {@code p = Pr( X <= x | n-1 )}
*/
public static double cdf( int n, double x ) {
if ( n < 2 ) {
throw new IllegalArgumentException();
}
// values converge after this point
n = ( n >= xtable.length - 1 ) ? xtable.length - 1 : n;
// Use symmetry property rather than double size of xtable
boolean negative = x < 0;
x = negative ? -x : x;
double r = 0.5D;
double[] xrow = xtable[ n - 2 ];
int i=0;
for( double xx: xrow ) {
if ( xx < x ) {
double alpha = 2 * ( 1 - xp[ i ] );
r = 1 - alpha;
i++;
} else {
break;
}
}
r = negative ? ( 1 - r ) : r;
return r;
}
/**
* Evaluate the inverse of the cumulative distribution function of the
* {@link StudentsT} distribution.
* @param n sample size such that there are {@code n-1} degrees of freedom.{@code 2 <= n}
* @param p level of confidence. {@code 0 <= p <= 1}
* @return {@code x} ∋ {@code Pr( X <= x | n-1 ) = p}
*/
public static double inv( int n, double p ) {
if ( p < 0 || p > 1 ) {
throw new IllegalArgumentException();
}
if ( n < 2 ) {
throw new IllegalArgumentException();
}
// values converge after this point
n = ( n >= xtable.length - 1 ) ? xtable.length - 1 : n;
double r = 0;
boolean negative = p < 0.50;
double alpha = negative ? p : ( 1D - p );
double half_alpha = alpha / 2;
double pvalue = 1 - half_alpha;
double[] xrow = xtable[ n - 2 ];
int i;
for( i=0; i < xp.length; i++ ) {
if ( pvalue < xp[ i ] ) {
break;
}
}
r = negative ? -xrow[ i ] : xrow[ i ];
return r;
}
/**
* Determine the confidence interval for sample statistics, assuming that
* the random variable they approximately describe is {@link Normal}.
* @param n sample size such that there are {@code n-1} degrees of freedom. {@code 2 <= n}
* @param p level of confidence. {@code 0 <= p <= 1}
* @param u sample mean.
* @param o sample variance.
* @return {@code [ L, U ]} ∈ {@code Pr( L <= u <= U ) >= p }
*/
public static double[] bounds( int n, double p, double u, double o ) {
if ( n < 2 ) {
throw new IllegalArgumentException();
}
if ( p < 0 || p > 1 ) {
throw new IllegalArgumentException();
}
if ( o < 0 ) {
throw new IllegalArgumentException();
}
double sqrt_n = Math.sqrt( (double)n );
double t = inv( n, p );
double L = u - o / sqrt_n * t;
double U = u + o / sqrt_n * t;
return new double[] { L, U };
}
/**
* <p>Test sample statistics for a given confidence level, assuming that the
* random variable they approximately describe is {@link Normal}.</p>
* @param n sample size such that there are {@code n-1} degrees of freedom. {@code 2 <= n}
* @param p level of confidence. {@code 0 <= p <= 1}
* @param u sample mean.
* @param o sample variance.
* @return {@code [ L, U ]} ∈ {@code Pr( L <= u <= U ) >= p }
*/
public static boolean test( int n, double p, double u, double o ) {
double[] bounds = bounds( n, p, u, o );
double L = bounds[0];
double U = bounds[1];
return u >= L && u <= U;
}
}
| |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2006, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ---------------
* TimeSeries.java
* ---------------
* (C) Copyright 2001-2006, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Bryan Scott;
*
* $Id: TimeSeries.java,v 1.10.2.10 2007/01/17 15:08:40 mungady Exp $
*
* Changes
* -------
* 11-Oct-2001 : Version 1 (DG);
* 14-Nov-2001 : Added listener mechanism (DG);
* 15-Nov-2001 : Updated argument checking and exceptions in add() method (DG);
* 29-Nov-2001 : Added properties to describe the domain and range (DG);
* 07-Dec-2001 : Renamed TimeSeries --> BasicTimeSeries (DG);
* 01-Mar-2002 : Updated import statements (DG);
* 28-Mar-2002 : Added a method add(TimePeriod, double) (DG);
* 27-Aug-2002 : Changed return type of delete method to void (DG);
* 04-Oct-2002 : Added itemCount and historyCount attributes, fixed errors
* reported by Checkstyle (DG);
* 29-Oct-2002 : Added series change notification to addOrUpdate() method (DG);
* 28-Jan-2003 : Changed name back to TimeSeries (DG);
* 13-Mar-2003 : Moved to com.jrefinery.data.time package and implemented
* Serializable (DG);
* 01-May-2003 : Updated equals() method (see bug report 727575) (DG);
* 14-Aug-2003 : Added ageHistoryCountItems method (copied existing code for
* contents) made a method and added to addOrUpdate. Made a
* public method to enable ageing against a specified time
* (eg now) as opposed to lastest time in series (BS);
* 15-Oct-2003 : Added fix for setItemCount method - see bug report 804425.
* Modified exception message in add() method to be more
* informative (DG);
* 13-Apr-2004 : Added clear() method (DG);
* 21-May-2004 : Added an extra addOrUpdate() method (DG);
* 15-Jun-2004 : Fixed NullPointerException in equals() method (DG);
* 29-Nov-2004 : Fixed bug 1075255 (DG);
* 17-Nov-2005 : Renamed historyCount --> maximumItemAge (DG);
* 28-Nov-2005 : Changed maximumItemAge from int to long (DG);
* 01-Dec-2005 : New add methods accept notify flag (DG);
* ------------- JFREECHART 1.0.0 ---------------------------------------------
* 24-May-2006 : Improved error handling in createCopy() methods (DG);
* 01-Sep-2006 : Fixed bugs in removeAgedItems() methods - see bug report
* 1550045 (DG);
*
*/
package org.jfree.data.time;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.jfree.data.general.Series;
import org.jfree.data.general.SeriesChangeEvent;
import org.jfree.data.general.SeriesException;
import org.jfree.util.ObjectUtilities;
/**
* Represents a sequence of zero or more data items in the form (period, value).
*/
public class TimeSeries extends Series implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -5032960206869675528L;
/** Default value for the domain description. */
protected static final String DEFAULT_DOMAIN_DESCRIPTION = "Time";
/** Default value for the range description. */
protected static final String DEFAULT_RANGE_DESCRIPTION = "Value";
/** A description of the domain. */
private String domain;
/** A description of the range. */
private String range;
/** The type of period for the data. */
protected Class timePeriodClass;
/** The list of data items in the series. */
protected List data;
/** The maximum number of items for the series. */
private int maximumItemCount;
/**
* The maximum age of items for the series, specified as a number of
* time periods.
*/
private long maximumItemAge;
/**
* Creates a new (empty) time series. By default, a daily time series is
* created. Use one of the other constructors if you require a different
* time period.
*
* @param name the series name (<code>null</code> not permitted).
*/
public TimeSeries(String name) {
this(name, DEFAULT_DOMAIN_DESCRIPTION, DEFAULT_RANGE_DESCRIPTION,
Day.class);
}
/**
* Creates a new (empty) time series with the specified name and class
* of {@link RegularTimePeriod}.
*
* @param name the series name (<code>null</code> not permitted).
* @param timePeriodClass the type of time period (<code>null</code> not
* permitted).
*/
public TimeSeries(String name, Class timePeriodClass) {
this(name, DEFAULT_DOMAIN_DESCRIPTION, DEFAULT_RANGE_DESCRIPTION,
timePeriodClass);
}
/**
* Creates a new time series that contains no data.
* <P>
* Descriptions can be specified for the domain and range. One situation
* where this is helpful is when generating a chart for the time series -
* axis labels can be taken from the domain and range description.
*
* @param name the name of the series (<code>null</code> not permitted).
* @param domain the domain description (<code>null</code> permitted).
* @param range the range description (<code>null</code> permitted).
* @param timePeriodClass the type of time period (<code>null</code> not
* permitted).
*/
public TimeSeries(String name, String domain, String range,
Class timePeriodClass) {
super(name);
this.domain = domain;
this.range = range;
this.timePeriodClass = timePeriodClass;
this.data = new java.util.ArrayList();
this.maximumItemCount = Integer.MAX_VALUE;
this.maximumItemAge = Long.MAX_VALUE;
}
/**
* Returns the domain description.
*
* @return The domain description (possibly <code>null</code>).
*
* @see #setDomainDescription(String)
*/
public String getDomainDescription() {
return this.domain;
}
/**
* Sets the domain description and sends a <code>PropertyChangeEvent</code>
* (with the property name <code>Domain</code>) to all registered
* property change listeners.
*
* @param description the description (<code>null</code> permitted).
*
* @see #getDomainDescription()
*/
public void setDomainDescription(String description) {
String old = this.domain;
this.domain = description;
firePropertyChange("Domain", old, description);
}
/**
* Returns the range description.
*
* @return The range description (possibly <code>null</code>).
*
* @see #setRangeDescription(String)
*/
public String getRangeDescription() {
return this.range;
}
/**
* Sets the range description and sends a <code>PropertyChangeEvent</code>
* (with the property name <code>Range</code>) to all registered listeners.
*
* @param description the description (<code>null</code> permitted).
*
* @see #getRangeDescription()
*/
public void setRangeDescription(String description) {
String old = this.range;
this.range = description;
firePropertyChange("Range", old, description);
}
/**
* Returns the number of items in the series.
*
* @return The item count.
*/
public int getItemCount() {
return this.data.size();
}
/**
* Returns the list of data items for the series (the list contains
* {@link TimeSeriesDataItem} objects and is unmodifiable).
*
* @return The list of data items.
*/
public List getItems() {
return Collections.unmodifiableList(this.data);
}
/**
* Returns the maximum number of items that will be retained in the series.
* The default value is <code>Integer.MAX_VALUE</code>.
*
* @return The maximum item count.
*
* @see #setMaximumItemCount(int)
*/
public int getMaximumItemCount() {
return this.maximumItemCount;
}
/**
* Sets the maximum number of items that will be retained in the series.
* If you add a new item to the series such that the number of items will
* exceed the maximum item count, then the FIRST element in the series is
* automatically removed, ensuring that the maximum item count is not
* exceeded.
*
* @param maximum the maximum (requires >= 0).
*
* @see #getMaximumItemCount()
*/
public void setMaximumItemCount(int maximum) {
if (maximum < 0) {
throw new IllegalArgumentException("Negative 'maximum' argument.");
}
this.maximumItemCount = maximum;
int count = this.data.size();
if (count > maximum) {
delete(0, count - maximum - 1);
}
}
/**
* Returns the maximum item age (in time periods) for the series.
*
* @return The maximum item age.
*
* @see #setMaximumItemAge(long)
*/
public long getMaximumItemAge() {
return this.maximumItemAge;
}
/**
* Sets the number of time units in the 'history' for the series. This
* provides one mechanism for automatically dropping old data from the
* time series. For example, if a series contains daily data, you might set
* the history count to 30. Then, when you add a new data item, all data
* items more than 30 days older than the latest value are automatically
* dropped from the series.
*
* @param periods the number of time periods.
*
* @see #getMaximumItemAge()
*/
public void setMaximumItemAge(long periods) {
if (periods < 0) {
throw new IllegalArgumentException("Negative 'periods' argument.");
}
this.maximumItemAge = periods;
removeAgedItems(true); // remove old items and notify if necessary
}
/**
* Returns the time period class for this series.
* <p>
* Only one time period class can be used within a single series (enforced).
* If you add a data item with a {@link Year} for the time period, then all
* subsequent data items must also have a {@link Year} for the time period.
*
* @return The time period class (never <code>null</code>).
*/
public Class getTimePeriodClass() {
return this.timePeriodClass;
}
/**
* Returns a data item for the series.
*
* @param index the item index (zero-based).
*
* @return The data item.
*
* @see #getDataItem(RegularTimePeriod)
*/
public TimeSeriesDataItem getDataItem(int index) {
return (TimeSeriesDataItem) this.data.get(index);
}
/**
* Returns the data item for a specific period.
*
* @param period the period of interest (<code>null</code> not allowed).
*
* @return The data item matching the specified period (or
* <code>null</code> if there is no match).
*
* @see #getDataItem(int)
*/
public TimeSeriesDataItem getDataItem(RegularTimePeriod period) {
if (period == null) {
throw new IllegalArgumentException("Null 'period' argument");
}
TimeSeriesDataItem dummy = new TimeSeriesDataItem(period,
Integer.MIN_VALUE);
int index = Collections.binarySearch(this.data, dummy);
if (index >= 0) {
return (TimeSeriesDataItem) this.data.get(index);
}
else {
return null;
}
}
/**
* Returns the time period at the specified index.
*
* @param index the index of the data item.
*
* @return The time period.
*/
public RegularTimePeriod getTimePeriod(int index) {
return getDataItem(index).getPeriod();
}
/**
* Returns a time period that would be the next in sequence on the end of
* the time series.
*
* @return The next time period.
*/
public RegularTimePeriod getNextTimePeriod() {
RegularTimePeriod last = getTimePeriod(getItemCount() - 1);
return last.next();
}
/**
* Returns a collection of all the time periods in the time series.
*
* @return A collection of all the time periods.
*/
public Collection getTimePeriods() {
Collection result = new java.util.ArrayList();
for (int i = 0; i < getItemCount(); i++) {
result.add(getTimePeriod(i));
}
return result;
}
/**
* Returns a collection of time periods in the specified series, but not in
* this series, and therefore unique to the specified series.
*
* @param series the series to check against this one.
*
* @return The unique time periods.
*/
public Collection getTimePeriodsUniqueToOtherSeries(TimeSeries series) {
Collection result = new java.util.ArrayList();
for (int i = 0; i < series.getItemCount(); i++) {
RegularTimePeriod period = series.getTimePeriod(i);
int index = getIndex(period);
if (index < 0) {
result.add(period);
}
}
return result;
}
/**
* Returns the index for the item (if any) that corresponds to a time
* period.
*
* @param period the time period (<code>null</code> not permitted).
*
* @return The index.
*/
public int getIndex(RegularTimePeriod period) {
if (period == null) {
throw new IllegalArgumentException("Null 'period' argument.");
}
TimeSeriesDataItem dummy = new TimeSeriesDataItem(
period, Integer.MIN_VALUE);
return Collections.binarySearch(this.data, dummy);
}
/**
* Returns the value at the specified index.
*
* @param index index of a value.
*
* @return The value (possibly <code>null</code>).
*/
public Number getValue(int index) {
return getDataItem(index).getValue();
}
/**
* Returns the value for a time period. If there is no data item with the
* specified period, this method will return <code>null</code>.
*
* @param period time period (<code>null</code> not permitted).
*
* @return The value (possibly <code>null</code>).
*/
public Number getValue(RegularTimePeriod period) {
int index = getIndex(period);
if (index >= 0) {
return getValue(index);
}
else {
return null;
}
}
/**
* Adds a data item to the series and sends a
* {@link org.jfree.data.general.SeriesChangeEvent} to all registered
* listeners.
*
* @param item the (timeperiod, value) pair (<code>null</code> not
* permitted).
*/
public void add(TimeSeriesDataItem item) {
add(item, true);
}
/**
* Adds a data item to the series and sends a
* {@link org.jfree.data.general.SeriesChangeEvent} to all registered
* listeners.
*
* @param item the (timeperiod, value) pair (<code>null</code> not
* permitted).
* @param notify notify listeners?
*/
public void add(TimeSeriesDataItem item, boolean notify) {
if (item == null) {
throw new IllegalArgumentException("Null 'item' argument.");
}
if (!item.getPeriod().getClass().equals(this.timePeriodClass)) {
StringBuffer b = new StringBuffer();
b.append("You are trying to add data where the time period class ");
b.append("is ");
b.append(item.getPeriod().getClass().getName());
b.append(", but the TimeSeries is expecting an instance of ");
b.append(this.timePeriodClass.getName());
b.append(".");
throw new SeriesException(b.toString());
}
// make the change (if it's not a duplicate time period)...
boolean added = false;
int count = getItemCount();
if (count == 0) {
this.data.add(item);
added = true;
}
else {
RegularTimePeriod last = getTimePeriod(getItemCount() - 1);
if (item.getPeriod().compareTo(last) > 0) {
this.data.add(item);
added = true;
}
else {
int index = Collections.binarySearch(this.data, item);
if (index < 0) {
this.data.add(-index - 1, item);
added = true;
}
else {
StringBuffer b = new StringBuffer();
b.append("You are attempting to add an observation for ");
b.append("the time period ");
b.append(item.getPeriod().toString());
b.append(" but the series already contains an observation");
b.append(" for that time period. Duplicates are not ");
b.append("permitted. Try using the addOrUpdate() method.");
throw new SeriesException(b.toString());
}
}
}
if (added) {
// check if this addition will exceed the maximum item count...
if (getItemCount() > this.maximumItemCount) {
this.data.remove(0);
}
removeAgedItems(false); // remove old items if necessary, but
// don't notify anyone, because that
// happens next anyway...
if (notify) {
fireSeriesChanged();
}
}
}
/**
* Adds a new data item to the series and sends a {@link SeriesChangeEvent}
* to all registered listeners.
*
* @param period the time period (<code>null</code> not permitted).
* @param value the value.
*/
public void add(RegularTimePeriod period, double value) {
// defer argument checking...
add(period, value, true);
}
/**
* Adds a new data item to the series and sends a {@link SeriesChangeEvent}
* to all registered listeners.
*
* @param period the time period (<code>null</code> not permitted).
* @param value the value.
* @param notify notify listeners?
*/
public void add(RegularTimePeriod period, double value, boolean notify) {
// defer argument checking...
TimeSeriesDataItem item = new TimeSeriesDataItem(period, value);
add(item, notify);
}
/**
* Adds a new data item to the series and sends
* a {@link org.jfree.data.general.SeriesChangeEvent} to all registered
* listeners.
*
* @param period the time period (<code>null</code> not permitted).
* @param value the value (<code>null</code> permitted).
*/
public void add(RegularTimePeriod period, Number value) {
// defer argument checking...
add(period, value, true);
}
/**
* Adds a new data item to the series and sends
* a {@link org.jfree.data.general.SeriesChangeEvent} to all registered
* listeners.
*
* @param period the time period (<code>null</code> not permitted).
* @param value the value (<code>null</code> permitted).
* @param notify notify listeners?
*/
public void add(RegularTimePeriod period, Number value, boolean notify) {
// defer argument checking...
TimeSeriesDataItem item = new TimeSeriesDataItem(period, value);
add(item, notify);
}
/**
* Updates (changes) the value for a time period. Throws a
* {@link SeriesException} if the period does not exist.
*
* @param period the period (<code>null</code> not permitted).
* @param value the value (<code>null</code> permitted).
*/
public void update(RegularTimePeriod period, Number value) {
TimeSeriesDataItem temp = new TimeSeriesDataItem(period, value);
int index = Collections.binarySearch(this.data, temp);
if (index >= 0) {
TimeSeriesDataItem pair = (TimeSeriesDataItem) this.data.get(index);
pair.setValue(value);
fireSeriesChanged();
}
else {
throw new SeriesException(
"TimeSeries.update(TimePeriod, Number): period does not exist."
);
}
}
/**
* Updates (changes) the value of a data item.
*
* @param index the index of the data item.
* @param value the new value (<code>null</code> permitted).
*/
public void update(int index, Number value) {
TimeSeriesDataItem item = getDataItem(index);
item.setValue(value);
fireSeriesChanged();
}
/**
* Adds or updates data from one series to another. Returns another series
* containing the values that were overwritten.
*
* @param series the series to merge with this.
*
* @return A series containing the values that were overwritten.
*/
public TimeSeries addAndOrUpdate(TimeSeries series) {
TimeSeries overwritten = new TimeSeries("Overwritten values from: "
+ getKey(), series.getTimePeriodClass());
for (int i = 0; i < series.getItemCount(); i++) {
TimeSeriesDataItem item = series.getDataItem(i);
TimeSeriesDataItem oldItem = addOrUpdate(item.getPeriod(),
item.getValue());
if (oldItem != null) {
overwritten.add(oldItem);
}
}
return overwritten;
}
/**
* Adds or updates an item in the times series and sends a
* {@link org.jfree.data.general.SeriesChangeEvent} to all registered
* listeners.
*
* @param period the time period to add/update (<code>null</code> not
* permitted).
* @param value the new value.
*
* @return A copy of the overwritten data item, or <code>null</code> if no
* item was overwritten.
*/
public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period,
double value) {
return this.addOrUpdate(period, new Double(value));
}
/**
* Adds or updates an item in the times series and sends a
* {@link org.jfree.data.general.SeriesChangeEvent} to all registered
* listeners.
*
* @param period the time period to add/update (<code>null</code> not
* permitted).
* @param value the new value (<code>null</code> permitted).
*
* @return A copy of the overwritten data item, or <code>null</code> if no
* item was overwritten.
*/
public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period,
Number value) {
if (period == null) {
throw new IllegalArgumentException("Null 'period' argument.");
}
TimeSeriesDataItem overwritten = null;
TimeSeriesDataItem key = new TimeSeriesDataItem(period, value);
int index = Collections.binarySearch(this.data, key);
if (index >= 0) {
TimeSeriesDataItem existing
= (TimeSeriesDataItem) this.data.get(index);
overwritten = (TimeSeriesDataItem) existing.clone();
existing.setValue(value);
removeAgedItems(false); // remove old items if necessary, but
// don't notify anyone, because that
// happens next anyway...
fireSeriesChanged();
}
else {
this.data.add(-index - 1, new TimeSeriesDataItem(period, value));
// check if this addition will exceed the maximum item count...
if (getItemCount() > this.maximumItemCount) {
this.data.remove(0);
}
removeAgedItems(false); // remove old items if necessary, but
// don't notify anyone, because that
// happens next anyway...
fireSeriesChanged();
}
return overwritten;
}
/**
* Age items in the series. Ensure that the timespan from the youngest to
* the oldest record in the series does not exceed maximumItemAge time
* periods. Oldest items will be removed if required.
*
* @param notify controls whether or not a {@link SeriesChangeEvent} is
* sent to registered listeners IF any items are removed.
*/
public void removeAgedItems(boolean notify) {
// check if there are any values earlier than specified by the history
// count...
if (getItemCount() > 1) {
long latest = getTimePeriod(getItemCount() - 1).getSerialIndex();
boolean removed = false;
while ((latest - getTimePeriod(0).getSerialIndex())
> this.maximumItemAge) {
this.data.remove(0);
removed = true;
}
if (removed && notify) {
fireSeriesChanged();
}
}
}
/**
* Age items in the series. Ensure that the timespan from the supplied
* time to the oldest record in the series does not exceed history count.
* oldest items will be removed if required.
*
* @param latest the time to be compared against when aging data
* (specified in milliseconds).
* @param notify controls whether or not a {@link SeriesChangeEvent} is
* sent to registered listeners IF any items are removed.
*/
public void removeAgedItems(long latest, boolean notify) {
// find the serial index of the period specified by 'latest'
long index = Long.MAX_VALUE;
try {
Method m = RegularTimePeriod.class.getDeclaredMethod(
"createInstance", new Class[] {Class.class, Date.class,
TimeZone.class});
RegularTimePeriod newest = (RegularTimePeriod) m.invoke(
this.timePeriodClass, new Object[] {this.timePeriodClass,
new Date(latest), TimeZone.getDefault()});
index = newest.getSerialIndex();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
// check if there are any values earlier than specified by the history
// count...
boolean removed = false;
while (getItemCount() > 0 && (index
- getTimePeriod(0).getSerialIndex()) > this.maximumItemAge) {
this.data.remove(0);
removed = true;
}
if (removed && notify) {
fireSeriesChanged();
}
}
/**
* Removes all data items from the series and sends a
* {@link SeriesChangeEvent} to all registered listeners.
*/
public void clear() {
if (this.data.size() > 0) {
this.data.clear();
fireSeriesChanged();
}
}
/**
* Deletes the data item for the given time period and sends a
* {@link SeriesChangeEvent} to all registered listeners. If there is no
* item with the specified time period, this method does nothing.
*
* @param period the period of the item to delete (<code>null</code> not
* permitted).
*/
public void delete(RegularTimePeriod period) {
int index = getIndex(period);
if (index >= 0) {
this.data.remove(index);
fireSeriesChanged();
}
}
/**
* Deletes data from start until end index (end inclusive).
*
* @param start the index of the first period to delete.
* @param end the index of the last period to delete.
*/
public void delete(int start, int end) {
if (end < start) {
throw new IllegalArgumentException("Requires start <= end.");
}
for (int i = 0; i <= (end - start); i++) {
this.data.remove(start);
}
fireSeriesChanged();
}
/**
* Returns a clone of the time series.
* <P>
* Notes:
* <ul>
* <li>no need to clone the domain and range descriptions, since String
* object is immutable;</li>
* <li>we pass over to the more general method clone(start, end).</li>
* </ul>
*
* @return A clone of the time series.
*
* @throws CloneNotSupportedException not thrown by this class, but
* subclasses may differ.
*/
public Object clone() throws CloneNotSupportedException {
Object clone = createCopy(0, getItemCount() - 1);
return clone;
}
/**
* Creates a new timeseries by copying a subset of the data in this time
* series.
*
* @param start the index of the first time period to copy.
* @param end the index of the last time period to copy.
*
* @return A series containing a copy of this times series from start until
* end.
*
* @throws CloneNotSupportedException if there is a cloning problem.
*/
public TimeSeries createCopy(int start, int end)
throws CloneNotSupportedException {
if (start < 0) {
throw new IllegalArgumentException("Requires start >= 0.");
}
if (end < start) {
throw new IllegalArgumentException("Requires start <= end.");
}
TimeSeries copy = (TimeSeries) super.clone();
copy.data = new java.util.ArrayList();
if (this.data.size() > 0) {
for (int index = start; index <= end; index++) {
TimeSeriesDataItem item
= (TimeSeriesDataItem) this.data.get(index);
TimeSeriesDataItem clone = (TimeSeriesDataItem) item.clone();
try {
copy.add(clone);
}
catch (SeriesException e) {
e.printStackTrace();
}
}
}
return copy;
}
/**
* Creates a new timeseries by copying a subset of the data in this time
* series.
*
* @param start the first time period to copy.
* @param end the last time period to copy.
*
* @return A time series containing a copy of this time series from start
* until end.
*
* @throws CloneNotSupportedException if there is a cloning problem.
*/
public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end)
throws CloneNotSupportedException {
if (start == null) {
throw new IllegalArgumentException("Null 'start' argument.");
}
if (end == null) {
throw new IllegalArgumentException("Null 'end' argument.");
}
if (start.compareTo(end) > 0) {
throw new IllegalArgumentException(
"Requires start on or before end.");
}
boolean emptyRange = false;
int startIndex = getIndex(start);
if (startIndex < 0) {
startIndex = -(startIndex + 1);
if (startIndex == this.data.size()) {
emptyRange = true; // start is after last data item
}
}
int endIndex = getIndex(end);
if (endIndex < 0) { // end period is not in original series
endIndex = -(endIndex + 1); // this is first item AFTER end period
endIndex = endIndex - 1; // so this is last item BEFORE end
}
if (endIndex < 0) {
emptyRange = true;
}
if (emptyRange) {
TimeSeries copy = (TimeSeries) super.clone();
copy.data = new java.util.ArrayList();
return copy;
}
else {
return createCopy(startIndex, endIndex);
}
}
/**
* Tests the series for equality with an arbitrary object.
*
* @param object the object to test against (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof TimeSeries) || !super.equals(object)) {
return false;
}
TimeSeries s = (TimeSeries) object;
if (!ObjectUtilities.equal(
getDomainDescription(), s.getDomainDescription()
)) {
return false;
}
if (!ObjectUtilities.equal(
getRangeDescription(), s.getRangeDescription()
)) {
return false;
}
if (!getClass().equals(s.getClass())) {
return false;
}
if (getMaximumItemAge() != s.getMaximumItemAge()) {
return false;
}
if (getMaximumItemCount() != s.getMaximumItemCount()) {
return false;
}
int count = getItemCount();
if (count != s.getItemCount()) {
return false;
}
for (int i = 0; i < count; i++) {
if (!getDataItem(i).equals(s.getDataItem(i))) {
return false;
}
}
return true;
}
/**
* Returns a hash code value for the object.
*
* @return The hashcode
*/
public int hashCode() {
int result;
result = (this.domain != null ? this.domain.hashCode() : 0);
result = 29 * result + (this.range != null ? this.range.hashCode() : 0);
result = 29 * result + (this.timePeriodClass != null
? this.timePeriodClass.hashCode() : 0);
result = 29 * result + this.data.hashCode();
result = 29 * result + this.maximumItemCount;
result = 29 * result + (int) this.maximumItemAge;
return result;
}
}
| |
package com.bill.jeson.test;
import java.util.List;
import junit.framework.TestCase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.bill.jeson.Jeson;
import com.bill.jeson.test.model.Company;
import com.bill.jeson.test.model.FinalValue;
import com.bill.jeson.test.model.HttpHeader;
import com.bill.jeson.test.model.PeopleAll;
import com.bill.jeson.test.model.PeopleWithoutType;
public class JsonObjectTest extends TestCase {
private String jsonObjStr;
private String emptyJsonStr;
private String jsonObjsStr;
private String jsonObjListStr;
private String jsonHttpheaderStr;
@Override
protected void setUp() throws Exception {
super.setUp();
initJsonObjStr();
emptyJsonStr = "{}";
initJsonObjsStr();
initJsonObjListString();
initHttpheaderStr();
}
/*
* initialize simple json object
*/
private void initJsonObjStr() throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("firstName", "John");
jsonObject.put("lastName", "Smith");
jsonObject.put("sex", "third");
jsonObject.put("age", 25);
jsonObject.put("height", 175);
jsonObject.put("phoneNumber", 13800000000L);
jsonObject.put("weight", 65.1);
jsonObjStr = jsonObject.toString();
}
/*
* initialize json object with inner json object
*/
private void initJsonObjsStr() throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "Baidu");
JSONObject ceoObject = new JSONObject();
ceoObject.put("firstName", "Robin");
ceoObject.put("lastName", "Li");
ceoObject.put("sex", "third");
ceoObject.put("age", 46);
ceoObject.put("height", 175);
ceoObject.put("phoneNumber", 13800000000L);
ceoObject.put("weight", 65.1);
jsonObject.put("ceo", ceoObject);
jsonObjsStr = jsonObject.toString();
}
/*
* base on initJsonObjsStr(), add a json array
*/
private void initJsonObjListString() throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "Baidu");
JSONObject ceoObject = new JSONObject();
ceoObject.put("firstName", "Robin");
ceoObject.put("lastName", "Li");
ceoObject.put("sex", "third");
ceoObject.put("age", 46);
ceoObject.put("height", 175);
ceoObject.put("phoneNumber", 13800000000L);
ceoObject.put("weight", 65.1);
jsonObject.put("ceo", ceoObject);
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 3; i++) {
JSONObject employeeObject = new JSONObject();
employeeObject.put("firstName", "Bill");
employeeObject.put("lastName", "Lv");
employeeObject.put("sex", "man");
employeeObject.put("age", 24);
employeeObject.put("height", 175);
employeeObject.put("phoneNumber", 13800000000L);
employeeObject.put("weight", 55.1);
jsonArray.put(employeeObject);
}
jsonObject.put("employee", jsonArray);
jsonObjListStr = jsonObject.toString();
}
private void initHttpheaderStr() throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Accept-Language", "en-US,en;q=0.8");
jsonObject.put("Host", "headers.jsontest.com");
jsonObject.put("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
jsonObject
.put("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
jsonHttpheaderStr = jsonObject.toString();
}
public void testJsonSource() {
try {
JSONObject jsonObject = new JSONObject(jsonObjStr);
assertEquals("John", jsonObject.getString("firstName"));
assertEquals("Smith", jsonObject.getString("lastName"));
assertEquals("third", jsonObject.getString("sex"));
assertEquals(25, jsonObject.getInt("age"));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void testJsonBaseTypeAnnotation() {
try {
PeopleAll people = Jeson.createBean(PeopleAll.class, jsonObjStr);
assertEquals("John", people.getFirstName());
assertEquals("Smith", people.getLastName());
assertEquals("third", people.getSex());
assertEquals(25, people.getAge());
assertEquals(175, people.getHeight(), 0);
assertEquals(13800000000L, people.getPhoneNumber());
assertEquals(65.1, people.getWeight());
} catch (Exception e) {
e.printStackTrace();
}
}
public void testFieldDetect() {
try {
PeopleWithoutType people = Jeson.createBean(
PeopleWithoutType.class, jsonObjStr);
assertEquals("John", people.getFirstName());
assertEquals("Smith", people.getLastName());
assertEquals("third", people.getSex());
assertEquals(25, people.getAge());
assertEquals(175, people.getHeight(), 0);
assertEquals(13800000000L, people.getPhoneNumber());
assertEquals(65.1, people.getWeight());
} catch (Exception e) {
e.printStackTrace();
}
}
public void testEmptyJsonDetect() {
try {
PeopleWithoutType people = Jeson.createBean(
PeopleWithoutType.class, emptyJsonStr);
assertEquals("Bill", people.getFirstName());
assertEquals("Lv", people.getLastName());
assertEquals("man", people.getSex());
assertEquals(1, people.getAge());
assertEquals(1, people.getHeight(), 0);
assertEquals(1, people.getPhoneNumber());
assertEquals(1, people.getWeight(), 0);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testJsonEmptyObjectsDetect() {
try {
Company company = Jeson.createBean(Company.class, emptyJsonStr);
assertEquals("HT", company.getName());
PeopleAll ceo = company.getCeo();
assertEquals("Bill", ceo.getFirstName());
assertEquals("Lv", ceo.getLastName());
assertEquals("man", ceo.getSex());
assertEquals(1, ceo.getAge());
assertEquals(1, ceo.getHeight(), 0);
assertEquals(1, ceo.getPhoneNumber());
assertEquals(1, ceo.getWeight(), 0);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testJsonObjectsDetect() {
try {
Company company = Jeson.createBean(Company.class, jsonObjsStr);
assertEquals("Baidu", company.getName());
PeopleAll ceo = company.getCeo();
assertEquals("Robin", ceo.getFirstName());
assertEquals("Li", ceo.getLastName());
assertEquals("third", ceo.getSex());
assertEquals(46, ceo.getAge());
assertEquals(175, ceo.getHeight(), 0);
assertEquals(13800000000L, ceo.getPhoneNumber());
assertEquals(65.1, ceo.getWeight(), 0);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testJsonObjectsListDetect() {
try {
Company company = Jeson.createBean(Company.class, jsonObjListStr);
assertEquals("Baidu", company.getName());
PeopleAll ceo = company.getCeo();
assertEquals("Robin", ceo.getFirstName());
assertEquals("Li", ceo.getLastName());
assertEquals("third", ceo.getSex());
assertEquals(46, ceo.getAge());
assertEquals(175, ceo.getHeight(), 0);
assertEquals(13800000000L, ceo.getPhoneNumber());
assertEquals(65.1, ceo.getWeight(), 0);
List<PeopleAll> employees = company.getEmployee();
assertNotNull(employees);
for (PeopleAll employee : employees) {
assertEquals("Bill", employee.getFirstName());
assertEquals("Lv", employee.getLastName());
assertEquals("man", employee.getSex());
assertEquals(24, employee.getAge());
assertEquals(175, employee.getHeight(), 0);
assertEquals(13800000000L, employee.getPhoneNumber());
assertEquals(55.1, employee.getWeight(), 0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void testHttpheaderJsonDetect() {
try {
HttpHeader header = Jeson.createBean(HttpHeader.class,
jsonHttpheaderStr);
assertEquals("en-US,en;q=0.8", header.getLanguage());
assertEquals("headers.jsontest.com", header.getHost());
assertEquals("ISO-8859-1,utf-8;q=0.7,*;q=0.3", header.getCharset());
assertEquals(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
header.getAccept());
} catch (Exception e) {
e.printStackTrace();
}
}
public void testSimpleJavaBean2String() {
PeopleAll all = new PeopleAll();
all.setAge(11);
all.setFirstName("Bill");
all.setLastName("Lv");
all.setHeight(177.7f);
all.setPhoneNumber(13000000000L);
all.setSex("male");
all.setWeight(56);
try {
String json = Jeson.bean2String(all);
JSONObject jsonObject = new JSONObject(json);
assertEquals("Bill", jsonObject.getString("firstName"));
assertEquals("Lv", jsonObject.getString("lastName"));
assertEquals("male", jsonObject.getString("sex"));
assertEquals(11, jsonObject.getInt("age"));
assertEquals(177.7, jsonObject.getDouble("height"), 0);
assertEquals(13000000000L, jsonObject.getLong("phoneNumber"));
assertEquals(56, jsonObject.getDouble("weight"), 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// inner json object
public void testJavaBeanWithObj2String() {
PeopleAll all = new PeopleAll();
all.setAge(11);
all.setFirstName("Bill");
all.setLastName("Lv");
all.setHeight(177.7f);
all.setPhoneNumber(13000000000L);
all.setSex("male");
all.setWeight(56);
Company company = new Company();
company.setCeo(all);
try {
String json = Jeson.bean2String(company);
JSONObject jsonObject = new JSONObject(json);
JSONObject ceoObj = jsonObject.getJSONObject("ceo");
assertEquals("Bill", ceoObj.getString("firstName"));
assertEquals("Lv", ceoObj.getString("lastName"));
assertEquals("male", ceoObj.getString("sex"));
assertEquals(11, ceoObj.getInt("age"));
assertEquals(177.7, ceoObj.getDouble("height"), 0);
assertEquals(13000000000L, ceoObj.getLong("phoneNumber"));
assertEquals(56, ceoObj.getDouble("weight"), 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// inner json object and list
public void testJavaBeanWithList2String() {
try {
Company company = Jeson.createBean(Company.class, jsonObjListStr);
String json = Jeson.bean2String(company);
JSONObject jsonCompany = new JSONObject(json);
JSONObject jsonCeo = jsonCompany.getJSONObject("ceo");
assertEquals("Baidu", jsonCompany.getString("name"));
assertEquals("Robin", jsonCeo.getString("firstName"));
assertEquals("Li", jsonCeo.getString("lastName"));
assertEquals("third", jsonCeo.getString("sex"));
assertEquals(46, jsonCeo.getInt("age"));
assertEquals(175, jsonCeo.getDouble("height"), 0);
assertEquals(13800000000L, jsonCeo.getLong("phoneNumber"));
assertEquals(65.1, jsonCeo.getDouble("weight"), 0);
JSONArray employeeJson = jsonCompany.getJSONArray("employee");
assertNotNull(employeeJson);
for (int i = 0; i < employeeJson.length(); i++) {
JSONObject item = employeeJson.getJSONObject(i);
assertEquals("Bill", item.getString("firstName"));
assertEquals("Lv", item.getString("lastName"));
assertEquals("man", item.getString("sex"));
assertEquals(24, item.getInt("age"));
assertEquals(175, item.getDouble("height"), 0);
assertEquals(13800000000L, item.getLong("phoneNumber"));
assertEquals(55.1, item.getDouble("weight"), 0);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void testFinalValue() {
FinalValue finalValue = new FinalValue();
try {
assertEquals("next",
new JSONObject(Jeson.bean2String(finalValue))
.getString("finalStr"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| |
/* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://fedora-commons.org/license/).
*/
package org.fcrepo.server.validation;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.xml.XMLConstants;
import javax.xml.validation.SchemaFactory;
import org.fcrepo.common.Constants;
import org.fcrepo.server.errors.GeneralException;
import org.fcrepo.server.errors.ObjectValidityException;
import org.fcrepo.server.errors.ServerException;
import org.fcrepo.server.storage.types.Validation;
import org.fcrepo.utilities.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
/**
* The implementation of the digital object validation module (see
* DOValidator.class and DOValidatorModule.class). The validator operates on
* digital object XML files encoded in one of the Fedora-supported encoding
* formats (i.e., FOXML, Fedora METS, and possibly others in the future). The
* following types of validation can be run:
*
* <pre>
* 0=VALDIATE_ALL : All validation will be done.
* 1=VALIDATE_XML_SCHEMA : the digital object will be validated against
* the the appropriate XML Schema. An ObjectValidityException
* will be thrown if the object fails the schema test.
* 2=VALIDATE_SCHEMATRON : the digital object will be validated
* against a set of rules expressed by a Schematron schema.
* These rules are beyond what can be expressed in XML Schema.
* The Schematron schema expresses rules for different phases
* of the object. There are rules appropriate to a digital
* object when it is first ingested into the repository
* (ingest phase). There are additional rules that must be met
* before a digital object is considered valid for permanent
* storage in the repository (completed phase). These rules
* pertain to aspects of the object that are system assigned,
* such as created dates and state codes.
* An ObjectValidityException will be thrown if the object fails
* the Fedora rules test.
* </pre>
*
* @author Sandy Payette
* @version $Id$
*/
public class DOValidatorImpl
implements DOValidator {
private static final Logger logger =
LoggerFactory.getLogger(DOValidatorImpl.class);
protected static boolean debug = true;
/** Configuration variable: tempdir is a working area for validation */
protected static String tempDir = null;
/**
* Configuration variable: xmlSchemaPath is the location of the XML Schema.
*/
protected static String xmlSchemaPath = null;
/**
* Configuration variable: schematronPreprocessorPath is the Schematron
* stylesheet that is used to transform a Schematron schema into a
* validating stylesheet based on the rules in the schema.
*/
protected static String schematronPreprocessorPath = null;
/**
* Configuration variable: schematronSchemaPath is the Schematron schema
* that expresses Fedora-specific validation rules. It is transformed into a
* validating stylesheet by the Schematron preprocessing stylesheet.
*/
protected static String schematronSchemaPath = null;
/**
* Map of XML Schemas configured with the Fedora Repository. key = format
* uri value = schema file path
*/
private final Map<String, DOValidatorXMLSchema> m_xmlSchemaMap;
/**
* Map of Schematron rule schemas configured with the Fedora Repository. key =
* format uri value = schema file path
*/
private final Map<String, String> m_ruleSchemaMap;
private final File m_tempDir;
private final String m_absoluteTempPath;
/**
* <p>
* Constructs a new DOValidatorImpl to support all forms of digital object
* validation, using specified values for configuration values.
* </p>
* <p>
* Any parameter may be given as null, in which case the default value is
* assumed.
* </p>
*
* @param tempDir
* Working area for validation, default is <i>temp/</i>
* @param xmlSchemaMap
* Location of XML Schemas (W3 Schema) configured with Fedora (see
* Fedora.fcfg). Current options are <i>xsd/foxml1-1.xsd</i> for
* FOXML or <i>xsd/mets-fedora-ext1-1.xsd</i> for METS (Fedora
* extension)
* @param schematronPreprocessorPath
* Location of the Schematron pre-processing stylesheet configured
* with Fedora.</i>
* @param ruleSchemaMap
* Location of rule schemas (Schematron), configured with Fedora (see
* Fedora.fcfg). Current options are <i>schematron/foxmlRules1-0.xml</i>
* for FOXML or <i>schematron/metsExtRules1-0.xml</i> for METS
* @throws ServerException
* If construction fails for any reason.
*/
public DOValidatorImpl(String tempDir,
Map<String, String> xmlSchemaMap,
String schematronPreprocessorPath,
Map<String, String> ruleSchemaMap)
throws ServerException {
logger.debug("VALIDATE: Initializing object validation...");
m_xmlSchemaMap = new HashMap<String, DOValidatorXMLSchema>(xmlSchemaMap.size());
SchemaFactory schemaFactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
for (Entry<String,String> entry: xmlSchemaMap.entrySet()) {
try {
m_xmlSchemaMap.put(
entry.getKey(),
new DOValidatorXMLSchema(
schemaFactory.newSchema(new File(entry.getValue()))));
} catch (SAXException e) {
throw new GeneralException("Cannot read or create schema at " +
entry.getValue(),e);
}
}
m_ruleSchemaMap = ruleSchemaMap;
if (tempDir == null) {
throw new ObjectValidityException("[DOValidatorImpl] ERROR in constructor: "
+ "tempDir is null.");
}
if (schematronPreprocessorPath == null) {
throw new ObjectValidityException("[DOValidatorImpl] ERROR in constructor. "
+ "schematronPreprocessorPath is null.");
}
m_tempDir = new File(tempDir);
if (!m_tempDir.exists() && !m_tempDir.mkdirs()) {
throw new GeneralException("Cannot read or create tempDir at " +
tempDir);
}
m_absoluteTempPath = m_tempDir.getAbsolutePath();
DOValidatorImpl.tempDir = tempDir;
DOValidatorImpl.schematronPreprocessorPath = schematronPreprocessorPath;
}
/**
* <p>
* Validates a digital object.
* </p>
*
* @param objectAsStream
* The digital object provided as a stream.
* @param format
* The format URI of the object serialization.
* @param validationType
* The level of validation to perform on the digital object. This is
* an integer from 0-2 with the following meanings: 0 = VALIDATE_ALL
* (do all validation levels) 1 = VALIDATE_XML_SCHEMA (perform only
* XML Schema validation) 2 = VALIDATE_SCHEMATRON (perform only
* Schematron Rules validation)
* @param phase
* The stage in the workflow for which the validation should be
* contextualized. "ingest" = the object is encoded for ingest into
* the repository "store" = the object is encoded with all final
* assignments so that it is appropriate for storage as the
* authoritative serialization of the object.
* @throws ObjectValidityException
* If validation fails for any reason.
* @throws GeneralException
* If validation fails for any reason.
*/
public void validate(InputStream objectAsStream,
String format,
int validationType,
String phase) throws ObjectValidityException,
GeneralException {
if (validationType == VALIDATE_NONE) return;
checkFormat(format);
switch (validationType) {
case VALIDATE_NONE:
break;
case VALIDATE_ALL:
try {
// FIXME We need to use the object Inputstream twice, once for XML
// Schema validation and once for Schematron validation.
// We may want to consider implementing some form of a rewindable
// InputStream. For now, I will just write the object InputStream to
// disk so I can read it multiple times.
if (logger.isDebugEnabled()) {
logger.debug(
"Validating streams against schema and schematron" +
" requires caching tempfiles to disk; consider" +
"calling validations seperately with a buffered" +
"InputStream"
);
}
File objectAsFile = streamtoFile(objectAsStream);
validate(objectAsFile, format, validationType, phase);
} catch (IOException ioe) {
throw new ObjectValidityException("[DOValidatorImpl]: "
+ "ERROR in validate(InputStream objectAsStream...). " + ioe.getMessage());
}
break;
case VALIDATE_XML_SCHEMA:
validateXMLSchema(objectAsStream, m_xmlSchemaMap.get(format));
break;
case VALIDATE_SCHEMATRON:
validateByRules(objectAsStream,
m_ruleSchemaMap.get(format),
schematronPreprocessorPath,
phase);
break;
default:
String msg = "VALIDATE: ERROR - missing or invalid validationType";
logger.error(msg);
throw new GeneralException("[DOValidatorImpl] " + msg + ":"
+ validationType);
}
return;
}
/**
* <p>
* Validates a digital object.
* </p>
*
* @param objectAsFile
* The digital object provided as a file.
* @param validationType
* The level of validation to perform on the digital object. This is
* an integer from 0-2 with the following meanings: 0 = VALIDATE_ALL
* (do all validation levels) 1 = VALIDATE_XML_SCHEMA (perform only
* XML Schema validation) 2 = VALIDATE_SCHEMATRON (perform only
* Schematron Rules validation)
* @param phase
* The stage in the work flow for which the validation should be
* contextualized. "ingest" = the object is in the submission format
* for the ingest phase "store" = the object is in the authoritative
* format for the final storage phase
* @throws ObjectValidityException
* If validation fails for any reason.
* @throws GeneralException
* If validation fails for any reason.
*/
public void validate(File objectAsFile,
String format,
int validationType,
String phase) throws ObjectValidityException,
GeneralException {
logger.debug("VALIDATE: Initiating validation: phase={} format={}",
phase, format);
if (validationType == VALIDATE_NONE) return;
checkFormat(format);
if (format.equals(Constants.ATOM_ZIP1_1.uri)) {
// If the object serialization is a Zip file with an atom
// manifest, extract the manifest for validation.
try {
File manifest = null;
ZipInputStream zip = new ZipInputStream(new FileInputStream(objectAsFile));
ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) {
if (entry.getName().equals("atommanifest.xml")) {
manifest = streamtoFile(zip);
break;
}
}
zip.close();
objectAsFile = manifest;
} catch(IOException e) {
throw new GeneralException(e.getMessage(), e);
}
}
try {
FileInputStream objectAsStream = new FileInputStream(objectAsFile);
if (validationType == VALIDATE_ALL) {
validateByRules(objectAsStream,
m_ruleSchemaMap.get(format),
schematronPreprocessorPath,
phase);
validateXMLSchema(new FileInputStream(objectAsFile),
m_xmlSchemaMap.get(format));
} else if (validationType == VALIDATE_XML_SCHEMA) {
validateXMLSchema(objectAsStream, m_xmlSchemaMap.get(format));
} else if (validationType == VALIDATE_SCHEMATRON) {
validateByRules(objectAsStream,
m_ruleSchemaMap.get(format),
schematronPreprocessorPath,
phase);
} else {
String msg = "VALIDATE: ERROR - missing or invalid validationType";
logger.error(msg);
throw new GeneralException("[DOValidatorImpl] " + msg + ":"
+ validationType);
}
} catch (IOException ioe) {
logger.error("VALIDATE: ERROR - failed validations.", ioe);
throw new ObjectValidityException("[DOValidatorImpl]: validate(File input...). "
+ ioe.getMessage());
} finally {
cleanUp(objectAsFile);
}
}
private void checkFormat(String format) throws ObjectValidityException {
if (!m_xmlSchemaMap.containsKey(format)) {
Validation validation = new Validation("unknown");
List<String> probs = new ArrayList<String>();
probs.add("Unsupported format: " + format);
validation.setObjectProblems(probs);
throw new ObjectValidityException("Unsupported format: " + format, validation);
}
}
/**
* Do XML Schema validation on the Fedora object.
*
* @param objectAsFile
* The digital object provided as a file.
* @throws ObjectValidityException
* If validation fails for any reason.
* @throws GeneralException
* If validation fails for any reason.
*/
private void validateXMLSchema(InputStream objectAsStream, DOValidatorXMLSchema xsv)
throws ObjectValidityException, GeneralException {
try {
xsv.validate(objectAsStream);
} catch (ObjectValidityException e) {
logger.error("VALIDATE: ERROR - failed XML Schema validation.", e);
throw e;
} catch (Exception e) {
logger.error("VALIDATE: ERROR - failed XML Schema validation.", e);
throw new ObjectValidityException("[DOValidatorImpl]: validateXMLSchema. "
+ e.getMessage());
}
logger.debug("VALIDATE: SUCCESS - passed XML Schema validation.");
}
/**
* Do Schematron rules validation on the Fedora object. Schematron
* validation tests the object against a set of rules expressed using XPATH
* in a Schematron schema. These test for things that are beyond what can be
* expressed using XML Schema.
*
* @param objectAsFile
* The digital object provided as a file.
* @param schemaPath
* Location of the Schematron rules file.
* @param preprocessorPath
* Location of Schematron preprocessing stylesheet
* @param phase
* The workflow phase (ingest, store) for the object.
* @throws ObjectValidityException
* If validation fails for any reason.
* @throws GeneralException
* If validation fails for any reason.
*/
private void validateByRules(InputStream objectAsStream,
String ruleSchemaPath,
String preprocessorPath,
String phase) throws ObjectValidityException,
GeneralException {
try {
DOValidatorSchematron schtron =
new DOValidatorSchematron(ruleSchemaPath,
preprocessorPath,
phase);
schtron.validate(objectAsStream);
} catch (ObjectValidityException e) {
logger.error("VALIDATE: ERROR - failed Schematron rules validation.",
e);
throw e;
} catch (Exception e) {
logger.error("VALIDATE: ERROR - failed Schematron rules validation.",
e);
throw new ObjectValidityException("[DOValidatorImpl]: "
+ "failed Schematron rules validation. " + e.getMessage());
}
logger.debug("VALIDATE: SUCCESS - passed Schematron rules validation.");
}
private File streamtoFile(InputStream objectAsStream)
throws IOException {
File objectAsFile = null;
try {
objectAsFile = File.createTempFile("validation", "tmp", m_tempDir);
FileOutputStream fos = new FileOutputStream(objectAsFile);
FileUtils.copy(objectAsStream, fos);
} catch (IOException e) {
if (objectAsFile != null && objectAsFile.exists()) {
objectAsFile.delete();
}
throw e;
}
return objectAsFile;
}
// Distinguish temporary object files from real object files
// that were passed in for validation. This is a bit ugly as it stands,
// but it should only blow away files in the temp directory.
private void cleanUp(File f) {
if (f.getParentFile() != null) {
if (m_absoluteTempPath.equalsIgnoreCase(f
.getParentFile().getAbsolutePath())) {
f.delete();
}
}
}
}
| |
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.event;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.expression.AnnotatedElementKey;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.Order;
import org.springframework.expression.EvaluationContext;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* {@link GenericApplicationListener} adapter that delegates the processing of
* an event to an {@link EventListener} annotated method.
*
* <p>Delegates to {@link #processEvent(ApplicationEvent)} to give sub-classes
* a chance to deviate from the default. Unwraps the content of a
* {@link PayloadApplicationEvent} if necessary to allow method declaration
* to define any arbitrary event type. If a condition is defined, it is
* evaluated prior to invoking the underlying method.
*
* @author Stephane Nicoll
* @author Juergen Hoeller
* @author Sam Brannen
* @since 4.2
*/
public class ApplicationListenerMethodAdapter implements GenericApplicationListener {
protected final Log logger = LogFactory.getLog(getClass());
private final String beanName;
private final Method method;
private final Class<?> targetClass;
private final Method bridgedMethod;
private final List<ResolvableType> declaredEventTypes;
private final String condition;
private final int order;
private final AnnotatedElementKey methodKey;
private ApplicationContext applicationContext;
private EventExpressionEvaluator evaluator;
public ApplicationListenerMethodAdapter(String beanName, Class<?> targetClass, Method method) {
this.beanName = beanName;
this.method = method;
this.targetClass = targetClass;
this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
EventListener ann = AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class);
this.declaredEventTypes = resolveDeclaredEventTypes(method, ann);
this.condition = (ann != null ? ann.condition() : null);
this.order = resolveOrder(method);
this.methodKey = new AnnotatedElementKey(method, targetClass);
}
private List<ResolvableType> resolveDeclaredEventTypes(Method method, EventListener ann) {
int count = method.getParameterCount();
if (count > 1) {
throw new IllegalStateException(
"Maximum one parameter is allowed for event listener method: " + method);
}
if (ann != null && ann.classes().length > 0) {
List<ResolvableType> types = new ArrayList<>(ann.classes().length);
for (Class<?> eventType : ann.classes()) {
types.add(ResolvableType.forClass(eventType));
}
return types;
}
else {
if (count == 0) {
throw new IllegalStateException(
"Event parameter is mandatory for event listener method: " + method);
}
return Collections.singletonList(ResolvableType.forMethodParameter(method, 0));
}
}
private int resolveOrder(Method method) {
Order ann = AnnotatedElementUtils.findMergedAnnotation(method, Order.class);
return (ann != null ? ann.value() : 0);
}
/**
* Initialize this instance.
*/
void init(ApplicationContext applicationContext, EventExpressionEvaluator evaluator) {
this.applicationContext = applicationContext;
this.evaluator = evaluator;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
processEvent(event);
}
@Override
public boolean supportsEventType(ResolvableType eventType) {
for (ResolvableType declaredEventType : this.declaredEventTypes) {
if (declaredEventType.isAssignableFrom(eventType)) {
return true;
}
else if (PayloadApplicationEvent.class.isAssignableFrom(eventType.getRawClass())) {
ResolvableType payloadType = eventType.as(PayloadApplicationEvent.class).getGeneric();
if (declaredEventType.isAssignableFrom(payloadType)) {
return true;
}
}
}
return eventType.hasUnresolvableGenerics();
}
@Override
public boolean supportsSourceType(Class<?> sourceType) {
return true;
}
@Override
public int getOrder() {
return this.order;
}
/**
* Process the specified {@link ApplicationEvent}, checking if the condition
* match and handling non-null result, if any.
*/
public void processEvent(ApplicationEvent event) {
Object[] args = resolveArguments(event);
if (shouldHandle(event, args)) {
Object result = doInvoke(args);
if (result != null) {
handleResult(result);
}
else {
logger.trace("No result object given - no result to handle");
}
}
}
/**
* Resolve the method arguments to use for the specified {@link ApplicationEvent}.
* <p>These arguments will be used to invoke the method handled by this instance. Can
* return {@code null} to indicate that no suitable arguments could be resolved and
* therefore the method should not be invoked at all for the specified event.
*/
protected Object[] resolveArguments(ApplicationEvent event) {
ResolvableType declaredEventType = getResolvableType(event);
if (declaredEventType == null) {
return null;
}
if (this.method.getParameterCount() == 0) {
return new Object[0];
}
if (!ApplicationEvent.class.isAssignableFrom(declaredEventType.getRawClass()) &&
event instanceof PayloadApplicationEvent) {
return new Object[] {((PayloadApplicationEvent) event).getPayload()};
}
else {
return new Object[] {event};
}
}
protected void handleResult(Object result) {
if (result.getClass().isArray()) {
Object[] events = ObjectUtils.toObjectArray(result);
for (Object event : events) {
publishEvent(event);
}
}
else if (result instanceof Collection<?>) {
Collection<?> events = (Collection<?>) result;
for (Object event : events) {
publishEvent(event);
}
}
else {
publishEvent(result);
}
}
private void publishEvent(Object event) {
if (event != null) {
Assert.notNull(this.applicationContext, "ApplicationContext must no be null");
this.applicationContext.publishEvent(event);
}
}
private boolean shouldHandle(ApplicationEvent event, Object[] args) {
if (args == null) {
return false;
}
String condition = getCondition();
if (StringUtils.hasText(condition)) {
Assert.notNull(this.evaluator, "EventExpressionEvaluator must no be null");
EvaluationContext evaluationContext = this.evaluator.createEvaluationContext(
event, this.targetClass, this.method, args, this.applicationContext);
return this.evaluator.condition(condition, this.methodKey, evaluationContext);
}
return true;
}
/**
* Invoke the event listener method with the given argument values.
*/
protected Object doInvoke(Object... args) {
Object bean = getTargetBean();
ReflectionUtils.makeAccessible(this.bridgedMethod);
try {
return this.bridgedMethod.invoke(bean, args);
}
catch (IllegalArgumentException ex) {
assertTargetBean(this.bridgedMethod, bean, args);
throw new IllegalStateException(getInvocationErrorMessage(bean, ex.getMessage(), args), ex);
}
catch (IllegalAccessException ex) {
throw new IllegalStateException(getInvocationErrorMessage(bean, ex.getMessage(), args), ex);
}
catch (InvocationTargetException ex) {
// Throw underlying exception
Throwable targetException = ex.getTargetException();
if (targetException instanceof RuntimeException) {
throw (RuntimeException) targetException;
}
else {
String msg = getInvocationErrorMessage(bean, "Failed to invoke event listener method", args);
throw new UndeclaredThrowableException(targetException, msg);
}
}
}
/**
* Return the target bean instance to use.
*/
protected Object getTargetBean() {
Assert.notNull(this.applicationContext, "ApplicationContext must no be null");
return this.applicationContext.getBean(this.beanName);
}
/**
* Return the condition to use.
* <p>Matches the {@code condition} attribute of the {@link EventListener}
* annotation or any matching attribute on a composed annotation that
* is meta-annotated with {@code @EventListener}.
*/
protected String getCondition() {
return this.condition;
}
/**
* Add additional details such as the bean type and method signature to
* the given error message.
* @param message error message to append the HandlerMethod details to
*/
protected String getDetailedErrorMessage(Object bean, String message) {
StringBuilder sb = new StringBuilder(message).append("\n");
sb.append("HandlerMethod details: \n");
sb.append("Bean [").append(bean.getClass().getName()).append("]\n");
sb.append("Method [").append(this.bridgedMethod.toGenericString()).append("]\n");
return sb.toString();
}
/**
* Assert that the target bean class is an instance of the class where the given
* method is declared. In some cases the actual bean instance at event-
* processing time may be a JDK dynamic proxy (lazy initialization, prototype
* beans, and others). Event listener beans that require proxying should prefer
* class-based proxy mechanisms.
*/
private void assertTargetBean(Method method, Object targetBean, Object[] args) {
Class<?> methodDeclaringClass = method.getDeclaringClass();
Class<?> targetBeanClass = targetBean.getClass();
if (!methodDeclaringClass.isAssignableFrom(targetBeanClass)) {
String msg = "The event listener method class '" + methodDeclaringClass.getName() +
"' is not an instance of the actual bean class '" +
targetBeanClass.getName() + "'. If the bean requires proxying " +
"(e.g. due to @Transactional), please use class-based proxying.";
throw new IllegalStateException(getInvocationErrorMessage(targetBean, msg, args));
}
}
private String getInvocationErrorMessage(Object bean, String message, Object[] resolvedArgs) {
StringBuilder sb = new StringBuilder(getDetailedErrorMessage(bean, message));
sb.append("Resolved arguments: \n");
for (int i = 0; i < resolvedArgs.length; i++) {
sb.append("[").append(i).append("] ");
if (resolvedArgs[i] == null) {
sb.append("[null] \n");
}
else {
sb.append("[type=").append(resolvedArgs[i].getClass().getName()).append("] ");
sb.append("[value=").append(resolvedArgs[i]).append("]\n");
}
}
return sb.toString();
}
private ResolvableType getResolvableType(ApplicationEvent event) {
ResolvableType payloadType = null;
if (event instanceof PayloadApplicationEvent) {
PayloadApplicationEvent<?> payloadEvent = (PayloadApplicationEvent<?>) event;
payloadType = payloadEvent.getResolvableType().as(
PayloadApplicationEvent.class).getGeneric(0);
}
for (ResolvableType declaredEventType : this.declaredEventTypes) {
if (!ApplicationEvent.class.isAssignableFrom(declaredEventType.getRawClass())
&& payloadType != null) {
if (declaredEventType.isAssignableFrom(payloadType)) {
return declaredEventType;
}
}
if (declaredEventType.getRawClass().isAssignableFrom(event.getClass())) {
return declaredEventType;
}
}
return null;
}
@Override
public String toString() {
return this.method.toGenericString();
}
}
| |
package net.bytebuddy.implementation.bind.annotation;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.bind.MethodDelegationBinder;
import net.bytebuddy.implementation.bytecode.Removal;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.member.MethodReturn;
import java.lang.annotation.Annotation;
import java.util.*;
/**
* This {@link net.bytebuddy.implementation.bind.MethodDelegationBinder} binds
* method by analyzing annotations found on the <i>target</i> method that is subject to a method binding.
*/
public class TargetMethodAnnotationDrivenBinder implements MethodDelegationBinder {
/**
* The processor for performing an actual method delegation.
*/
private final DelegationProcessor delegationProcessor;
/**
* The provider for annotations to be supplied for binding of non-annotated parameters.
*/
private final DefaultsProvider defaultsProvider;
/**
* The termination handler to be applied.
*/
private final TerminationHandler terminationHandler;
/**
* An user-supplied assigner to use for variable assignments.
*/
private final Assigner assigner;
/**
* A delegate for actually invoking a method.
*/
private final MethodInvoker methodInvoker;
/**
* Creates a new method delegation binder that binds method based on annotations found on the target method.
*
* @param parameterBinders A list of parameter binder delegates. Each such delegate is responsible for creating a
* {@link net.bytebuddy.implementation.bind.MethodDelegationBinder.ParameterBinding}
* for a specific annotation.
* @param defaultsProvider A provider that creates an annotation for parameters that are not annotated by any annotation
* that is handled by any of the registered {@code parameterBinders}.
* @param terminationHandler The termination handler to be applied.
* @param assigner An assigner that is supplied to the {@code parameterBinders} and that is used for binding the return value.
* @param methodInvoker A delegate for applying the actual method invocation of the target method.
*/
public TargetMethodAnnotationDrivenBinder(List<ParameterBinder<?>> parameterBinders,
DefaultsProvider defaultsProvider,
TerminationHandler terminationHandler,
Assigner assigner,
MethodInvoker methodInvoker) {
delegationProcessor = DelegationProcessor.of(parameterBinders);
this.defaultsProvider = defaultsProvider;
this.terminationHandler = terminationHandler;
this.assigner = assigner;
this.methodInvoker = methodInvoker;
}
@Override
public MethodBinding bind(Implementation.Target implementationTarget,
MethodDescription source,
MethodDescription target) {
if (IgnoreForBinding.Verifier.check(target)) {
return MethodBinding.Illegal.INSTANCE;
}
StackManipulation methodTermination = terminationHandler.resolve(assigner, source, target);
if (!methodTermination.isValid()) {
return MethodBinding.Illegal.INSTANCE;
}
MethodBinding.Builder methodDelegationBindingBuilder = new MethodBinding.Builder(methodInvoker, target);
Iterator<AnnotationDescription> defaults = defaultsProvider.makeIterator(implementationTarget, source, target);
for (ParameterDescription parameterDescription : target.getParameters()) {
ParameterBinding<?> parameterBinding = delegationProcessor
.handler(parameterDescription.getDeclaredAnnotations(), defaults)
.bind(source,
parameterDescription,
implementationTarget,
assigner);
if (!parameterBinding.isValid() || !methodDelegationBindingBuilder.append(parameterBinding)) {
return MethodBinding.Illegal.INSTANCE;
}
}
return methodDelegationBindingBuilder.build(methodTermination);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
TargetMethodAnnotationDrivenBinder that = (TargetMethodAnnotationDrivenBinder) other;
return assigner.equals(that.assigner)
&& defaultsProvider.equals(that.defaultsProvider)
&& terminationHandler.equals(that.terminationHandler)
&& delegationProcessor.equals(that.delegationProcessor)
&& methodInvoker.equals(that.methodInvoker);
}
@Override
public int hashCode() {
int result = delegationProcessor.hashCode();
result = 31 * result + defaultsProvider.hashCode();
result = 31 * result + terminationHandler.hashCode();
result = 31 * result + assigner.hashCode();
result = 31 * result + methodInvoker.hashCode();
return result;
}
@Override
public String toString() {
return "TargetMethodAnnotationDrivenBinder{" +
"delegationProcessor=" + delegationProcessor +
", defaultsProvider=" + defaultsProvider +
", terminationHandler=" + terminationHandler +
", assigner=" + assigner +
", methodInvoker=" + methodInvoker +
'}';
}
/**
* A parameter binder is used as a delegate for binding a parameter according to a particular annotation type found
* on this parameter.
*
* @param <T> The {@link java.lang.annotation.Annotation#annotationType()} handled by this parameter binder.
*/
@SuppressFBWarnings(value = "IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION", justification = "No circularity, initialization is safe")
public interface ParameterBinder<T extends Annotation> {
/**
* The default parameter binders to be used.
*/
List<ParameterBinder<?>> DEFAULTS = Collections.unmodifiableList(Arrays.<TargetMethodAnnotationDrivenBinder.ParameterBinder<?>>asList(
Argument.Binder.INSTANCE,
AllArguments.Binder.INSTANCE,
Origin.Binder.INSTANCE,
This.Binder.INSTANCE,
Super.Binder.INSTANCE,
Default.Binder.INSTANCE,
SuperCall.Binder.INSTANCE,
DefaultCall.Binder.INSTANCE,
FieldValue.Binder.INSTANCE,
StubValue.Binder.INSTANCE,
Empty.Binder.INSTANCE));
/**
* The annotation type that is handled by this parameter binder.
*
* @return The {@link java.lang.annotation.Annotation#annotationType()} handled by this parameter binder.
*/
Class<T> getHandledType();
/**
* Creates a parameter binding for the given target parameter.
*
* @param annotation The annotation that was cause for the delegation to this argument binder.
* @param source The intercepted source method.
* @param target Tge target parameter that is subject to be bound to
* intercepting the {@code source} method.
* @param implementationTarget The target of the current implementation that is subject to this binding.
* @param assigner An assigner that can be used for applying the binding.
* @return A parameter binding for the requested target method parameter.
*/
ParameterBinding<?> bind(AnnotationDescription.Loadable<T> annotation,
MethodDescription source,
ParameterDescription target,
Implementation.Target implementationTarget,
Assigner assigner);
}
/**
* Implementations of the defaults provider interface create annotations for parameters that are not annotated with
* a known annotation.
*
* @see net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder
*/
public interface DefaultsProvider {
/**
* Creates an iterator from which a value is pulled each time no processable annotation is found on a
* method parameter.
*
* @param implementationTarget The target of the current implementation.
* @param source The source method that is bound to the {@code target} method.
* @param target Tge target method that is subject to be bound by the {@code source} method.
* @return An iterator that supplies default annotations for
*/
Iterator<AnnotationDescription> makeIterator(Implementation.Target implementationTarget,
MethodDescription source,
MethodDescription target);
/**
* A defaults provider that does not supply any defaults. If this defaults provider is used, a target
* method is required to annotate each parameter with a known annotation.
*/
enum Empty implements DefaultsProvider {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Iterator<AnnotationDescription> makeIterator(Implementation.Target implementationTarget,
MethodDescription source,
MethodDescription target) {
return EmptyIterator.INSTANCE;
}
@Override
public String toString() {
return "TargetMethodAnnotationDrivenBinder.DefaultsProvider.Empty." + name();
}
/**
* A trivial iterator without any elements.
*/
protected enum EmptyIterator implements Iterator<AnnotationDescription> {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public boolean hasNext() {
return false;
}
@Override
public AnnotationDescription next() {
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new NoSuchElementException();
}
@Override
public String toString() {
return "TargetMethodAnnotationDrivenBinder.DefaultsProvider.Empty.EmptyIterator." + name();
}
}
}
}
/**
* Responsible for creating a {@link StackManipulation}
* that is applied after the interception method is applied.
*/
public interface TerminationHandler {
/**
* Creates a stack manipulation that is to be applied after the method return.
*
* @param assigner The supplied assigner.
* @param source The source method that is bound to the {@code target} method.
* @param target The target method that is subject to be bound by the {@code source} method.
* @return A stack manipulation that is applied after the method return.
*/
StackManipulation resolve(Assigner assigner, MethodDescription source, MethodDescription target);
/**
* A termination handler that returns the return value of the interception method.
*/
enum Returning implements TerminationHandler {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public StackManipulation resolve(Assigner assigner, MethodDescription source, MethodDescription target) {
return new StackManipulation.Compound(assigner.assign(target.isConstructor()
? target.getDeclaringType().asErasure()
: target.getReturnType().asErasure(),
source.getReturnType().asErasure(),
RuntimeType.Verifier.check(target)), MethodReturn.returning(source.getReturnType().asErasure()));
}
@Override
public String toString() {
return "TargetMethodAnnotationDrivenBinder.TerminationHandler.Returning." + name();
}
}
/**
* A termination handler that pops the return value of the interception method.
*/
enum Dropping implements TerminationHandler {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public StackManipulation resolve(Assigner assigner, MethodDescription source, MethodDescription target) {
return Removal.pop(target.isConstructor()
? target.getDeclaringType().asErasure()
: target.getReturnType().asErasure());
}
@Override
public String toString() {
return "TargetMethodAnnotationDrivenBinder.TerminationHandler.Dropping." + name();
}
}
}
/**
* A delegation processor is a helper class for a
* {@link net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder}
* for performing its actual logic. By outsourcing this logic to this helper class, a cleaner implementation
* can be provided.
*/
protected static class DelegationProcessor {
/**
* A map of registered annotation types to the binder that is responsible for binding a parameter
* that is annotated with the given annotation.
*/
private final Map<TypeDescription, ParameterBinder<?>> parameterBinders;
/**
* Creates a new delegation processor.
*
* @param parameterBinders A mapping of parameter binders by their handling type.
*/
protected DelegationProcessor(Map<TypeDescription, ParameterBinder<?>> parameterBinders) {
this.parameterBinders = parameterBinders;
}
/**
* Creates a new delegation processor.
*
* @param parameterBinders A list of parameter binder delegates. Each such delegate is responsible for creating
* a {@link net.bytebuddy.implementation.bind.MethodDelegationBinder.ParameterBinding}
* for a specific annotation.
* @return A corresponding delegation processor.
*/
protected static DelegationProcessor of(List<ParameterBinder<?>> parameterBinders) {
Map<TypeDescription, ParameterBinder<?>> parameterBinderMap = new HashMap<TypeDescription, ParameterBinder<?>>();
for (ParameterBinder<?> parameterBinder : parameterBinders) {
if (parameterBinderMap.put(new TypeDescription.ForLoadedType(parameterBinder.getHandledType()), parameterBinder) != null) {
throw new IllegalArgumentException("Attempt to bind two handlers to " + parameterBinder.getHandledType());
}
}
return new DelegationProcessor(parameterBinderMap);
}
/**
* Locates a handler which is responsible for processing the given parameter. If no explicit handler can
* be located, a fallback handler is provided.
*
* @param annotations The annotations of the parameter for which a handler should be provided.
* @param defaults The defaults provider to be queried if no explicit handler mapping could be found.
* @return A handler for processing the parameter with the given annotations.
*/
private Handler handler(List<AnnotationDescription> annotations, Iterator<AnnotationDescription> defaults) {
Handler handler = null;
for (AnnotationDescription annotation : annotations) {
ParameterBinder<?> parameterBinder = parameterBinders.get(annotation.getAnnotationType());
if (parameterBinder != null && handler != null) {
throw new IllegalStateException("Ambiguous binding for parameter annotated with two handled annotation types");
} else if (parameterBinder != null /* && handler == null */) {
handler = makeHandler(parameterBinder, annotation);
}
}
if (handler == null) { // No handler was found: attempt using defaults provider.
if (defaults.hasNext()) {
AnnotationDescription defaultAnnotation = defaults.next();
ParameterBinder<?> parameterBinder = parameterBinders.get(defaultAnnotation.getAnnotationType());
if (parameterBinder == null) {
return Handler.Unbound.INSTANCE;
} else {
handler = makeHandler(parameterBinder, defaultAnnotation);
}
} else {
return Handler.Unbound.INSTANCE;
}
}
return handler;
}
/**
* Creates a handler for a given annotation.
*
* @param parameterBinder The parameter binder that should process an annotation.
* @param annotation An annotation instance that can be understood by this parameter binder.
* @return A handler for processing the given annotation.
*/
@SuppressWarnings("unchecked")
private Handler makeHandler(ParameterBinder<?> parameterBinder, AnnotationDescription annotation) {
return new Handler.Bound<Annotation>((ParameterBinder<Annotation>) parameterBinder,
(AnnotationDescription.Loadable<Annotation>) annotation.prepare(parameterBinder.getHandledType()));
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& parameterBinders.equals(((DelegationProcessor) other).parameterBinders);
}
@Override
public int hashCode() {
return parameterBinders.hashCode();
}
@Override
public String toString() {
return "TargetMethodAnnotationDrivenBinder.DelegationProcessor{" +
"parameterBinders=" + parameterBinders +
'}';
}
/**
* A handler is responsible for processing a parameter's binding.
*/
protected interface Handler {
/**
* Handles a parameter binding.
*
* @param source The intercepted source method.
* @param target The target parameter that is subject to binding.
* @param implementationTarget The target of the current implementation.
* @param assigner An assigner that can be used for applying the binding.
* @return A parameter binding that reflects the given arguments.
*/
ParameterBinding<?> bind(MethodDescription source,
ParameterDescription target,
Implementation.Target implementationTarget,
Assigner assigner);
/**
* An unbound handler is a fallback for returning an illegal binding for parameters for which no parameter
* binder could be located.
*/
enum Unbound implements Handler {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public ParameterBinding<?> bind(MethodDescription source,
ParameterDescription target,
Implementation.Target implementationTarget,
Assigner assigner) {
return ParameterBinding.Illegal.INSTANCE;
}
@Override
public String toString() {
return "TargetMethodAnnotationDrivenBinder.DelegationProcessor.Handler.Unbound." + name();
}
}
/**
* A bound handler represents an unambiguous parameter binder that was located for a given array of
* annotations.
*
* @param <T> The annotation type of a given handler.
*/
class Bound<T extends Annotation> implements Handler {
/**
* The parameter binder that is actually responsible for binding the parameter.
*/
private final ParameterBinder<T> parameterBinder;
/**
* The annotation value that lead to the binding of this handler.
*/
private final AnnotationDescription.Loadable<T> annotation;
/**
* Creates a new bound handler.
*
* @param parameterBinder The parameter binder that is actually responsible for binding the parameter.
* @param annotation The annotation value that lead to the binding of this handler.
*/
public Bound(ParameterBinder<T> parameterBinder, AnnotationDescription.Loadable<T> annotation) {
this.parameterBinder = parameterBinder;
this.annotation = annotation;
}
@Override
public ParameterBinding<?> bind(MethodDescription source,
ParameterDescription target,
Implementation.Target implementationTarget,
Assigner assigner) {
return parameterBinder.bind(annotation,
source,
target,
implementationTarget,
assigner);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& parameterBinder.equals(((Bound<?>) other).parameterBinder)
&& annotation.equals(((Bound<?>) other).annotation);
}
@Override
public int hashCode() {
int result = parameterBinder.hashCode();
result = 31 * result + annotation.hashCode();
return result;
}
@Override
public String toString() {
return "TargetMethodAnnotationDrivenBinder.DelegationProcessor.Handler.Bound{" +
"parameterBinder=" + parameterBinder +
", annotation=" + annotation +
'}';
}
}
}
}
}
| |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tcl.simpletv.launcher2;
import android.app.SearchManager;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Xml;
import com.tcl.simpletv.launcher2.R;
import com.tcl.simpletv.launcher2.LauncherSettings.Favorites;
import com.tcl.simpletv.launcher2.toolbar.ToolbarDatabaseHelper;
import com.tcl.simpletv.launcher2.toolbar.ToolbarUtilities;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class LauncherProvider extends ContentProvider {
private static final String TAG = "Launcher.LauncherProvider";
private static final boolean LOGD = false;
private static final String DATABASE_NAME = "launcher.db";
private static final int DATABASE_VERSION = 12;
static final String AUTHORITY = "com.tcl.simpletv.launcher2.settings";
static final String TABLE_FAVORITES = "favorites";
static final String PARAMETER_NOTIFY = "notify";
static final String DB_CREATED_BUT_DEFAULT_WORKSPACE_NOT_LOADED = "DB_CREATED_BUT_DEFAULT_WORKSPACE_NOT_LOADED";
static final String DEFAULT_WORKSPACE_RESOURCE_ID = "DEFAULT_WORKSPACE_RESOURCE_ID";
private static final String ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE = "com.android.launcher.action.APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE";
/**
* {@link Uri} triggered at any registered
* {@link android.database.ContentObserver} when
* {@link AppWidgetHost#deleteHost()} is called during database creation.
* Use this to recall {@link AppWidgetHost#startListening()} if needed.
*/
static final Uri CONTENT_APPWIDGET_RESET_URI = Uri.parse("content://" + AUTHORITY
+ "/appWidgetReset");
private DatabaseHelper mOpenHelper;
private ToolbarDatabaseHelper mtbDbHelper;
private boolean isFrist = true;
private String[] favoriteApp_name = new String[12];
@Override
public boolean onCreate() {
mOpenHelper = new DatabaseHelper(getContext());
//Toolbar start
mtbDbHelper = new ToolbarDatabaseHelper(getContext());
SharedPreferences favorite_settings = getContext().getSharedPreferences("favoriteSetting",
getContext().MODE_PRIVATE);
isFrist = favorite_settings.getBoolean("isFrist", true);
SharedPreferences.Editor editor = favorite_settings.edit();
editor.putBoolean("isFrist", false);
editor.commit();
Log.v(TAG, "isFrist= " + isFrist);
if (isFrist) {
favoriteApp_name = getContext().getResources().getStringArray(R.array.toolbar_default_app_arr);
Log.v(TAG, "toolbar_default_packagename.length=" + favoriteApp_name.length);
for (int i = 0; i < favoriteApp_name.length; i++) {
Log.v(TAG, favoriteApp_name[i]);
ToolbarUtilities.addFavorites(getContext(),favoriteApp_name[i]);
}
}else{//Power-On, refresh ToolbarUtilities.favoriteList
ToolbarUtilities.queryFavoritesdb(getContext());
}
//Toolbar end
((LauncherApplication) getContext()).setLauncherProvider(this);
return true;
}
@Override
public String getType(Uri uri) {
SqlArguments args = new SqlArguments(uri, null, null);
if (TextUtils.isEmpty(args.where)) {
return "vnd.android.cursor.dir/" + args.table;
} else {
return "vnd.android.cursor.item/" + args.table;
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(args.table);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
result.setNotificationUri(getContext().getContentResolver(), uri);
return result;
}
private static long dbInsertAndCheck(DatabaseHelper helper, SQLiteDatabase db, String table,
String nullColumnHack, ContentValues values) {
if (!values.containsKey(LauncherSettings.Favorites._ID)) {
throw new RuntimeException("Error: attempting to add item without specifying an id");
}
return db.insert(table, nullColumnHack, values);
}
private static void deleteId(SQLiteDatabase db, long id) {
Uri uri = LauncherSettings.Favorites.getContentUri(id, false);
SqlArguments args = new SqlArguments(uri, null, null);
db.delete(args.table, args.where, args.args);
}
@Override
public Uri insert(Uri uri, ContentValues initialValues) {
SqlArguments args = new SqlArguments(uri);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
if (rowId <= 0)
return null;
uri = ContentUris.withAppendedId(uri, rowId);
sendNotify(uri);
return uri;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
SqlArguments args = new SqlArguments(uri);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
int numValues = values.length;
for (int i = 0; i < numValues; i++) {
if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
return 0;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
sendNotify(uri);
return values.length;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count = db.delete(args.table, args.where, args.args);
if (count > 0)
sendNotify(uri);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count = db.update(args.table, values, args.where, args.args);
if (count > 0)
sendNotify(uri);
return count;
}
private void sendNotify(Uri uri) {
String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
if (notify == null || "true".equals(notify)) {
getContext().getContentResolver().notifyChange(uri, null);
}
}
public long generateNewId() {
return mOpenHelper.generateNewId();
}
/**
* @param workspaceResId
* that can be 0 to use default or non-zero for specific resource
*/
synchronized public void loadDefaultFavoritesIfNecessary(int origWorkspaceResId) {
// String spKey = LauncherApplication.getSharedPreferencesKey();
// SharedPreferences sp = getContext().getSharedPreferences(spKey,
// Context.MODE_PRIVATE);
SharedPreferences sp = LauncherApplication.getPreferenceUtils(getContext())
.getsSharedPreferences();
if (sp.getBoolean(DB_CREATED_BUT_DEFAULT_WORKSPACE_NOT_LOADED, false)) {
int workspaceResId = origWorkspaceResId;
// Use default workspace resource if none provided
if (workspaceResId == 0) {
workspaceResId = sp.getInt(DEFAULT_WORKSPACE_RESOURCE_ID, R.xml.default_workspace);
}
// Populate favorites table with initial favorites
SharedPreferences.Editor editor = sp.edit();
editor.remove(DB_CREATED_BUT_DEFAULT_WORKSPACE_NOT_LOADED);
if (origWorkspaceResId != 0) {
editor.putInt(DEFAULT_WORKSPACE_RESOURCE_ID, origWorkspaceResId);
}
Log.w(TAG, "2131099648workspaceResId=" + workspaceResId);
mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), workspaceResId);
editor.commit();
}
}
private static class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG_FAVORITES = "favorites";
private static final String TAG_FAVORITE = "favorite";
private static final String TAG_CLOCK = "clock";
private static final String TAG_SEARCH = "search";
private static final String TAG_APPWIDGET = "appwidget";
private static final String TAG_SHORTCUT = "shortcut";
private static final String TAG_FOLDER = "folder";
private static final String TAG_EXTRA = "extra";
private final Context mContext;
private final AppWidgetHost mAppWidgetHost;
private long mMaxId = -1;
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
mAppWidgetHost = new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
// In the case where neither onCreate nor onUpgrade gets called, we
// read the maxId from
// the DB here
if (mMaxId == -1) {
mMaxId = initializeMaxId(getWritableDatabase());
}
}
/**
* Send notification that we've deleted the {@link AppWidgetHost},
* probably as part of the initial database creation. The receiver may
* want to re-call {@link AppWidgetHost#startListening()} to ensure
* callbacks are correctly set.
*/
private void sendAppWidgetResetNotify() {
final ContentResolver resolver = mContext.getContentResolver();
resolver.notifyChange(CONTENT_APPWIDGET_RESET_URI, null);
}
@Override
public void onCreate(SQLiteDatabase db) {
if (LOGD)
Log.d(TAG, "creating new launcher database");
mMaxId = 1;
db.execSQL("CREATE TABLE favorites (" + "_id INTEGER PRIMARY KEY," + "title TEXT,"
+ "intent TEXT," + "container INTEGER," + "screen INTEGER," + "cellX INTEGER,"
+ "cellY INTEGER," + "spanX INTEGER," + "spanY INTEGER," + "itemType INTEGER,"
+ "appWidgetId INTEGER NOT NULL DEFAULT -1," + "isShortcut INTEGER,"
+ "iconType INTEGER," + "iconPackage TEXT," + "iconResource TEXT,"
+ "icon BLOB," + "uri TEXT," + "displayMode INTEGER" + ");");
// Database was just created, so wipe any previous widgets
if (mAppWidgetHost != null) {
mAppWidgetHost.deleteHost();
sendAppWidgetResetNotify();
}
if (!convertDatabase(db)) {
// Set a shared pref so that we know we need to load the default
// workspace later
setFlagToLoadDefaultWorkspaceLater();
}
}
private void setFlagToLoadDefaultWorkspaceLater() {
// String spKey = LauncherApplication.getSharedPreferencesKey();
// SharedPreferences sp = mContext.getSharedPreferences(spKey,
// Context.MODE_PRIVATE);
SharedPreferences sp = LauncherApplication.getPreferenceUtils(mContext)
.getsSharedPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(DB_CREATED_BUT_DEFAULT_WORKSPACE_NOT_LOADED, true);
editor.commit();
}
private boolean convertDatabase(SQLiteDatabase db) {
if (LOGD)
Log.d(TAG, "converting database from an older format, but not onUpgrade");
boolean converted = false;
final Uri uri = Uri.parse("content://" + Settings.AUTHORITY
+ "/old_favorites?notify=true");
final ContentResolver resolver = mContext.getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(uri, null, null, null, null);
} catch (Exception e) {
// Ignore
}
// We already have a favorites database in the old provider
if (cursor != null && cursor.getCount() > 0) {
try {
converted = copyFromCursor(db, cursor) > 0;
} finally {
cursor.close();
}
if (converted) {
resolver.delete(uri, null, null);
}
}
if (converted) {
// Convert widgets from this import into widgets
if (LOGD)
Log.d(TAG, "converted and now triggering widget upgrade");
convertWidgets(db);
}
return converted;
}
private int copyFromCursor(SQLiteDatabase db, Cursor c) {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c
.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c
.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c
.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c
.getColumnIndexOrThrow(LauncherSettings.Favorites.DISPLAY_MODE);
ContentValues[] rows = new ContentValues[c.getCount()];
int i = 0;
while (c.moveToNext()) {
ContentValues values = new ContentValues(c.getColumnCount());
values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
values.put(LauncherSettings.Favorites.INTENT, c.getString(intentIndex));
values.put(LauncherSettings.Favorites.TITLE, c.getString(titleIndex));
values.put(LauncherSettings.Favorites.ICON_TYPE, c.getInt(iconTypeIndex));
values.put(LauncherSettings.Favorites.ICON, c.getBlob(iconIndex));
values.put(LauncherSettings.Favorites.ICON_PACKAGE, c.getString(iconPackageIndex));
values.put(LauncherSettings.Favorites.ICON_RESOURCE, c.getString(iconResourceIndex));
values.put(LauncherSettings.Favorites.CONTAINER, c.getInt(containerIndex));
values.put(LauncherSettings.Favorites.ITEM_TYPE, c.getInt(itemTypeIndex));
values.put(LauncherSettings.Favorites.APPWIDGET_ID, -1);
values.put(LauncherSettings.Favorites.SCREEN, c.getInt(screenIndex));
values.put(LauncherSettings.Favorites.CELLX, c.getInt(cellXIndex));
values.put(LauncherSettings.Favorites.CELLY, c.getInt(cellYIndex));
values.put(LauncherSettings.Favorites.URI, c.getString(uriIndex));
values.put(LauncherSettings.Favorites.DISPLAY_MODE, c.getInt(displayModeIndex));
rows[i++] = values;
}
db.beginTransaction();
int total = 0;
try {
int numValues = rows.length;
for (i = 0; i < numValues; i++) {
if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, rows[i]) < 0) {
return 0;
} else {
total++;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return total;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (LOGD)
Log.d(TAG, "onUpgrade triggered");
int version = oldVersion;
if (version < 3) {
// upgrade 1,2 -> 3 added appWidgetId column
db.beginTransaction();
try {
// Insert new column for holding appWidgetIds
db.execSQL("ALTER TABLE favorites "
+ "ADD COLUMN appWidgetId INTEGER NOT NULL DEFAULT -1;");
db.setTransactionSuccessful();
version = 3;
} catch (SQLException ex) {
// Old version remains, which means we wipe old data
Log.e(TAG, ex.getMessage(), ex);
} finally {
db.endTransaction();
}
// Convert existing widgets only if table upgrade was successful
if (version == 3) {
convertWidgets(db);
}
}
if (version < 4) {
version = 4;
}
// Where's version 5?
// - Donut and sholes on 2.0 shipped with version 4 of launcher1.
// - Passion shipped on 2.1 with version 6 of launcher2
// - Sholes shipped on 2.1r1 (aka Mr. 3) with version 5 of launcher
// 1
// but version 5 on there was the updateContactsShortcuts change
// which was version 6 in launcher 2 (first shipped on passion
// 2.1r1).
// The updateContactsShortcuts change is idempotent, so running it
// twice
// is okay so we'll do that when upgrading the devices that shipped
// with it.
if (version < 6) {
// We went from 3 to 5 screens. Move everything 1 to the right
db.beginTransaction();
try {
db.execSQL("UPDATE favorites SET screen=(screen + 1);");
db.setTransactionSuccessful();
} catch (SQLException ex) {
// Old version remains, which means we wipe old data
Log.e(TAG, ex.getMessage(), ex);
} finally {
db.endTransaction();
}
// We added the fast track.
if (updateContactsShortcuts(db)) {
version = 6;
}
}
if (version < 7) {
// Version 7 gets rid of the special search widget.
convertWidgets(db);
version = 7;
}
if (version < 8) {
// Version 8 (froyo) has the icons all normalized. This should
// already be the case in practice, but we now rely on it and
// don't
// resample the images each time.
normalizeIcons(db);
version = 8;
}
if (version < 9) {
// The max id is not yet set at this point (onUpgrade is
// triggered in the ctor
// before it gets a change to get set, so we need to read it
// here when we use it)
if (mMaxId == -1) {
mMaxId = initializeMaxId(db);
}
// Add default hotseat icons
loadFavorites(db, R.xml.update_workspace);
version = 9;
}
// We bumped the version three time during JB, once to update the
// launch flags, once to
// update the override for the default launch animation and once to
// set the mimetype
// to improve startup performance
if (version < 12) {
// Contact shortcuts need a different set of flags to be
// launched now
// The updateContactsShortcuts change is idempotent, so we can
// keep using it like
// back in the Donut days
updateContactsShortcuts(db);
version = 12;
}
if (version != DATABASE_VERSION) {
Log.w(TAG, "Destroying all old data.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
onCreate(db);
}
}
private boolean updateContactsShortcuts(SQLiteDatabase db) {
final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE,
new int[] { Favorites.ITEM_TYPE_SHORTCUT });
Cursor c = null;
final String actionQuickContact = "com.android.contacts.action.QUICK_CONTACT";
db.beginTransaction();
try {
// Select and iterate through each matching widget
c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.INTENT },
selectWhere, null, null, null, null);
if (c == null)
return false;
if (LOGD)
Log.d(TAG, "found upgrade cursor count=" + c.getCount());
final int idIndex = c.getColumnIndex(Favorites._ID);
final int intentIndex = c.getColumnIndex(Favorites.INTENT);
while (c.moveToNext()) {
long favoriteId = c.getLong(idIndex);
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
try {
final Intent intent = Intent.parseUri(intentUri, 0);
android.util.Log.d("Home", intent.toString());
final Uri uri = intent.getData();
if (uri != null) {
final String data = uri.toString();
if ((Intent.ACTION_VIEW.equals(intent.getAction()) || actionQuickContact
.equals(intent.getAction()))
&& (data.startsWith("content://contacts/people/") || data
.startsWith("content://com.android.contacts/"
+ "contacts/lookup/"))) {
final Intent newIntent = new Intent(actionQuickContact);
// When starting from the launcher, start in
// a new, cleared task
// CLEAR_WHEN_TASK_RESET cannot reset the
// root of a task, so we
// clear the whole thing preemptively here
// since
// QuickContactActivity will finish itself
// when launching other
// detail activities.
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
newIntent.putExtra(
Launcher.INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);
newIntent.setData(uri);
// Determine the type and also put that in
// the shortcut
// (that can speed up launch a bit)
newIntent.setDataAndType(uri, newIntent.resolveType(mContext));
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.INTENT,
newIntent.toUri(0));
String updateWhere = Favorites._ID + "=" + favoriteId;
db.update(TABLE_FAVORITES, values, updateWhere, null);
}
}
} catch (RuntimeException ex) {
Log.e(TAG, "Problem upgrading shortcut", ex);
} catch (URISyntaxException e) {
Log.e(TAG, "Problem upgrading shortcut", e);
}
}
}
db.setTransactionSuccessful();
} catch (SQLException ex) {
Log.w(TAG, "Problem while upgrading contacts", ex);
return false;
} finally {
db.endTransaction();
if (c != null) {
c.close();
}
}
return true;
}
private void normalizeIcons(SQLiteDatabase db) {
Log.d(TAG, "normalizing icons");
db.beginTransaction();
Cursor c = null;
SQLiteStatement update = null;
try {
boolean logged = false;
update = db.compileStatement("UPDATE favorites " + "SET icon=? WHERE _id=?");
c = db.rawQuery("SELECT _id, icon FROM favorites WHERE iconType="
+ Favorites.ICON_TYPE_BITMAP, null);
final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
final int iconIndex = c.getColumnIndexOrThrow(Favorites.ICON);
while (c.moveToNext()) {
long id = c.getLong(idIndex);
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = Utilities.resampleIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), mContext);
if (bitmap != null) {
update.bindLong(1, id);
data = ItemInfo.flattenBitmap(bitmap);
if (data != null) {
update.bindBlob(2, data);
update.execute();
}
bitmap.recycle();
}
} catch (Exception e) {
if (!logged) {
Log.e(TAG, "Failed normalizing icon " + id, e);
} else {
Log.e(TAG, "Also failed normalizing icon " + id);
}
logged = true;
}
}
db.setTransactionSuccessful();
} catch (SQLException ex) {
Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
} finally {
db.endTransaction();
if (update != null) {
update.close();
}
if (c != null) {
c.close();
}
}
}
// Generates a new ID to use for an object in your database. This method
// should be only
// called from the main UI thread. As an exception, we do call it when
// we call the
// constructor from the worker thread; however, this doesn't extend
// until after the
// constructor is called, and we only pass a reference to
// LauncherProvider to LauncherApp
// after that point
public long generateNewId() {
if (mMaxId < 0) {
throw new RuntimeException("Error: max id was not initialized");
}
mMaxId += 1;
return mMaxId;
}
private long initializeMaxId(SQLiteDatabase db) {
Cursor c = db.rawQuery("SELECT MAX(_id) FROM favorites", null);
// get the result
final int maxIdIndex = 0;
long id = -1;
if (c != null && c.moveToNext()) {
id = c.getLong(maxIdIndex);
}
if (c != null) {
c.close();
}
if (id == -1) {
throw new RuntimeException("Error: could not query max id");
}
return id;
}
/**
* Upgrade existing clock and photo frame widgets into their new widget
* equivalents.
*/
private void convertWidgets(SQLiteDatabase db) {
final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
final int[] bindSources = new int[] { Favorites.ITEM_TYPE_WIDGET_CLOCK,
Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME, Favorites.ITEM_TYPE_WIDGET_SEARCH, };
final String selectWhere = buildOrWhereString(Favorites.ITEM_TYPE, bindSources);
Cursor c = null;
db.beginTransaction();
try {
// Select and iterate through each matching widget
c = db.query(TABLE_FAVORITES, new String[] { Favorites._ID, Favorites.ITEM_TYPE },
selectWhere, null, null, null, null);
if (LOGD)
Log.d(TAG, "found upgrade cursor count=" + c.getCount());
final ContentValues values = new ContentValues();
while (c != null && c.moveToNext()) {
long favoriteId = c.getLong(0);
int favoriteType = c.getInt(1);
// Allocate and update database with new appWidgetId
try {
int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
if (LOGD) {
Log.d(TAG, "allocated appWidgetId=" + appWidgetId + " for favoriteId="
+ favoriteId);
}
values.clear();
values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
values.put(Favorites.APPWIDGET_ID, appWidgetId);
// Original widgets might not have valid spans when
// upgrading
if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
values.put(LauncherSettings.Favorites.SPANX, 4);
values.put(LauncherSettings.Favorites.SPANY, 1);
} else {
values.put(LauncherSettings.Favorites.SPANX, 2);
values.put(LauncherSettings.Favorites.SPANY, 2);
}
String updateWhere = Favorites._ID + "=" + favoriteId;
db.update(TABLE_FAVORITES, values, updateWhere, null);
if (favoriteType == Favorites.ITEM_TYPE_WIDGET_CLOCK) {
// TODO: check return value
appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
new ComponentName("com.android.alarmclock",
"com.android.alarmclock.AnalogAppWidgetProvider"));
} else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
// TODO: check return value
appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
new ComponentName("com.android.camera",
"com.android.camera.PhotoAppWidgetProvider"));
} else if (favoriteType == Favorites.ITEM_TYPE_WIDGET_SEARCH) {
// TODO: check return value
appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
getSearchWidgetProvider());
}
} catch (RuntimeException ex) {
Log.e(TAG, "Problem allocating appWidgetId", ex);
}
}
db.setTransactionSuccessful();
} catch (SQLException ex) {
Log.w(TAG, "Problem while allocating appWidgetIds for existing widgets", ex);
} finally {
db.endTransaction();
if (c != null) {
c.close();
}
}
}
private static final void beginDocument(XmlPullParser parser, String firstElementName)
throws XmlPullParserException, IOException {
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG
&& type != XmlPullParser.END_DOCUMENT) {
;
}
if (type != XmlPullParser.START_TAG) {
throw new XmlPullParserException("No start tag found");
}
if (!parser.getName().equals(firstElementName)) {
throw new XmlPullParserException("Unexpected start tag: found " + parser.getName()
+ ", expected " + firstElementName);
}
}
/**
* Loads the default set of favorite packages from an xml file.
*
* @param db
* The database to write the values into
* @param filterContainerId
* The specific container id of items to load
*/
private int loadFavorites(SQLiteDatabase db, int workspaceResourceId) {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ContentValues values = new ContentValues();
PackageManager packageManager = mContext.getPackageManager();
int allAppsButtonRank = mContext.getResources().getInteger(
R.integer.hotseat_all_apps_index);
int i = 0;
try {
XmlResourceParser parser = mContext.getResources().getXml(workspaceResourceId);
AttributeSet attrs = Xml.asAttributeSet(parser);
beginDocument(parser, TAG_FAVORITES);
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
&& type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
boolean added = false;
final String name = parser.getName();
TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.Favorite);
long container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
if (a.hasValue(R.styleable.Favorite_container)) {
container = Long.valueOf(a.getString(R.styleable.Favorite_container));
}
String screen = a.getString(R.styleable.Favorite_screen);
String x = a.getString(R.styleable.Favorite_x);
String y = a.getString(R.styleable.Favorite_y);
// If we are adding to the hotseat, the screen is used as
// the position in the
// hotseat. This screen can't be at position 0 because
// AllApps is in the
// zeroth position.
if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT
&& Integer.valueOf(screen) == allAppsButtonRank) {
throw new RuntimeException("Invalid screen position for hotseat item");
}
values.clear();
values.put(LauncherSettings.Favorites.CONTAINER, container);
values.put(LauncherSettings.Favorites.SCREEN, screen);
values.put(LauncherSettings.Favorites.CELLX, x);
values.put(LauncherSettings.Favorites.CELLY, y);
Log.w(TAG, "name=" + name.toString());
Log.w(TAG, "values=" + values.toString());
if (TAG_FAVORITE.equals(name)) {
long id = addAppShortcut(db, values, a, packageManager, intent);
added = id >= 0;
} else if (TAG_SEARCH.equals(name)) {
added = addSearchWidget(db, values);
} else if (TAG_CLOCK.equals(name)) {
added = addClockWidget(db, values);
} else if (TAG_APPWIDGET.equals(name)) {
added = addAppWidget(parser, attrs, type, db, values, a, packageManager);
} else if (TAG_SHORTCUT.equals(name)) {
long id = addUriShortcut(db, values, a);
added = id >= 0;
} else if (TAG_FOLDER.equals(name)) {
String title;
int titleResId = a.getResourceId(R.styleable.Favorite_title, -1);
if (titleResId != -1) {
title = mContext.getResources().getString(titleResId);
} else {
title = mContext.getResources().getString(R.string.folder_name);
}
values.put(LauncherSettings.Favorites.TITLE, title);
long folderId = addFolder(db, values);
added = folderId >= 0;
ArrayList<Long> folderItems = new ArrayList<Long>();
int folderDepth = parser.getDepth();
while ((type = parser.next()) != XmlPullParser.END_TAG
|| parser.getDepth() > folderDepth) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String folder_item_name = parser.getName();
TypedArray ar = mContext.obtainStyledAttributes(attrs,
R.styleable.Favorite);
values.clear();
values.put(LauncherSettings.Favorites.CONTAINER, folderId);
if (TAG_FAVORITE.equals(folder_item_name) && folderId >= 0) {
long id = addAppShortcut(db, values, ar, packageManager, intent);
if (id >= 0) {
folderItems.add(id);
}
} else if (TAG_SHORTCUT.equals(folder_item_name) && folderId >= 0) {
long id = addUriShortcut(db, values, ar);
if (id >= 0) {
folderItems.add(id);
}
} else {
throw new RuntimeException("Folders can "
+ "contain only shortcuts");
}
ar.recycle();
}
// We can only have folders with >= 2 items, so we need
// to remove the
// folder and clean up if less than 2 items were
// included, or some
// failed to add, and less than 2 were actually added
if (folderItems.size() < 2 && folderId >= 0) {
// We just delete the folder and any items that made
// it
deleteId(db, folderId);
if (folderItems.size() > 0) {
deleteId(db, folderItems.get(0));
}
added = false;
}
}
if (added)
i++;
a.recycle();
}
} catch (XmlPullParserException e) {
Log.w(TAG, "Got exception parsing favorites.", e);
} catch (IOException e) {
Log.w(TAG, "Got exception parsing favorites.", e);
} catch (RuntimeException e) {
Log.w(TAG, "Got exception parsing favorites.", e);
}
return i;
}
private long addAppShortcut(SQLiteDatabase db, ContentValues values, TypedArray a,
PackageManager packageManager, Intent intent) {
long id = -1;
ActivityInfo info;
String packageName = a.getString(R.styleable.Favorite_packageName);
String className = a.getString(R.styleable.Favorite_className);
try {
ComponentName cn;
try {
cn = new ComponentName(packageName, className);
info = packageManager.getActivityInfo(cn, 0);
} catch (PackageManager.NameNotFoundException nnfe) {
String[] packages = packageManager
.currentToCanonicalPackageNames(new String[] { packageName });
cn = new ComponentName(packages[0], className);
info = packageManager.getActivityInfo(cn, 0);
}
id = generateNewId();
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
values.put(Favorites.INTENT, intent.toUri(0));
values.put(Favorites.TITLE, info.loadLabel(packageManager).toString());
values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPLICATION);
values.put(Favorites.SPANX, 1);
values.put(Favorites.SPANY, 1);
values.put(Favorites._ID, generateNewId());
if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
return -1;
}
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "Unable to add favorite: " + packageName + "/" + className, e);
}
return id;
}
private long addFolder(SQLiteDatabase db, ContentValues values) {
values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
values.put(Favorites.SPANX, 1);
values.put(Favorites.SPANY, 1);
long id = generateNewId();
values.put(Favorites._ID, id);
if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) <= 0) {
return -1;
} else {
return id;
}
}
private ComponentName getSearchWidgetProvider() {
SearchManager searchManager = (SearchManager) mContext
.getSystemService(Context.SEARCH_SERVICE);
ComponentName searchComponent = searchManager.getGlobalSearchActivity();
if (searchComponent == null)
return null;
return getProviderInPackage(searchComponent.getPackageName());
}
/**
* Gets an appwidget provider from the given package. If the package
* contains more than one appwidget provider, an arbitrary one is
* returned.
*/
private ComponentName getProviderInPackage(String packageName) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
List<AppWidgetProviderInfo> providers = appWidgetManager.getInstalledProviders();
if (providers == null)
return null;
final int providerCount = providers.size();
for (int i = 0; i < providerCount; i++) {
ComponentName provider = providers.get(i).provider;
if (provider != null && provider.getPackageName().equals(packageName)) {
return provider;
}
}
return null;
}
private boolean addSearchWidget(SQLiteDatabase db, ContentValues values) {
ComponentName cn = getSearchWidgetProvider();
return addAppWidget(db, values, cn, 4, 1, null);
}
private boolean addClockWidget(SQLiteDatabase db, ContentValues values) {
ComponentName cn = new ComponentName("com.android.alarmclock",
"com.android.alarmclock.AnalogAppWidgetProvider");
return addAppWidget(db, values, cn, 2, 2, null);
}
private boolean addAppWidget(XmlResourceParser parser, AttributeSet attrs, int type,
SQLiteDatabase db, ContentValues values, TypedArray a, PackageManager packageManager)
throws XmlPullParserException, IOException {
String packageName = a.getString(R.styleable.Favorite_packageName);
String className = a.getString(R.styleable.Favorite_className);
if (packageName == null || className == null) {
return false;
}
boolean hasPackage = true;
ComponentName cn = new ComponentName(packageName, className);
try {
packageManager.getReceiverInfo(cn, 0);
} catch (Exception e) {
String[] packages = packageManager
.currentToCanonicalPackageNames(new String[] { packageName });
cn = new ComponentName(packages[0], className);
try {
packageManager.getReceiverInfo(cn, 0);
} catch (Exception e1) {
hasPackage = false;
}
}
if (hasPackage) {
int spanX = a.getInt(R.styleable.Favorite_spanX, 0);
int spanY = a.getInt(R.styleable.Favorite_spanY, 0);
// Read the extras
Bundle extras = new Bundle();
int widgetDepth = parser.getDepth();
while ((type = parser.next()) != XmlPullParser.END_TAG
|| parser.getDepth() > widgetDepth) {
if (type != XmlPullParser.START_TAG) {
continue;
}
TypedArray ar = mContext.obtainStyledAttributes(attrs, R.styleable.Extra);
if (TAG_EXTRA.equals(parser.getName())) {
String key = ar.getString(R.styleable.Extra_key);
String value = ar.getString(R.styleable.Extra_value);
if (key != null && value != null) {
extras.putString(key, value);
} else {
throw new RuntimeException("Widget extras must have a key and value");
}
} else {
throw new RuntimeException("Widgets can contain only extras");
}
ar.recycle();
}
return addAppWidget(db, values, cn, spanX, spanY, extras);
}
return false;
}
private boolean addAppWidget(SQLiteDatabase db, ContentValues values, ComponentName cn,
int spanX, int spanY, Bundle extras) {
boolean allocatedAppWidgets = false;
final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
try {
int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_APPWIDGET);
values.put(Favorites.SPANX, spanX);
values.put(Favorites.SPANY, spanY);
values.put(Favorites.APPWIDGET_ID, appWidgetId);
values.put(Favorites._ID, generateNewId());
dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values);
allocatedAppWidgets = true;
// TODO: need to check return value
appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
// Send a broadcast to configure the widget
if (extras != null && !extras.isEmpty()) {
Intent intent = new Intent(ACTION_APPWIDGET_DEFAULT_WORKSPACE_CONFIGURE);
intent.setComponent(cn);
intent.putExtras(extras);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
mContext.sendBroadcast(intent);
}
} catch (RuntimeException ex) {
Log.e(TAG, "Problem allocating appWidgetId", ex);
}
return allocatedAppWidgets;
}
private long addUriShortcut(SQLiteDatabase db, ContentValues values, TypedArray a) {
Resources r = mContext.getResources();
final int iconResId = a.getResourceId(R.styleable.Favorite_icon, 0);
final int titleResId = a.getResourceId(R.styleable.Favorite_title, 0);
Intent intent;
String uri = null;
try {
uri = a.getString(R.styleable.Favorite_uri);
intent = Intent.parseUri(uri, 0);
} catch (URISyntaxException e) {
Log.w(TAG, "Shortcut has malformed uri: " + uri);
return -1; // Oh well
}
if (iconResId == 0 || titleResId == 0) {
Log.w(TAG, "Shortcut is missing title or icon resource ID");
return -1;
}
long id = generateNewId();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
values.put(Favorites.INTENT, intent.toUri(0));
values.put(Favorites.TITLE, r.getString(titleResId));
values.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_SHORTCUT);
values.put(Favorites.SPANX, 1);
values.put(Favorites.SPANY, 1);
values.put(Favorites.ICON_TYPE, Favorites.ICON_TYPE_RESOURCE);
values.put(Favorites.ICON_PACKAGE, mContext.getPackageName());
values.put(Favorites.ICON_RESOURCE, r.getResourceName(iconResId));
values.put(Favorites._ID, id);
if (dbInsertAndCheck(this, db, TABLE_FAVORITES, null, values) < 0) {
return -1;
}
return id;
}
}
/**
* Build a query string that will match any row where the column matches
* anything in the values list.
*/
static String buildOrWhereString(String column, int[] values) {
StringBuilder selectWhere = new StringBuilder();
for (int i = values.length - 1; i >= 0; i--) {
selectWhere.append(column).append("=").append(values[i]);
if (i > 0) {
selectWhere.append(" OR ");
}
}
return selectWhere.toString();
}
static class SqlArguments {
public final String table;
public final String where;
public final String[] args;
SqlArguments(Uri url, String where, String[] args) {
if (url.getPathSegments().size() == 1) {
this.table = url.getPathSegments().get(0);
this.where = where;
this.args = args;
} else if (url.getPathSegments().size() != 2) {
throw new IllegalArgumentException("Invalid URI: " + url);
} else if (!TextUtils.isEmpty(where)) {
throw new UnsupportedOperationException("WHERE clause not supported: " + url);
} else {
this.table = url.getPathSegments().get(0);
this.where = "_id=" + ContentUris.parseId(url);
this.args = null;
}
}
SqlArguments(Uri url) {
if (url.getPathSegments().size() == 1) {
table = url.getPathSegments().get(0);
where = null;
args = null;
} else {
throw new IllegalArgumentException("Invalid URI: " + url);
}
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2006-2007 University of Toronto Database Group
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/
package experiment;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Vector;
import dbdriver.MySqlDB;
import simfunctions.ApproximateGES;
import simfunctions.BM25;
import simfunctions.EditDistance;
import simfunctions.EvaluateSJoinThread;
import simfunctions.GeneralizedEditSimilarity;
import simfunctions.HMM;
import simfunctions.Intersect;
import simfunctions.Jaccard;
import simfunctions.Preprocess;
import simfunctions.SoftTfIdf;
import simfunctions.TfIdf;
import simfunctions.WeightedIntersect;
import simfunctions.WeightedIntersectBM25;
import simfunctions.WeightedJaccard;
import simfunctions.WeightedJaccardBM25;
import utility.Config;
import utility.Util;
public class evalSingleSimilarityJoin {
public static int queryTokenLength = 2;
public static String getQuery(int tid, String tableName) {
String resultQuery = "";
String query = "";
Config config = new Config();
MySqlDB mysqlDB = new MySqlDB(config.returnURL(), config.user, config.passwd);
try {
query = "SELECT " + config.preprocessingColumn + ", id FROM " + config.dbName + "."
+ tableName + " T WHERE T.tid = " + tid;
//System.out.println("Executing " + query);
ResultSet rs = mysqlDB.executeQuery(query);
rs.next();
resultQuery = rs.getString(config.preprocessingColumn);
mysqlDB.close();
} catch (Exception e) {
System.err.println("Can't generate the query");
e.printStackTrace();
}
return resultQuery;
}
public static HashSet<Integer> getAllTidsHavingIdSameAs(int tid, String tableName) {
HashSet<Integer> tidsHavingThisID = new HashSet<Integer>();
Config config = new Config();
MySqlDB mysqlDB = new MySqlDB(config.returnURL(), config.user, config.passwd);
try {
String query = "SELECT tid FROM " + config.dbName + "." + tableName + " where id=" +
"(SELECT id FROM " + config.dbName + "." + tableName + " t where t.tid= " + tid +")";
//System.out.println("Executing " + query);
ResultSet rs = mysqlDB.executeQuery(query);
if (rs != null) {
while (rs.next()) {
tidsHavingThisID.add(rs.getInt("tid"));
}
}
mysqlDB.close();
} catch (Exception e) {
System.err.println("Can't run query");
e.printStackTrace();
}
return tidsHavingThisID;
}
// The sortOrder defines the ordering for the tuples having similar scores
public static int[] generateBooleanList(HashSet<Integer> actualResult, List<IdScore> scoreList, int sortOrder) {
int[] booleanList = new int[scoreList.size()];
int booleanListCounter = 0;
double oldScore = 0, newScore = 0;
ArrayList<Integer> tempBooleanList = new ArrayList<Integer>();
// For the first element
newScore = scoreList.get(0).score;
oldScore = scoreList.get(0).score;
if (actualResult.contains(scoreList.get(0).id + 1)) {
tempBooleanList.add(1);
Util.printlnDebug("Got match at position: "+1);
} else {
tempBooleanList.add(0);
}
for (int i = 1; i < scoreList.size(); i++) {
newScore = scoreList.get(i).score;
if (newScore != oldScore) {
// sort the old list and set the values in the actual
// booleanList
Collections.sort(tempBooleanList);
if (sortOrder != 0) {
Collections.reverse(tempBooleanList);
}
for (int k = 0; k < tempBooleanList.size(); k++) {
booleanList[booleanListCounter++] = tempBooleanList.get(k);
}
tempBooleanList = new ArrayList<Integer>();
oldScore = newScore;
if (actualResult.contains(scoreList.get(i).id + 1)) {
tempBooleanList.add(1);
Util.printlnDebug("Got match at position: "+ (i+1));
} else {
tempBooleanList.add(0);
}
} else {
if (actualResult.contains(scoreList.get(i).id + 1)) {
tempBooleanList.add(1);
Util.printlnDebug("Got match at position: "+ (i+1));
} else {
tempBooleanList.add(0);
}
}
}
Collections.sort(tempBooleanList);
if (sortOrder != 0) {
Collections.reverse(tempBooleanList);
}
for (int k = 0; k < tempBooleanList.size(); k++) {
booleanList[booleanListCounter++] = tempBooleanList.get(k);
}
// For the last block of tempBooleanList
return booleanList;
}
public static void main(String[] args) {
Config config = new Config();
MySqlDB mysqlDB = new MySqlDB(config.returnURL(), config.user, config.passwd);
String resultTable = "ssingle_sjoinresults";
try {
//String query = "DROP TABLE IF EXISTS " + config.dbName + "." + resultTable;
//mysqlDB.executeUpdate(query);
String query = "CREATE TABLE IF NOT EXISTS " + config.dbName + "." + resultTable
+ " (tbl varchar(10), simfunc varchar(50), thr double, pr double, re double, f1 double, " +
" PRIMARY KEY (tbl, simfunc, thr) )";
System.out.println(query);
mysqlDB.executeUpdate(query);
mysqlDB.close();
} catch (Exception e) {
System.err.println("DB Error");
e.printStackTrace();
}
Preprocess tfidf = new TfIdf();
Preprocess bm25 = new BM25();
Preprocess hmm = new HMM();
Preprocess ed = new EditDistance();
Preprocess ges = new GeneralizedEditSimilarity();
Preprocess softtfidf = new SoftTfIdf();
Preprocess fms = new ApproximateGES();
Preprocess weightedJaccard = new WeightedJaccard();
Preprocess jaccard = new Jaccard();
Preprocess weightedIntersect = new WeightedIntersect();
Preprocess intersect = new Intersect();
Preprocess bm25WeightedJaccard = new WeightedJaccardBM25();
Preprocess bm25weightedIntersect = new WeightedIntersectBM25();
//Preprocess bm25WeightedJaccard = new WeightedJaccardBM25();
//Preprocess measure = bm25WeightedJaccard;
//Preprocess measure = tfidf;
//Preprocess measure = ges;
// measure = ed;
//Preprocess hmm = new HMM();
//Preprocess measure = softtfidf;
//Preprocess measure = bm25weightedIntersect;
//Preprocess measure = bm25;
//Preprocess measure = jaccard;
//Preprocess measure = new HMM();
Preprocess measure = ges;
double range = 2.0;
Vector<String> tables = new Vector<String>();
tables.add("cu1");
/*
tables.add("cu1");
tables.add("cu2");
tables.add("cu3");
tables.add("cu4");
tables.add("cu5");
tables.add("cu6");
tables.add("cu7");
tables.add("cu8");
tables.add("F1");
tables.add("F2");
tables.add("F3");
tables.add("F4");
tables.add("F5");
*/
/*
tables.add("5K");
tables.add("10K");
tables.add("20K");
tables.add("50K");
*/
//tables.add("100K");
Vector<Thread> threads = new Vector<Thread>();
/*
for (String table : tables){
threads.add(new RunSimilarityJoinThread(table,ed,0.1));
}
for (String table : tables){
threads.add(new RunSimilarityJoinThread(table,tfidf,0.1));
}
for (String table : tables){
threads.add(new RunSimilarityJoinThread(table,softtfidf,0.1));
}
for (String table : tables){
threads.add(new RunSimilarityJoinThread(table,jaccard,0.1));
}
for (String table : tables){
threads.add(new RunSimilarityJoinThread(table,bm25WeightedJaccard,0.1));
}
for (String table : tables){
threads.add(new RunSimilarityJoinThread(table,ges,0.1));
}
for (String table : tables){
threads.add(new RunSimilarityJoinThread(table,hmm,0.1));
}
for (String table : tables){
threads.add(new RunSimilarityJoinThread(table,bm25,0.1));
}
*/
//threads.add(new RunSimilarityJoinThread("cu1",ges,0.1));
for (Thread thread: threads){
thread.start();
}
for (Thread thread: threads){
try{
thread.join();
} catch (Exception e) {
System.out.println("Error");
}
}
threads = new Vector<Thread>();
/* threads.add(new RunClusteringThread("cu1",hmm));
//threads.add(new RunClusteringThread("cu1",measure,0.0));
threads.add(new RunClusteringThread("cu1",measure,0.2));
threads.add(new RunClusteringThread("cu1",measure,0.4));
threads.add(new RunClusteringThread("cu1",measure,0.6));
threads.add(new RunClusteringThread("cu1",measure,0.8));
/*
threads.add(new RunClusteringThread("cu2",measure,0.6));
threads.add(new RunClusteringThread("cu3",measure,0.6));
threads.add(new RunClusteringThread("cu4",measure,0.6));
threads.add(new RunClusteringThread("cu5",measure,0.6));
threads.add(new RunClusteringThread("cu6",measure,0.6));
threads.add(new RunClusteringThread("cu7",measure,0.6));
threads.add(new RunClusteringThread("cu8",measure,0.6));
* /
threads.add(new EvaluateSJoinThread("cu8",measure,0.01));
threads.add(new EvaluateSJoinThread("cu8",measure,0.15));
threads.add(new EvaluateSJoinThread("cu8",measure,0.20));
threads.add(new EvaluateSJoinThread("cu8",measure,0.25)); */
//threads.add(new EvaluateSJoinThread("cu8",measure,0.30));
//threads.add(new EvaluateSJoinThread("cu1",measure,0.4));
//threads.add(new EvaluateSJoinThread("cu1",measure,0.6));
//threads.add(new EvaluateSJoinThread("cu1",measure,0.8));
/*
*
*
*/
double startThr = 0.1;
double stopThr = 0.9;
double step = 0.05;
for (String table : tables){
double thr = startThr;
while (thr < stopThr){
threads.add(new EvaluateSJoinThread(table,measure,thr*range, resultTable));
thr += step;
}
}
for (Thread thread: threads){
thread.start();
try{
thread.join();
} catch (Exception e) {
System.out.println("Error");
}
}
/*
Vector<Integer> v = new Vector<Integer>();
v.add(1);
v.add(2);
v.add(3);
v.add(4);
System.out.println(v);
boolean[][] correctOrder = new boolean[v.size()][v.size()];
for (int i=0; i<v.size(); i++)
for (int j=0; j<v.size(); j++)
correctOrder[i][j]=false;
int size = 0;
for (int i=0; i<v.size(); i++){
for (int j=i+1; j<v.size(); j++){
size++;
correctOrder[v.get(i)-1][v.get(j)-1] = true;
System.out.println(v.get(i) + ", " + v.get(j));
}
}
Vector<Integer> v2 = new Vector<Integer>();
v2.add(4);
v2.add(3);
v2.add(1);
v2.add(2);
//Collections.sort(v2);
//v2 = new Vector<Integer>();
System.out.println(v2);
/*
HashMap<Integer, Double> probs = new HashMap<Integer, Double>();
probs.put(1, 0.5);
probs.put(2, 0.2);
probs.put(3, 0.2);
probs.put(4, 0.6);
List mapValues = new ArrayList(probs.values());
Vector<Double> sortedProbs = new Vector<Double>();
for (Double prob:probs.values()){
sortedProbs.add(prob);
}
Collections.sort(sortedProbs);
for (Double prob:sortedProbs){
//System.out.println(prob);
int m = mapValues.indexOf(prob);
System.out.println(m+1);
mapValues.set(m, -1);
}
* /
int correct = 0;
for (int i=0; i<v2.size(); i++){
for (int j=i+1; j<v2.size(); j++){
if (correctOrder[v2.get(i)-1][v2.get(j)-1]) {
correct++;
System.out.println(v2.get(i) + ", " + v2.get(j));
}
}
}
System.out.println("Percentage: " + correct + "/" + size);
/*
int i = -1;
Integer j = -1;
Vector<String> vStr = new Vector<String>();
HashMap<Integer, Double> hm = new HashMap<Integer, Double>();
System.out.println(i + " " + j + " " + vStr + " " + hm);
tst(i,j,vStr,hm);
System.out.println(i + " " + j + " " + vStr + " " + hm);
/*
String str1 = "ab";
String str2 = "$$";
char[] chars = str1.toCharArray();
int h1 = str1.charAt (1) << 7 | str1.charAt (0);
int h2 = str2.charAt (0) << 7 | str2.charAt (1);
System.out.println("hash(" + str1 + ") = " + (h1) );
System.out.println("hash(" + str1 + ") = " + (h2) );
BitSet b = new BitSet();
long n = 327544767;
//for (int i=0; i<32; i++)
// System.out.println("bit(" + i + ") = " + ( ((n & (1 << i)) >>> i) == 1 ? 1 : 0 ) );
long one = 1;
long n2 = (one << 40);
System.out.println(n2);
for (int i=63; i>=0; i--)
System.out.print(( ((n2 & (one << i)) >>> i) == 1 ? 1 : 0 ) );
*/
/*
Vector<Integer> m1 = new Vector<Integer>(2);
m1.add(1);
m1.add(2);
m1.add(3);
Vector<Integer> m2 = new Vector<Integer>();
m2.add(1);
m2.add(2);
m2.add(3);
System.out.println(m1.equals(m2));
* /
Set<String> qgrams = new HashSet<String>();
qgrams.add("ab");
qgrams.add("df");
qgrams.add("et");
qgrams.add("se");
qgrams.add("df");
qgrams.add("gh");
System.out.println(qgrams.toString());
BitSet b = convertToBitSet(qgrams);
System.out.println(b.toString());
qgrams = convertToStringSet(b);
System.out.println(qgrams.toString());
/*
//System.out.println(1 << 14);
//HashMap<Integer, Integer> perm = permutation(1 << 14);
//System.out.println(perm.toString());
BitSet v = new BitSet();
int N = 6;
v.set(2); v.set(4); v.set(5);
int k=3, n1=2, n2=3;
int k2 = (k+1)/n1 - 1;
//HashMap<Integer, Integer> perm = permutation(6);
//for (int i=0; i<=N; i++) perm.put(i, i);
*
* /
perm = permutation(6);
System.out.println(perm);
Vector<Integer> v = new Vector<Integer>();
v.add(2); v.add(7); v.add(9);
System.out.println(subsets(v,2));
/*
//BitSet[] p = new BitSet[65];
for (int i=1; i<=n1; i++){
BitSet bb1 = p(i,1,n1,n2,N);
BitSet bb2 = p(i,2,n1,n2,N);
bb1.or(bb2);
System.out.println(bb1);
System.out.println(p(i,3,n1,n2,N));
}
* /
BitSet test = new BitSet();
test.set(1, 7, true);
//Vector<Integer> vv = new Vector<Integer>();
//vv.add(1); vv.add(2); vv.add(3); vv.add(4); vv.add(5); vv.add(6);
//System.out.println(subsets(vv, 2));
System.out.println(v.toString());
Vector<Integer> vv = new Vector<Integer>();
for (int i=1; i<=n2; i++) vv.add(i);
for (int i=1; i<=n1; i++){
for (Vector<Integer> subset:subsets(vv, n2-k2)){
BitSet P = new BitSet();
for (Integer j: subset){
P.or(p(i,j,n1,n2,N));
}
HashMap<BitSet, BitSet> sign = new HashMap<BitSet, BitSet>();
BitSet proj = new BitSet();
proj = (BitSet) v.clone();
proj.and(P);
System.out.println("<" + proj + "," + P + ">");
sign.put(proj, P);
Random rand = new Random();
Long hash= new Long(0);
int t = P.nextSetBit(0);
while (t!=-1){
rand = new Random(t);
hash += rand.nextLong();
t=P.nextSetBit(t+1);
}
t = proj.nextSetBit(0);
while (t!=-1){
rand = new Random(t);
hash += rand.nextLong();
t=proj.nextSetBit(t+1);
}
System.out.println(hash);
//System.out.println((int)(P.hashCode()+proj.hashCode()));
//System.out.println(P.hashCode());System.out.println(proj.hashCode());
//System.out.println(sign.hashCode());
}
}
*/
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.endpoint.dsl;
import javax.annotation.Generated;
import org.apache.camel.ExchangePattern;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
import org.apache.camel.spi.ExceptionHandler;
/**
* Call another endpoint from the same Camel Context synchronously.
*
* Generated by camel build tools - do NOT edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface DirectEndpointBuilderFactory {
/**
* Builder for endpoint consumers for the Direct component.
*/
public interface DirectEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default AdvancedDirectEndpointConsumerBuilder advanced() {
return (AdvancedDirectEndpointConsumerBuilder) this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*/
default DirectEndpointConsumerBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer
*/
default DirectEndpointConsumerBuilder bridgeErrorHandler(
String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the Direct component.
*/
public interface AdvancedDirectEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default DirectEndpointConsumerBuilder basic() {
return (DirectEndpointConsumerBuilder) this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*/
default AdvancedDirectEndpointConsumerBuilder exceptionHandler(
ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedDirectEndpointConsumerBuilder exceptionHandler(
String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedDirectEndpointConsumerBuilder exchangePattern(
ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*/
default AdvancedDirectEndpointConsumerBuilder exchangePattern(
String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointConsumerBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointConsumerBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointConsumerBuilder synchronous(
boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointConsumerBuilder synchronous(
String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint producers for the Direct component.
*/
public interface DirectEndpointProducerBuilder
extends
EndpointProducerBuilder {
default AdvancedDirectEndpointProducerBuilder advanced() {
return (AdvancedDirectEndpointProducerBuilder) this;
}
/**
* If sending a message to a direct endpoint which has no active
* consumer, then we can tell the producer to block and wait for the
* consumer to become active.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer
*/
default DirectEndpointProducerBuilder block(boolean block) {
doSetProperty("block", block);
return this;
}
/**
* If sending a message to a direct endpoint which has no active
* consumer, then we can tell the producer to block and wait for the
* consumer to become active.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer
*/
default DirectEndpointProducerBuilder block(String block) {
doSetProperty("block", block);
return this;
}
/**
* Whether the producer should fail by throwing an exception, when
* sending to a DIRECT endpoint with no active consumers.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer
*/
default DirectEndpointProducerBuilder failIfNoConsumers(
boolean failIfNoConsumers) {
doSetProperty("failIfNoConsumers", failIfNoConsumers);
return this;
}
/**
* Whether the producer should fail by throwing an exception, when
* sending to a DIRECT endpoint with no active consumers.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer
*/
default DirectEndpointProducerBuilder failIfNoConsumers(
String failIfNoConsumers) {
doSetProperty("failIfNoConsumers", failIfNoConsumers);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default DirectEndpointProducerBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default DirectEndpointProducerBuilder lazyStartProducer(
String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* The timeout value to use if block is enabled.
*
* The option is a: <code>long</code> type.
*
* Default: 30000
* Group: producer
*/
default DirectEndpointProducerBuilder timeout(long timeout) {
doSetProperty("timeout", timeout);
return this;
}
/**
* The timeout value to use if block is enabled.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 30000
* Group: producer
*/
default DirectEndpointProducerBuilder timeout(String timeout) {
doSetProperty("timeout", timeout);
return this;
}
}
/**
* Advanced builder for endpoint producers for the Direct component.
*/
public interface AdvancedDirectEndpointProducerBuilder
extends
EndpointProducerBuilder {
default DirectEndpointProducerBuilder basic() {
return (DirectEndpointProducerBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointProducerBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointProducerBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointProducerBuilder synchronous(
boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointProducerBuilder synchronous(
String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
/**
* Builder for endpoint for the Direct component.
*/
public interface DirectEndpointBuilder
extends
DirectEndpointConsumerBuilder,
DirectEndpointProducerBuilder {
default AdvancedDirectEndpointBuilder advanced() {
return (AdvancedDirectEndpointBuilder) this;
}
}
/**
* Advanced builder for endpoint for the Direct component.
*/
public interface AdvancedDirectEndpointBuilder
extends
AdvancedDirectEndpointConsumerBuilder,
AdvancedDirectEndpointProducerBuilder {
default DirectEndpointBuilder basic() {
return (DirectEndpointBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointBuilder synchronous(boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedDirectEndpointBuilder synchronous(String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
public interface DirectBuilders {
/**
* Direct (camel-direct)
* Call another endpoint from the same Camel Context synchronously.
*
* Category: core,endpoint
* Since: 1.0
* Maven coordinates: org.apache.camel:camel-direct
*
* Syntax: <code>direct:name</code>
*
* Path parameter: name (required)
* Name of direct endpoint
*
* @param path name
*/
default DirectEndpointBuilder direct(String path) {
return DirectEndpointBuilderFactory.endpointBuilder("direct", path);
}
/**
* Direct (camel-direct)
* Call another endpoint from the same Camel Context synchronously.
*
* Category: core,endpoint
* Since: 1.0
* Maven coordinates: org.apache.camel:camel-direct
*
* Syntax: <code>direct:name</code>
*
* Path parameter: name (required)
* Name of direct endpoint
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path name
*/
default DirectEndpointBuilder direct(String componentName, String path) {
return DirectEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
static DirectEndpointBuilder endpointBuilder(
String componentName,
String path) {
class DirectEndpointBuilderImpl extends AbstractEndpointBuilder implements DirectEndpointBuilder, AdvancedDirectEndpointBuilder {
public DirectEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new DirectEndpointBuilderImpl(path);
}
}
| |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sunshine.app.data;
import android.annotation.TargetApi;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
public class WeatherProvider extends ContentProvider {
// The URI Matcher used by this content provider.
private static final UriMatcher sUriMatcher = buildUriMatcher();
private WeatherDbHelper mOpenHelper;
static final int WEATHER = 100;
static final int WEATHER_WITH_LOCATION = 101;
static final int WEATHER_WITH_LOCATION_AND_DATE = 102;
static final int LOCATION = 300;
private static final SQLiteQueryBuilder sWeatherByLocationSettingQueryBuilder;
static{
sWeatherByLocationSettingQueryBuilder = new SQLiteQueryBuilder();
//This is an inner join which looks like
//weather INNER JOIN location ON weather.location_id = location._id
sWeatherByLocationSettingQueryBuilder.setTables(
WeatherContract.WeatherEntry.TABLE_NAME + " INNER JOIN " +
WeatherContract.LocationEntry.TABLE_NAME +
" ON " + WeatherContract.WeatherEntry.TABLE_NAME +
"." + WeatherContract.WeatherEntry.COLUMN_LOC_KEY +
" = " + WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry._ID);
}
//location.location_setting = ?
private static final String sLocationSettingSelection =
WeatherContract.LocationEntry.TABLE_NAME+
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? ";
//location.location_setting = ? AND date >= ?
private static final String sLocationSettingWithStartDateSelection =
WeatherContract.LocationEntry.TABLE_NAME+
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
WeatherContract.WeatherEntry.COLUMN_DATE + " >= ? ";
//location.location_setting = ? AND date = ?
private static final String sLocationSettingAndDaySelection =
WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
WeatherContract.WeatherEntry.COLUMN_DATE + " = ? ";
private Cursor getWeatherByLocationSetting(Uri uri, String[] projection, String sortOrder) {
String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
long startDate = WeatherContract.WeatherEntry.getStartDateFromUri(uri);
String[] selectionArgs;
String selection;
if (startDate == 0) {
selection = sLocationSettingSelection;
selectionArgs = new String[]{locationSetting};
} else {
selectionArgs = new String[]{locationSetting, Long.toString(startDate)};
selection = sLocationSettingWithStartDateSelection;
}
return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
}
private Cursor getWeatherByLocationSettingAndDate(
Uri uri, String[] projection, String sortOrder) {
String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
long date = WeatherContract.WeatherEntry.getDateFromUri(uri);
return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
sLocationSettingAndDaySelection,
new String[]{locationSetting, Long.toString(date)},
null,
null,
sortOrder
);
}
/*
Students: Here is where you need to create the UriMatcher. This UriMatcher will
match each URI to the WEATHER, WEATHER_WITH_LOCATION, WEATHER_WITH_LOCATION_AND_DATE,
and LOCATION integer constants defined above. You can test this by uncommenting the
testUriMatcher test within TestUriMatcher.
*/
static UriMatcher buildUriMatcher() {
// 1) The code passed into the constructor represents the code to return for the root
// URI. It's common to use NO_MATCH as the code for this case. Add the constructor below.
UriMatcher sUriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
// 2) Use the addURI function to match each of the types. Use the constants from
// WeatherContract to help define the types to the UriMatcher.
sUriMatcher.addURI("com.example.android.sunshine.app",WeatherContract.PATH_WEATHER,WEATHER);
sUriMatcher.addURI("com.example.android.sunshine.app",WeatherContract.PATH_WEATHER+"/*",WEATHER_WITH_LOCATION);
sUriMatcher.addURI("com.example.android.sunshine.app",WeatherContract.PATH_WEATHER+"/*/#",WEATHER_WITH_LOCATION_AND_DATE);
sUriMatcher.addURI("com.example.android.sunshine.app",WeatherContract.PATH_LOCATION,LOCATION);
// 3) Return the new matcher!
return sUriMatcher;
}
/*
Students: We've coded this for you. We just create a new WeatherDbHelper for later use
here.
*/
@Override
public boolean onCreate() {
mOpenHelper = new WeatherDbHelper(getContext());
return true;
}
/*
Students: Here's where you'll code the getType function that uses the UriMatcher. You can
test this by uncommenting testGetType in TestProvider.
*/
@Override
public String getType(Uri uri) {
// Use the Uri Matcher to determine what kind of URI this is.
final int match = sUriMatcher.match(uri);
switch (match) {
// Student: Uncomment and fill out these two cases
case WEATHER_WITH_LOCATION_AND_DATE:
return WeatherContract.WeatherEntry.CONTENT_ITEM_TYPE;
case WEATHER_WITH_LOCATION:
return WeatherContract.WeatherEntry.CONTENT_TYPE;
case WEATHER:
return WeatherContract.WeatherEntry.CONTENT_TYPE;
case LOCATION:
return WeatherContract.LocationEntry.CONTENT_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// Here's the switch statement that, given a URI, will determine what kind of request it is,
// and query the database accordingly.
Cursor retCursor;
switch (sUriMatcher.match(uri)) {
// "weather/*/*"
case WEATHER_WITH_LOCATION_AND_DATE:
{
retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder);
break;
}
// "weather/*"
case WEATHER_WITH_LOCATION: {
retCursor = getWeatherByLocationSetting(uri, projection, sortOrder);
break;
}
// "weather"
case WEATHER: {
retCursor =mOpenHelper.getReadableDatabase().query(WeatherContract.WeatherEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
break;
}
// "location"
case LOCATION: {
retCursor =mOpenHelper.getReadableDatabase().query(WeatherContract.LocationEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
retCursor.setNotificationUri(getContext().getContentResolver(), uri);
return retCursor;
}
/*
Student: Add the ability to insert Locations to the implementation of this function.
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
Uri returnUri;
switch (match) {
case WEATHER: {
normalizeDate(values);
long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, values);
if ( _id > 0 )
returnUri = WeatherContract.WeatherEntry.buildWeatherUri(_id);
else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
case LOCATION:
{
long _id = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, values);
if ( _id > 0 )
returnUri = WeatherContract.LocationEntry.buildLocationUri(_id);
else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Student: Start by getting a writable database
final SQLiteDatabase db=mOpenHelper.getWritableDatabase();
// Student: Use the uriMatcher to match the WEATHER and LOCATION URI's we are going to
// handle. If it doesn't match these, throw an UnsupportedOperationException.
final int match=sUriMatcher.match(uri);
int number;
switch(match){
case WEATHER:{
number= db.delete(WeatherContract.WeatherEntry.TABLE_NAME,selection,selectionArgs);
break;
}
case LOCATION:{
number= db.delete(WeatherContract.LocationEntry.TABLE_NAME,selection,selectionArgs);
break;
}
default:throw new UnsupportedOperationException("Unknown uri: " + uri);
}
// Student: A null value deletes all rows. In my implementation of this, I only notified
// the uri listeners (using the content resolver) if the rowsDeleted != 0 or the selection
// is null.
// Oh, and you should notify the listeners here.
if(number!=0||selection==null)
getContext().getContentResolver().notifyChange(uri, null);
// Student: return the actual rows deleted
return number;
}
private void normalizeDate(ContentValues values) {
// normalize the date value
if (values.containsKey(WeatherContract.WeatherEntry.COLUMN_DATE)) {
long dateValue = values.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE);
values.put(WeatherContract.WeatherEntry.COLUMN_DATE, WeatherContract.normalizeDate(dateValue));
}
}
@Override
public int update(
Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// Student: This is a lot like the delete function. We return the number of rows impacted
// by the update.
final SQLiteDatabase db=mOpenHelper.getWritableDatabase();
final int match=sUriMatcher.match(uri);
int number;
switch(match)
{
case WEATHER:{
number=db.update(WeatherContract.WeatherEntry.TABLE_NAME,values,selection,selectionArgs);
break;
}
case LOCATION:{
number=db.update(WeatherContract.LocationEntry.TABLE_NAME,values,selection,selectionArgs);
break;
}
default:throw new UnsupportedOperationException("Uri is wrong"+uri);
}
if(number>0)
getContext().getContentResolver().notifyChange(uri,null);
return number;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case WEATHER:
db.beginTransaction();
int returnCount = 0;
try {
for (ContentValues value : values) {
normalizeDate(value);
long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
if (_id != -1) {
returnCount++;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
getContext().getContentResolver().notifyChange(uri, null);
return returnCount;
default:
return super.bulkInsert(uri, values);
}
}
// You do not need to call this method. This is a method specifically to assist the testing
// framework in running smoothly. You can read more at:
// http://developer.android.com/reference/android/content/ContentProvider.html#shutdown()
@Override
@TargetApi(11)
public void shutdown() {
mOpenHelper.close();
super.shutdown();
}
}
| |
package dae.prefabs.parameters;
import dae.components.ComponentType;
import dae.prefabs.Prefab;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Implementation of a dictionary type parameter. In order for this parameter to
* work the object needs to have the following methods:
*
* void addPropertyKey( String key );
* void removePropertyKey( String key );
*
* int getNrOfPropertyKeys();
* int getIndexOfPropertyKey(String key);
* String getPropertyKeyAt(int index);
*
* void setProperty( String key, T value);
* T getProperty( String key );
*
* with Property the name of the property, and T the type of the property.
*
* @author Koen Samyn
*/
public class DictionaryParameter extends Parameter {
private Parameter baseType;
/**
* Creates a new IndexedParameter object.
*
* @param componentType the componentType of the parameter.
* @param id the id of the parameter.
* @param baseType the base type of the parameter.
*/
public DictionaryParameter(ComponentType componentType, String type, String id, Parameter baseType) {
super(componentType, type, id);
this.baseType = baseType;
}
/**
* Returns the base type of this ListParameter.
*
* @return the base type of this list parameter.
*/
public Parameter getBaseType() {
return baseType;
}
/**
* Gets the method to retrieve the number of values in this dictionary.
*
* @param p the prefab to get this method for.
* @return the Method that can invoke the method.
*/
public Method getNrOfKeysMethod(Prefab p) {
try {
return p.getClass().getMethod("getNrOf" + getProperty() + "Keys");
} catch (NoSuchMethodException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Returns the actual number of keys in the prefab.
*
* @param prefab the prefab to get the keys for.
*/
public int getNrOfKeys(Prefab prefab) {
try {
Method method = getNrOfKeysMethod(prefab);
if (method != null) {
return (Integer) method.invoke(prefab);
} else {
return 0;
}
} catch (IllegalAccessException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return 0;
}
/**
* Returns the method to get the index of a key.
* @param p the prefab to get the key index of.
* @return the index of the key.
*/
public Method getIndexOfKeyMethod( Prefab p){
try {
return p.getClass().getMethod("getIndexOf"+getProperty()+"Key" , String.class);
} catch (NoSuchMethodException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Returns the actual index of the key for this property of the Prefab.
* @param p the prefab that contains the property with the key.
* @param key the key to get the index for.
* @return the index of the given key.
*/
public int getIndexOfKey(Prefab p, String key){
Method m = getIndexOfKeyMethod(p);
if ( m!= null){
try {
return (Integer) m.invoke(p, key);
} catch (IllegalAccessException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
return -1;
}
/**
* Gets the method to return the key list.
* @param p the prefab object to return the key list for.
* @return the Method that can get the list of keys.
*/
public Method getKeyAtMethod(Prefab p){
try {
return p.getClass().getMethod("get" +getProperty()+"KeyAt", int.class);
} catch (NoSuchMethodException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Get the actual key at the given index.
* @param p the prefab to get the key from.
* @param index the index of the key.
* @return the actual string.
*/
public String getKeyAt(Prefab p, int index){
Method getKeyAtMethod = getKeyAtMethod(p);
try {
return (String)getKeyAtMethod.invoke(p, (Integer)index);
} catch (IllegalAccessException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Returns the method that can add a key to the list of keys in this
* dicationary.
*
* @param p the prefab to get this method for.
* @return the Method object that can invoke the method.
*/
public Method getAddKeyMethod(Prefab p) {
try {
return p.getClass().getMethod("add" + getProperty() + "Key", String.class);
} catch (NoSuchMethodException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Adds an actual key for this property on the prefab.
*
* @param prefab the prefab to add the key to.
* @param key the key to add.
*/
public void addKey(Prefab prefab, String key) {
Method addKeyMethod = getAddKeyMethod(prefab);
if (addKeyMethod != null) {
try {
addKeyMethod.invoke(prefab, key);
} catch (IllegalAccessException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* Returns the method that can remove a key from the list of keys.
*
* @param p the prefab to get this method for.
* @return the Method object that can invoke the method.
*/
public Method getRemoveKeyMethod(Prefab p) {
try {
return p.getClass().getMethod("remove" + getProperty() + "Key", String.class);
} catch (NoSuchMethodException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Removes an actual key for this property on the prefab.
*
* @param prefab the prefab to remove the key to.
* @param key the key to remove.
*/
public void removeKey(Prefab prefab, String key) {
Method removeKeyMethod = getRemoveKeyMethod(prefab);
if (removeKeyMethod != null) {
try {
removeKeyMethod.invoke(prefab, key);
} catch (IllegalAccessException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* Returns a method that can get the value of the property.
*
* @param p the prefab to get this method for.
* @return the Method that
*/
public Method getGetPropertyMethod(Prefab p) {
try {
return p.getClass().getMethod("get" + getProperty(), String.class);
} catch (NoSuchMethodException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Returns the value for the property for a given key.
*
* @param p the prefab to get the value for.
* @param key the key that is associated with the value.
* @return the value for the property for a given key.
*/
public Object getProperty(Prefab p, String key) {
Method getMethod = getGetPropertyMethod(p);
if ( getMethod != null){
try {
return getMethod.invoke(p, key);
} catch (IllegalAccessException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}else{
return null;
}
}
/**
* Returns a method that can get the value of the property.
*
* @param p the prefab to get this method for.
* @return the Method that
*/
public Method getSetPropertyMethod(Prefab p) {
try {
return p.getClass().getMethod("set" + getProperty(), String.class, baseType.getClassType());
} catch (NoSuchMethodException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Sets the value for the property for a given key.
*
* @param p the prefab to set the value for.
* @param key the key that is associated with the value.
*/
public void setProperty(Prefab p, String key, Object value) {
Method setMethod = getSetPropertyMethod(p);
if ( setMethod != null){
try {
setMethod.invoke(p, key, value);
} catch (IllegalAccessException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(DictionaryParameter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
| |
/*
* Copyright (c) 2010-2020. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axonframework.queryhandling;
import org.axonframework.messaging.GenericMessage;
import org.axonframework.messaging.MessageDispatchInterceptor;
import org.axonframework.messaging.MetaData;
import org.axonframework.messaging.responsetypes.InstanceResponseType;
import org.axonframework.utils.MockException;
import org.junit.jupiter.api.*;
import org.mockito.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static org.axonframework.messaging.responsetypes.ResponseTypes.instanceOf;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* Test class verifying correct workings of the {@link DefaultQueryGateway}.
*
* @author Allard Buijze
*/
class DefaultQueryGatewayTest {
private QueryBus mockBus;
private DefaultQueryGateway testSubject;
private QueryResponseMessage<String> answer;
@SuppressWarnings("unchecked")
@BeforeEach
void setUp() {
answer = new GenericQueryResponseMessage<>("answer");
MessageDispatchInterceptor<QueryMessage<?, ?>> mockDispatchInterceptor = mock(MessageDispatchInterceptor.class);
mockBus = mock(QueryBus.class);
testSubject = DefaultQueryGateway.builder()
.queryBus(mockBus)
.dispatchInterceptors(mockDispatchInterceptor)
.build();
when(mockDispatchInterceptor.handle(isA(QueryMessage.class))).thenAnswer(i -> i.getArguments()[0]);
}
@Test
void testPointToPointQuery() throws Exception {
when(mockBus.query(anyMessage(String.class, String.class))).thenReturn(completedFuture(answer));
CompletableFuture<String> queryResponse = testSubject.query("query", String.class);
assertEquals("answer", queryResponse.get());
//noinspection unchecked
ArgumentCaptor<QueryMessage<String, String>> queryMessageCaptor = ArgumentCaptor.forClass(QueryMessage.class);
verify(mockBus).query(queryMessageCaptor.capture());
QueryMessage<String, String> result = queryMessageCaptor.getValue();
assertEquals("query", result.getPayload());
assertEquals(String.class, result.getPayloadType());
assertEquals(String.class.getName(), result.getQueryName());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getResponseType().getClass()));
assertEquals(String.class, result.getResponseType().getExpectedResponseType());
assertEquals(MetaData.emptyInstance(), result.getMetaData());
}
@Test
void testPointToPointQuerySpecifyingQueryName() throws Exception {
String expectedQueryName = "myQueryName";
when(mockBus.query(anyMessage(String.class, String.class))).thenReturn(completedFuture(answer));
CompletableFuture<String> queryResponse = testSubject.query(expectedQueryName, "query", String.class);
assertEquals("answer", queryResponse.get());
//noinspection unchecked
ArgumentCaptor<QueryMessage<String, String>> queryMessageCaptor = ArgumentCaptor.forClass(QueryMessage.class);
verify(mockBus).query(queryMessageCaptor.capture());
QueryMessage<String, String> result = queryMessageCaptor.getValue();
assertEquals("query", result.getPayload());
assertEquals(String.class, result.getPayloadType());
assertEquals(expectedQueryName, result.getQueryName());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getResponseType().getClass()));
assertEquals(String.class, result.getResponseType().getExpectedResponseType());
assertEquals(MetaData.emptyInstance(), result.getMetaData());
}
@Test
void testPointToPointQueryWithMetaData() throws Exception {
String expectedMetaDataKey = "key";
String expectedMetaDataValue = "value";
when(mockBus.query(anyMessage(String.class, String.class))).thenReturn(completedFuture(answer));
GenericMessage<String> testQuery =
new GenericMessage<>("query", MetaData.with(expectedMetaDataKey, expectedMetaDataValue));
CompletableFuture<String> queryResponse = testSubject.query(testQuery, instanceOf(String.class));
assertEquals("answer", queryResponse.get());
//noinspection unchecked
ArgumentCaptor<QueryMessage<String, String>> queryMessageCaptor = ArgumentCaptor.forClass(QueryMessage.class);
verify(mockBus).query(queryMessageCaptor.capture());
QueryMessage<String, String> result = queryMessageCaptor.getValue();
assertEquals("query", result.getPayload());
assertEquals(String.class, result.getPayloadType());
assertEquals(String.class.getName(), result.getQueryName());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getResponseType().getClass()));
assertEquals(String.class, result.getResponseType().getExpectedResponseType());
MetaData resultMetaData = result.getMetaData();
assertTrue(resultMetaData.containsKey(expectedMetaDataKey));
assertTrue(resultMetaData.containsValue(expectedMetaDataValue));
}
@Test
void testPointToPointQueryWhenQueryBusReportsAnError() throws Exception {
Throwable expected = new Throwable("oops");
when(mockBus.query(anyMessage(String.class, String.class)))
.thenReturn(completedFuture(new GenericQueryResponseMessage<>(String.class, expected)));
CompletableFuture<String> result = testSubject.query("query", String.class);
assertTrue(result.isDone());
assertTrue(result.isCompletedExceptionally());
assertEquals(expected.getMessage(), result.exceptionally(Throwable::getMessage).get());
}
@Test
void testPointToPointQueryWhenQueryBusThrowsException() throws Exception {
Throwable expected = new Throwable("oops");
CompletableFuture<QueryResponseMessage<String>> queryResponseCompletableFuture = new CompletableFuture<>();
queryResponseCompletableFuture.completeExceptionally(expected);
when(mockBus.query(anyMessage(String.class, String.class))).thenReturn(queryResponseCompletableFuture);
CompletableFuture<String> result = testSubject.query("query", String.class);
assertTrue(result.isDone());
assertTrue(result.isCompletedExceptionally());
assertEquals(expected.getMessage(), result.exceptionally(Throwable::getMessage).get());
}
@Test
void testScatterGatherQuery() {
long expectedTimeout = 1L;
TimeUnit expectedTimeUnit = TimeUnit.SECONDS;
when(mockBus.scatterGather(anyMessage(String.class, String.class), anyLong(), any()))
.thenReturn(Stream.of(answer));
Stream<String> queryResponse =
testSubject.scatterGather("scatterGather", instanceOf(String.class), expectedTimeout, expectedTimeUnit);
Optional<String> firstResult = queryResponse.findFirst();
assertTrue(firstResult.isPresent());
assertEquals("answer", firstResult.get());
//noinspection unchecked
ArgumentCaptor<QueryMessage<String, String>> queryMessageCaptor = ArgumentCaptor.forClass(QueryMessage.class);
verify(mockBus).scatterGather(queryMessageCaptor.capture(), eq(expectedTimeout), eq(expectedTimeUnit));
QueryMessage<String, String> result = queryMessageCaptor.getValue();
assertEquals("scatterGather", result.getPayload());
assertEquals(String.class, result.getPayloadType());
assertEquals(String.class.getName(), result.getQueryName());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getResponseType().getClass()));
assertEquals(String.class, result.getResponseType().getExpectedResponseType());
assertEquals(MetaData.emptyInstance(), result.getMetaData());
}
@Test
void testScatterGatherQuerySpecifyingQueryName() {
String expectedQueryName = "myQueryName";
long expectedTimeout = 1L;
TimeUnit expectedTimeUnit = TimeUnit.SECONDS;
when(mockBus.scatterGather(anyMessage(String.class, String.class), anyLong(), any()))
.thenReturn(Stream.of(answer));
Stream<String> queryResponse = testSubject.scatterGather(
expectedQueryName, "scatterGather", instanceOf(String.class), expectedTimeout, expectedTimeUnit
);
Optional<String> firstResult = queryResponse.findFirst();
assertTrue(firstResult.isPresent());
assertEquals("answer", firstResult.get());
//noinspection unchecked
ArgumentCaptor<QueryMessage<String, String>> queryMessageCaptor = ArgumentCaptor.forClass(QueryMessage.class);
verify(mockBus).scatterGather(queryMessageCaptor.capture(), eq(expectedTimeout), eq(expectedTimeUnit));
QueryMessage<String, String> result = queryMessageCaptor.getValue();
assertEquals("scatterGather", result.getPayload());
assertEquals(String.class, result.getPayloadType());
assertEquals(expectedQueryName, result.getQueryName());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getResponseType().getClass()));
assertEquals(String.class, result.getResponseType().getExpectedResponseType());
assertEquals(MetaData.emptyInstance(), result.getMetaData());
}
@Test
void testScatterGatherQueryWithMetaData() {
String expectedMetaDataKey = "key";
String expectedMetaDataValue = "value";
long expectedTimeout = 1L;
TimeUnit expectedTimeUnit = TimeUnit.SECONDS;
when(mockBus.scatterGather(anyMessage(String.class, String.class), anyLong(), any()))
.thenReturn(Stream.of(answer));
GenericMessage<String> testQuery =
new GenericMessage<>("scatterGather", MetaData.with(expectedMetaDataKey, expectedMetaDataValue));
Stream<String> queryResponse =
testSubject.scatterGather(testQuery, instanceOf(String.class), expectedTimeout, expectedTimeUnit);
Optional<String> firstResult = queryResponse.findFirst();
assertTrue(firstResult.isPresent());
assertEquals("answer", firstResult.get());
//noinspection unchecked
ArgumentCaptor<QueryMessage<String, String>> queryMessageCaptor = ArgumentCaptor.forClass(QueryMessage.class);
verify(mockBus).scatterGather(queryMessageCaptor.capture(), eq(expectedTimeout), eq(expectedTimeUnit));
QueryMessage<String, String> result = queryMessageCaptor.getValue();
assertEquals("scatterGather", result.getPayload());
assertEquals(String.class, result.getPayloadType());
assertEquals(String.class.getName(), result.getQueryName());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getResponseType().getClass()));
assertEquals(String.class, result.getResponseType().getExpectedResponseType());
MetaData resultMetaData = result.getMetaData();
assertTrue(resultMetaData.containsKey(expectedMetaDataKey));
assertTrue(resultMetaData.containsValue(expectedMetaDataValue));
}
@Test
void testSubscriptionQuery() {
when(mockBus.subscriptionQuery(any(), any(), anyInt()))
.thenReturn(new DefaultSubscriptionQueryResult<>(Mono.empty(), Flux.empty(), () -> true));
testSubject.subscriptionQuery("subscription", instanceOf(String.class), instanceOf(String.class));
//noinspection unchecked
ArgumentCaptor<SubscriptionQueryMessage<String, String, String>> queryMessageCaptor =
ArgumentCaptor.forClass(SubscriptionQueryMessage.class);
verify(mockBus).subscriptionQuery(queryMessageCaptor.capture(), any(), anyInt());
SubscriptionQueryMessage<String, String, String> result = queryMessageCaptor.getValue();
assertEquals("subscription", result.getPayload());
assertEquals(String.class, result.getPayloadType());
assertEquals(String.class.getName(), result.getQueryName());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getResponseType().getClass()));
assertEquals(String.class, result.getResponseType().getExpectedResponseType());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getUpdateResponseType().getClass()));
assertEquals(String.class, result.getUpdateResponseType().getExpectedResponseType());
assertEquals(MetaData.emptyInstance(), result.getMetaData());
}
@Test
void testSubscriptionQuerySpecifyingQueryName() {
String expectedQueryName = "myQueryName";
when(mockBus.subscriptionQuery(any(), any(), anyInt()))
.thenReturn(new DefaultSubscriptionQueryResult<>(Mono.empty(), Flux.empty(), () -> true));
testSubject.subscriptionQuery(expectedQueryName, "subscription", String.class, String.class);
//noinspection unchecked
ArgumentCaptor<SubscriptionQueryMessage<String, String, String>> queryMessageCaptor =
ArgumentCaptor.forClass(SubscriptionQueryMessage.class);
verify(mockBus).subscriptionQuery(queryMessageCaptor.capture(), any(), anyInt());
SubscriptionQueryMessage<String, String, String> result = queryMessageCaptor.getValue();
assertEquals("subscription", result.getPayload());
assertEquals(String.class, result.getPayloadType());
assertEquals(expectedQueryName, result.getQueryName());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getResponseType().getClass()));
assertEquals(String.class, result.getResponseType().getExpectedResponseType());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getUpdateResponseType().getClass()));
assertEquals(String.class, result.getUpdateResponseType().getExpectedResponseType());
assertEquals(MetaData.emptyInstance(), result.getMetaData());
}
@Test
void testSubscriptionQueryWithMetaData() {
String expectedMetaDataKey = "key";
String expectedMetaDataValue = "value";
when(mockBus.subscriptionQuery(any(), any(), anyInt()))
.thenReturn(new DefaultSubscriptionQueryResult<>(Mono.empty(), Flux.empty(), () -> true));
GenericMessage<String> testQuery =
new GenericMessage<>("subscription", MetaData.with(expectedMetaDataKey, expectedMetaDataValue));
testSubject.subscriptionQuery(testQuery, instanceOf(String.class), instanceOf(String.class));
//noinspection unchecked
ArgumentCaptor<SubscriptionQueryMessage<String, String, String>> queryMessageCaptor =
ArgumentCaptor.forClass(SubscriptionQueryMessage.class);
verify(mockBus).subscriptionQuery(queryMessageCaptor.capture(), any(), anyInt());
SubscriptionQueryMessage<String, String, String> result = queryMessageCaptor.getValue();
assertEquals("subscription", result.getPayload());
assertEquals(String.class, result.getPayloadType());
assertEquals(String.class.getName(), result.getQueryName());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getResponseType().getClass()));
assertEquals(String.class, result.getResponseType().getExpectedResponseType());
assertTrue(InstanceResponseType.class.isAssignableFrom(result.getUpdateResponseType().getClass()));
assertEquals(String.class, result.getUpdateResponseType().getExpectedResponseType());
MetaData resultMetaData = result.getMetaData();
assertTrue(resultMetaData.containsKey(expectedMetaDataKey));
assertTrue(resultMetaData.containsValue(expectedMetaDataValue));
}
@Test
void testDispatchInterceptor() {
when(mockBus.query(anyMessage(String.class, String.class))).thenReturn(completedFuture(answer));
testSubject.registerDispatchInterceptor(messages -> (integer, queryMessage) -> new GenericQueryMessage<>(
"dispatch-" + queryMessage.getPayload(),
queryMessage.getQueryName(),
queryMessage.getResponseType()));
testSubject.query("query", String.class).join();
verify(mockBus).query(
argThat((ArgumentMatcher<QueryMessage<String, String>>) x -> "dispatch-query".equals(x.getPayload()))
);
}
@Test
void testExceptionInInitialResultOfSubscriptionQueryReportedInMono() {
when(mockBus.subscriptionQuery(anySubscriptionMessage(String.class, String.class), any(), anyInt()))
.thenReturn(new DefaultSubscriptionQueryResult<>(
Mono.just(new GenericQueryResponseMessage<>(String.class, new MockException())),
Flux.empty(),
() -> true
));
SubscriptionQueryResult<String, String> actual =
testSubject.subscriptionQuery("Test", instanceOf(String.class), instanceOf(String.class));
//noinspection NullableInLambdaInTransform
assertEquals(
MockException.class,
actual.initialResult().map(i -> null).onErrorResume(e -> Mono.just(e.getClass())).block()
);
}
@Test
void testNullInitialResultOfSubscriptionQueryReportedAsEmptyMono() {
when(mockBus.subscriptionQuery(anySubscriptionMessage(String.class, String.class), any(), anyInt()))
.thenReturn(new DefaultSubscriptionQueryResult<>(
Mono.just(new GenericQueryResponseMessage<>(String.class, (String) null)),
Flux.empty(),
() -> true
));
SubscriptionQueryResult<String, String> actual =
testSubject.subscriptionQuery("Test", instanceOf(String.class), instanceOf(String.class));
assertNull(actual.initialResult().block());
}
@Test
void testNullUpdatesOfSubscriptionQuerySkipped() {
when(mockBus.subscriptionQuery(anySubscriptionMessage(String.class, String.class), any(), anyInt()))
.thenReturn(new DefaultSubscriptionQueryResult<>(
Mono.empty(),
Flux.just(new GenericSubscriptionQueryUpdateMessage<>(String.class, null)),
() -> true
));
SubscriptionQueryResult<String, String> actual =
testSubject.subscriptionQuery("Test", instanceOf(String.class), instanceOf(String.class));
assertNull(actual.initialResult().block());
assertEquals((Long) 0L, actual.updates().count().block());
}
@Test
void testPayloadExtractionProblemsReportedInException() throws ExecutionException, InterruptedException {
when(mockBus.query(anyMessage(String.class, String.class)))
.thenReturn(completedFuture(new GenericQueryResponseMessage<String>("test") {
@Override
public String getPayload() {
throw new MockException("Faking serialization problem");
}
}));
CompletableFuture<String> actual = testSubject.query("query", String.class);
assertTrue(actual.isDone());
assertTrue(actual.isCompletedExceptionally());
assertEquals("Faking serialization problem", actual.exceptionally(Throwable::getMessage).get());
}
@SuppressWarnings({"unused", "SameParameterValue"})
private <Q, R> QueryMessage<Q, R> anyMessage(Class<Q> queryType, Class<R> responseType) {
return any();
}
@SuppressWarnings({"SameParameterValue", "unused"})
private <Q, R> SubscriptionQueryMessage<Q, R, R> anySubscriptionMessage(Class<Q> queryType, Class<R> responseType) {
return any();
}
}
| |
/**
*
*/
package org.commcare.util;
import org.commcare.applogic.CommCareUpgradeState;
import org.commcare.cases.CaseManagementModule;
import org.commcare.cases.ledger.Ledger;
import org.commcare.cases.ledger.LedgerPurgeFilter;
import org.commcare.cases.model.Case;
import org.commcare.cases.util.CasePurgeFilter;
import org.commcare.core.properties.CommCareProperties;
import org.commcare.model.PeriodicEvent;
import org.commcare.model.PeriodicEventRecord;
import org.commcare.resources.ResourceManager;
import org.commcare.resources.model.InstallCancelledException;
import org.commcare.resources.model.Resource;
import org.commcare.resources.model.ResourceTable;
import org.commcare.resources.model.TableStateListener;
import org.commcare.resources.model.UnresolvedResourceException;
import org.commcare.services.AutomatedSenderService;
import org.commcare.util.time.AutoSyncEvent;
import org.commcare.util.time.AutoUpdateEvent;
import org.commcare.util.time.PermissionsEvent;
import org.commcare.util.time.TimeMessageEvent;
import org.commcare.view.CommCareStartupInteraction;
import org.commcare.xml.CommCareElementParser;
import org.javarosa.core.model.CoreModelModule;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.condition.IFunctionHandler;
import org.javarosa.core.model.instance.AbstractTreeElement;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.model.utils.IPreloadHandler;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.Reference;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.reference.RootTranslator;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.PropertyManager;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.properties.JavaRosaPropertyRules;
import org.javarosa.core.services.storage.EntityFilter;
import org.javarosa.core.services.storage.IStorageIterator;
import org.javarosa.core.services.storage.IStorageUtility;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.services.storage.StorageFullException;
import org.javarosa.core.services.storage.StorageManager;
import org.javarosa.core.services.storage.WrappingStorageUtility.SerializationWrapper;
import org.javarosa.core.util.JavaRosaCoreModule;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.formmanager.FormManagerModule;
import org.javarosa.formmanager.properties.FormManagerProperties;
import org.javarosa.j2me.J2MEModule;
import org.javarosa.j2me.file.J2meFileReference;
import org.javarosa.j2me.file.J2meFileRoot;
import org.javarosa.j2me.file.J2meFileSystemProperties;
import org.javarosa.j2me.reference.HttpReference.SecurityFailureListener;
import org.javarosa.j2me.storage.rms.RMSRecordLoc;
import org.javarosa.j2me.storage.rms.RMSStorageUtility;
import org.javarosa.j2me.storage.rms.RMSStorageUtilityIndexed;
import org.javarosa.j2me.storage.rms.RMSTransaction;
import org.javarosa.j2me.util.DumpRMS;
import org.javarosa.j2me.view.J2MEDisplay;
import org.javarosa.log.LogManagementModule;
import org.javarosa.log.util.LogReportUtils;
import org.javarosa.model.xform.XFormsModule;
import org.javarosa.model.xform.XPathReference;
import org.javarosa.resources.locale.LanguagePackModule;
import org.javarosa.resources.locale.LanguageUtils;
import org.javarosa.service.transport.securehttp.AuthUtils;
import org.javarosa.service.transport.securehttp.HttpAuthenticator;
import org.javarosa.service.transport.securehttp.HttpCredentialProvider;
import org.javarosa.services.transport.TransportManagerModule;
import org.javarosa.services.transport.TransportService;
import org.javarosa.services.transport.impl.TransportMessageSerializationWrapper;
import org.javarosa.services.transport.impl.TransportMessageStore;
import org.javarosa.user.activity.UserModule;
import org.javarosa.core.model.User;
import org.javarosa.user.utility.UserPreloadHandler;
import org.javarosa.user.utility.UserUtility;
import org.javarosa.xform.util.XFormUtils;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.midlet.MIDlet;
import de.enough.polish.ui.Display;
/**
* @author ctsims
*
*/
public class CommCareContext {
private static CommCareContext i;
private MIDlet midlet;
private String loggedInUserID;
private CommCarePlatform manager;
protected boolean inDemoMode;
/** We'll store the credential provider internally to be produced first in syncing **/
private HttpCredentialProvider userCredentials;
public String getSubmitURL() {
String url = PropertyManager._().getSingularProperty(CommCareProperties.POST_URL_PROPERTY);
String testUrl = PropertyManager._().getSingularProperty(CommCareProperties.POST_URL_TEST_PROPERTY);
if(CommCareUtil.isTestingMode() && testUrl != null) {
//In testing mode, use this URL instead, if available.
url = testUrl;
}
return url;
}
public MIDlet getMidlet() {
return midlet;
}
public CommCarePlatform getManager() {
return manager;
}
public void configureApp(MIDlet m, InitializationListener listener) {
//Application Entry point should be considered to be here
failsafeInit(m);
Logger.log("app-start", "");
this.midlet = m;
setProperties();
loadModules();
registerAddtlStorage();
StorageManager.repairAll();
RMSTransaction.cleanup();
initReferences();
Localization.registerLanguageReference("default","jr://resource/messages_cc_default.txt");
Localization.registerLanguageReference("sw","jr://resource/messages_cc_sw.txt");
final CommCareStartupInteraction interaction = new CommCareStartupInteraction(CommCareStartupInteraction.failSafeText("commcare.init", "CommCare is Starting..."));
Display.getDisplay(m).setCurrent(interaction);
CommCareInitializer initializer = new CommCareInitializer() {
int currentProgress = 0;
int block = 0;
private String validate() {
interaction.setMessage(CommCareStartupInteraction.failSafeText("install.verify","CommCare initialized. Validating multimedia files..."));
return CommCareStatic.validate(CommCareContext.RetrieveGlobalResourceTable());
}
protected boolean runWrapper() throws UnfullfilledRequirementsException {
updateProgress(10);
//TODO: Make this update progress, takes forever
//Real quick, go trigger an index build to sure we do this when we have the most memory possible
((IStorageUtilityIndexed)StorageManager.getStorage(FormDef.STORAGE_KEY)).getIDsForValue("XMLNS", "");
//Clear out any resources from any botched installations
CommCareContext.ClearUpdateTable();
manager = new CommCarePlatform(CommCareUtil.getMajorVersion(), CommCareUtil.getMinorVersion());
//Try to initialize and install the application resources...
try {
//TODO: This cleanup is replicated across different parts of code.
ResourceTable global = RetrieveGlobalResourceTable();
ResourceTable upgrade = CommCareContext.CreateTemporaryResourceTable(CommCareUpgradeState.UPGRADE_TABLE_NAME);
/**
* See if any of our tables got left in a weird state
*/
if(global.getTableReadiness() == ResourceTable.RESOURCE_TABLE_UNCOMMITED) {
global.rollbackCommits();
}
if(upgrade.getTableReadiness() == ResourceTable.RESOURCE_TABLE_UNCOMMITED) {
upgrade.rollbackCommits();
}
/**
* See if we got left in the middle of an update, make sure we get fixed.
*
*/
if(global.getTableReadiness() == ResourceTable.RESOURCE_TABLE_UNSTAGED) {
//If so, repair the global table. (Always takes priority over maintaining
//the update)
global.repairTable(upgrade);
}
global.setStateListener(new TableStateListener() {
private int score = 0;
private int max = 0;
static final int INSTALL_SCORE = 5;
public void simpleResourceAdded() {
updateProgress(10 + (int)Math.ceil(50 * (++score * 1.0 / max)));
}
public void compoundResourceAdded(final ResourceTable table) {
setCurrentOOMMessage(CommCareStartupInteraction.failSafeText("commcare.install.oom","CommCare needs to restart in order to continue installing your application. Please press 'OK' and start CommCare again."));
score = 0;
max = 0;
Vector<Resource> resources = ResourceManager.getResourceListFromProfile(table);
max = resources.size() * INSTALL_SCORE;
if(max <= INSTALL_SCORE*2) {
//Apps have to have at least 1 resource (profile), and won't really work without a suite, and
//we don't want to jump around too much past that, so we won't bother updating the slider until
//we've found at least those.
return;
}
for(Resource r : resources) {
switch(r.getStatus()) {
case Resource.RESOURCE_STATUS_INSTALLED:
score += INSTALL_SCORE;
break;
default:
score += 1;
break;
}
}
updateProgress(10 + (int)Math.ceil(50 * (score * 1.0 / max)));
}
public void incrementProgress(int complete, int total) {
// TODO Auto-generated method stub
updateProgress(currentProgress + (int)Math.ceil(block * (complete * 1.0 / total)));
}
});
String profileRef = CommCareUtil.getProfileReference();
if(global.isEmpty()) {
this.setMessage(CommCareStartupInteraction.failSafeText("commcare.firstload","First start detected, loading resources..."));
if(profileRef == null) {
String message = "CommCare could not find any application configuration data to install. Please make sure that all CommCare install files are present.";
//#ifdef polish.group.Series40
//# message = "CommCare cannot find the CommCare.jad file. Please ensure that it is placed in the same install folder as CommCare.jar";
//#endif
throw new RuntimeException(message);
}
}
ResourceManager.installAppResources(manager, profileRef, global, false);
updateProgress(60);
} catch (InstallCancelledException e) {
Logger.log("upgrade", "User cancellation unsupported on J2ME: " + e.getMessage());
throw new RuntimeException("User cancellation unsupported on J2ME: " + e.getMessage());
} catch (UnfullfilledRequirementsException e) {
if(e.getSeverity() == CommCareElementParser.SEVERITY_PROMPT) {
String message = e.getMessage();
if(e.getRequirementCode() == CommCareElementParser.REQUIREMENT_MAJOR_APP_VERSION || e.getRequirementCode() == CommCareElementParser.REQUIREMENT_MAJOR_APP_VERSION) {
message = CommCareStartupInteraction.failSafeText("commcare.badversion",
"The application requires a newer version of CommCare than is installed. It may not work correctly. Should installation be attempted anyway?");
}
if(this.blockForResponse(message)) {
try {
//If we're going to try to run commcare with an incompatible version, first clear everything
RetrieveGlobalResourceTable().clear();
ResourceManager.installAppResources(manager, CommCareUtil.getProfileReference(), RetrieveGlobalResourceTable(), true);
} catch (InstallCancelledException e1) {
Logger.log("upgrade", "User cancellation unsupported on J2ME: " + e1.getMessage());
throw new RuntimeException("User cancellation unsupported on J2ME: " + e1.getMessage());
} catch (UnfullfilledRequirementsException e1) {
//Maybe we should try to clear the table here, too?
throw e1;
} catch (UnresolvedResourceException e3) {
//this whole process needs to be cleaned up
throw new RuntimeException(e3.getMessage());
}
} else {
throw e;
}
} else {
throw e;
}
} catch (UnresolvedResourceException e) {
//this whole process needs to be cleaned up
throw new RuntimeException("Error installing resource: " + e.getResource().getDescriptor() + "\n" + e.getMessage());
}
currentProgress = 60;
block = 30;
if(!CommCareUtil.getAppProperty("Skip-Validation","no").equals("yes") && !CommCareProperties.PROPERTY_YES.equals(PropertyManager._().getSingularProperty(CommCareProperties.CONTENT_VALIDATED))) {
String failureMessage = this.validate();
while(failureMessage != null) {
Logger.log("startup", "Missing Resources on startup");
this.blockForResponse(failureMessage, "Retry", "No");
if(this.response == CommCareInitializer.RESPONSE_YES) {
failureMessage = this.validate();
} else {
//TODO: We need to set a flag which says that CommCare can't start up.
CommCareContext.this.exitApp();
return false;
}
}
PropertyManager._().setProperty(CommCareProperties.CONTENT_VALIDATED, CommCareProperties.PROPERTY_YES);
}
updateProgress(90);
//When we might initialize language files, we need to make sure it's not trying
//to load any of them into memory, since the default ones are not guaranteed to
//be added later.
Localization.setLocale("default");
manager.initialize(RetrieveGlobalResourceTable());
purgeScheduler(false);
//Now that the profile has had a chance to set properties (without them requiring
//override) set the fallback defaults.
postProfilePropertyInit();
initUserFramework();
//Establish default logging deadlines
LogReportUtils.initPendingDates(new Date().getTime());
//Now we can initialize the language for real.
LanguageUtils.initializeLanguage(true,"default");
updateProgress(95);
//We need to let All Localizations register before we can do this
J2MEDisplay.init(CommCareContext.this.midlet);
if(CommCareSense.isAutoSendEnabled()) {
AutomatedSenderService.InitializeAndSpawnSenderService();
}
return true;
}
protected void askForResponse(String message, YesNoListener yesNoListener, boolean yesNo) {
if(yesNo) {
interaction.AskYesNo(message,yesNoListener);
} else {
interaction.PromptResponse(message, yesNoListener);
}
}
protected void askForResponse(String message, YesNoListener yesNoListener, boolean yesNo, String left, String right) {
if(yesNo) {
interaction.AskYesNo(message,yesNoListener, left, right);
} else {
interaction.PromptResponse(message, yesNoListener);
}
}
protected void setMessage(String message) {
interaction.setMessage(message, true);
}
protected void updateProgress(int progress) {
interaction.updateProgess(progress);
}
};
initializer.initialize(listener);
}
private void failsafeInit (MIDlet m) {
DumpRMS.RMSRecoveryHook(m);
String fileSystemTranslator = m.getAppProperty("FileRootTranslator");
boolean useRealFiles = true;
if(fileSystemTranslator != null) {
useRealFiles = false;
ReferenceManager._().addRootTranslator(new RootTranslator("jr://file/",fileSystemTranslator));
}
//TODO: Hilarious? Yes. Reasonable? No.
//#if !j2merosa.disable.autofile
new J2MEModule(new J2meFileSystemProperties(useRealFiles) {
protected J2meFileRoot root(String root) {
return new J2meFileRoot(root) {
protected Reference factory(String terminal, String URI) {
return new J2meFileReference(localRoot, terminal) {
protected FileConnection connector(String URI, boolean cache) throws IOException {
try {
return super.connector(URI, cache);
} catch(SecurityException se) {
PeriodicEvent.schedule(new PermissionsEvent());
//Should get swallowed
throw new IOException("Couldn't access data at " + this.getLocalURI() + " due to lack of permissions.");
}
}
};
}
};
}
protected void securityException(SecurityException e) {
super.securityException(e);
PeriodicEvent.schedule(new PermissionsEvent());
}
}) {
protected void postStorageRegistration() {
//immediately after the storage is registered, we want to catch file system events
StorageManager.registerStorage(PeriodicEventRecord.STORAGE_KEY, PeriodicEventRecord.class);
super.postStorageRegistration();
}
}.registerModule();
//#else
//new J2MEModule().registerModule();
////Since this is being registered in the fancy module init above
//StorageManager.registerStorage(PeriodicEventRecord.STORAGE_KEY, PeriodicEventRecord.class);
//#endif
}
private void initUserFramework() {
UserUtility.populateAdminUser(midlet);
inDemoMode = false;
String namespace = PropertyUtils.initializeProperty(CommCareProperties.USER_REG_NAMESPACE, "http://code.javarosa.org/user_registration");
if(namespace.equals("http://code.javarosa.org/user_registration")) {
IStorageUtilityIndexed formDefStorage = (IStorageUtilityIndexed)StorageManager.getStorage(FormDef.STORAGE_KEY);
Vector forms = formDefStorage.getIDsForValue("XMLNS", namespace);
if(forms.size() == 0) {
//Default user registration form isn't present, parse if from the default location.
try {
formDefStorage.write(XFormUtils.getFormFromInputStream(ReferenceManager._().DeriveReference("jr://resource/register_user.xhtml").getStream()));
} catch (IOException e) {
//I dunno? Log it?
e.printStackTrace();
} catch (InvalidReferenceException e) {
// TODO Auto-referralCache catch block
e.printStackTrace();
} catch (StorageFullException e) {
// TODO Auto-referralCache catch block
e.printStackTrace();
}
}
}
}
protected void registerAddtlStorage () {
//do nothing
StorageManager.registerStorage(FormInstance.STORAGE_KEY, FormInstance.class);
}
protected void initReferences() {
ReferenceManager._().addRootTranslator(new RootTranslator("jr://media/","jr://resource/img/"));
}
private void loadModules() {
//So that properties appear at the bottom...
new LogManagementModule().registerModule();
new JavaRosaCoreModule().registerModule();
new UserModule().registerModule();
new LanguagePackModule().registerModule();
new CoreModelModule().registerModule();
new XFormsModule().registerModule();
new CaseManagementModule().registerModule();
new TransportManagerModule(new SecurityFailureListener(){
public void onSecurityException(SecurityException e) {
PeriodicEvent.schedule(new PermissionsEvent());
}
}).registerModule();
new CommCareModule().registerModule();
new FormManagerModule().registerModule();
}
protected void setProperties() {
//NOTE: These properties should all be properties which are not expected to
//be set by the profile, otherwise the profile will need to override the existing property.
//Put generic fallbacks into postProfile property intiializer below.
PropertyManager._().addRules(new JavaRosaPropertyRules());
PropertyManager._().addRules(new CommCareProperties());
PropertyUtils.initalizeDeviceID();
PropertyUtils.initializeProperty(CommCareProperties.IS_FIRST_RUN, CommCareProperties.PROPERTY_YES);
PropertyManager._().setProperty(CommCareProperties.COMMCARE_VERSION, CommCareUtil.getVersion());
PropertyUtils.initializeProperty(CommCareProperties.DEPLOYMENT_MODE, CommCareProperties.DEPLOY_DEFAULT);
//NOTE: Don't put any properties here which should be able to be override inside of the app profile. Users
//should be able to override most properties without forcing.
}
private void postProfilePropertyInit() {
PropertyUtils.initializeProperty(FormManagerProperties.EXTRA_KEY_FORMAT, FormManagerProperties.EXTRA_KEY_LANGUAGE_CYCLE);
PropertyUtils.initializeProperty(CommCareProperties.ENTRY_MODE, CommCareProperties.ENTRY_MODE_QUICK);
PropertyUtils.initializeProperty(CommCareProperties.SEND_STYLE, CommCareProperties.SEND_STYLE_HTTP);
PropertyUtils.initializeProperty(CommCareProperties.OTA_RESTORE_OFFLINE, "jr://file/commcare_ota_backup_offline.xml");
PropertyUtils.initializeProperty(CommCareProperties.RESTORE_TOLERANCE, CommCareProperties.REST_TOL_LOOSE);
PropertyUtils.initializeProperty(CommCareProperties.DEMO_MODE, CommCareProperties.DEMO_ENABLED);
PropertyUtils.initializeProperty(CommCareProperties.TETHER_MODE, CommCareProperties.TETHER_PUSH_ONLY);
PropertyUtils.initializeProperty(CommCareProperties.LOGIN_IMAGE, "jr://resource/icon.png");
PropertyManager._().setProperty(CommCareProperties.COMMCARE_VERSION, CommCareUtil.getVersion());
PropertyUtils.initializeProperty(CommCareProperties.USER_REG_TYPE, CommCareProperties.USER_REG_REQUIRED);
PropertyUtils.initializeProperty(CommCareProperties.AUTO_UPDATE_FREQUENCY, CommCareProperties.FREQUENCY_NEVER);
}
public static void init(MIDlet m, InitializationListener listener) {
i = new CommCareContext();
try{
i.configureApp(m, listener);
} catch(Exception e) {
Logger.die("Init!", e);
}
}
public static CommCareContext _() {
if(i == null) {
throw new RuntimeException("CommCareContext must be initialized with the Midlet to be used.");
}
return i;
}
public void setUser (User u, HttpCredentialProvider userCredentials) {
this.loggedInUserID = u.getUniqueId();
this.userCredentials = userCredentials;
AuthUtils.setStaticAuthenticator(new HttpAuthenticator(CommCareUtil.wrapCredentialProvider(userCredentials)));
}
public User getUser () {
if(User.DEMO_USER.equals(loggedInUserID)) {
return User.FactoryDemoUser();
} else if(loggedInUserID != null) {
return (User)((IStorageUtilityIndexed)StorageManager.getStorage(User.STORAGE_KEY)).getRecordForValue(User.META_UID, loggedInUserID);
} else {
return null;
}
}
public HttpCredentialProvider getCurrentUserCredentials() {
if( userCredentials != null) {
return userCredentials;
} else {
return new UserCredentialProvider(CommCareContext._().getUser());
}
}
public PeriodicEvent[] getEventDescriptors() {
return new PeriodicEvent[] {new TimeMessageEvent(), new PermissionsEvent(), new AutoUpdateEvent(), new AutoSyncEvent()};
}
public Vector<IFunctionHandler> getFuncHandlers () {
Vector<IFunctionHandler> handlers = new Vector<IFunctionHandler>();
handlers.addElement(new HouseholdExistsFuncHandler());
handlers.addElement(new CHWReferralNumFunc()); //BHOMA custom!
return handlers;
}
/// Probably put this stuff into app specific ones.
public Vector<IPreloadHandler> getPreloaders() {
Vector<IPreloadHandler> handlers = new Vector<IPreloadHandler>();
MetaPreloadHandler meta = new MetaPreloadHandler(this.getUser());
handlers.addElement(meta);
handlers.addElement(new UserPreloadHandler(this.getUser()));
return handlers;
}
private void registerDemoStorage (String key, Class type) {
StorageManager.registerStorage(key, "DEMO_" + key, type);
}
private void registerWrappedDemoStorage(String key, SerializationWrapper wrapper) {
StorageManager.registerWrappedStorage(key, "DEMO_" + key, wrapper);
}
public void toggleDemoMode(boolean demoOn) {
if (demoOn != inDemoMode) {
CommCareUtil.cycleDemoStyles(demoOn);
inDemoMode = demoOn;
if (demoOn) {
registerDemoStorage(Case.STORAGE_KEY, Case.class);
registerDemoStorage(FormInstance.STORAGE_KEY, FormInstance.class);
registerWrappedDemoStorage(TransportMessageStore.Q_STORENAME, new TransportMessageSerializationWrapper());
registerWrappedDemoStorage(TransportMessageStore.RECENTLY_SENT_STORENAME, new TransportMessageSerializationWrapper());
TransportService.reinit();
} else {
StorageManager.registerStorage(Case.STORAGE_KEY, Case.class);
StorageManager.registerStorage(FormInstance.STORAGE_KEY, FormInstance.class);
StorageManager.registerWrappedStorage(TransportMessageStore.Q_STORENAME, TransportMessageStore.Q_STORENAME, new TransportMessageSerializationWrapper());
StorageManager.registerWrappedStorage(TransportMessageStore.RECENTLY_SENT_STORENAME, TransportMessageStore.RECENTLY_SENT_STORENAME, new TransportMessageSerializationWrapper());
TransportService.reinit();
}
}
}
public void resetDemoData() {
boolean curmode = inDemoMode;
if(!inDemoMode) {
toggleDemoMode(true);
}
StorageManager.getStorage(Case.STORAGE_KEY).removeAll();
StorageManager.getStorage(FormInstance.STORAGE_KEY).removeAll();
StorageManager.getStorage(TransportMessageStore.Q_STORENAME).removeAll();
StorageManager.getStorage(TransportMessageStore.RECENTLY_SENT_STORENAME).removeAll();
toggleDemoMode(curmode);
}
public boolean inDemoMode() {
return inDemoMode;
}
public void purgeScheduler (boolean force) {
int purgeFreq = CommCareProperties.parsePurgeFreq(PropertyManager._().getSingularProperty(CommCareProperties.PURGE_FREQ));
Date purgeLast = CommCareProperties.parseLastPurge(PropertyManager._().getSingularProperty(CommCareProperties.PURGE_LAST));
if (force || purgeFreq <= 0 || purgeLast == null || ((new Date().getTime() - purgeLast.getTime()) / 86400000l) >= purgeFreq) {
String logMsg = purgeMsg(autoPurge());
PropertyManager._().setProperty(CommCareProperties.PURGE_LAST, DateUtils.formatDateTime(new Date(), DateUtils.FORMAT_ISO8601));
Logger.log("record-purge", logMsg);
}
}
public Hashtable<String, Hashtable<Integer, String>> autoPurge () {
Hashtable<String, Hashtable<Integer, String>> deletedLog = new Hashtable<String, Hashtable<Integer, String>>();
//attempt to purge different types of objects in such an order that, if interrupted, we'll avoid referential integrity errors
//1) tx queue is self-managing
//do nothing
//3) cases (delete cases that are closed AND have no open cases which index them)
purgeRMS(Case.STORAGE_KEY, caseFilter(), deletedLog);
//4) Ledger models (ledger database objects with no matching case)
purgeRMS(Ledger.STORAGE_KEY, new LedgerPurgeFilter((IStorageUtilityIndexed)StorageManager.getStorage(Ledger.STORAGE_KEY),
(IStorageUtilityIndexed)StorageManager.getStorage(Case.STORAGE_KEY)), deletedLog);
//5) reclog will never grow that large in size
//do nothing
//6) incident log is (mostly) self-managing
//do nothing
return deletedLog;
}
private EntityFilter<Case> caseFilter() {
//We need to determine if we're using ownership for purging. For right now, only in sync mode
Vector<String> owners = null;
if(CommCareProperties.TETHER_SYNC.equals(PropertyManager._().getSingularProperty(CommCareProperties.TETHER_MODE))) {
owners = new Vector<String>();
Vector<String> users = new Vector<String>();
for(IStorageIterator<User> userIterator = StorageManager.getStorage(User.STORAGE_KEY).iterate(); userIterator.hasMore();) {
String id = userIterator.nextRecord().getUniqueId();
owners.addElement(id);
users.addElement(id);
}
//Now add all of the relevant groups
//TODO: Wow. This is.... kind of megasketch
for(String userId : users) {
DataInstance instance = CommCareUtil.loadFixtureForUser("user-groups", userId);
if(instance == null) { continue; }
EvaluationContext ec = new EvaluationContext(instance);
for(TreeReference ref : ec.expandReference(XPathReference.getPathExpr("/groups/group/@id").getReference())) {
AbstractTreeElement<AbstractTreeElement> idelement = ec.resolveReference(ref);
if(idelement.getValue() != null) {
owners.addElement(idelement.getValue().uncast().getString());
}
}
}
}
return new CasePurgeFilter((RMSStorageUtilityIndexed<Case>)StorageManager.getStorage(Case.STORAGE_KEY), owners);
}
private void purgeRMS (String key, EntityFilter filt, Hashtable<String, Hashtable<Integer, String>> deletedLog) {
RMSStorageUtility rms = (RMSStorageUtility)StorageManager.getStorage(key);
//TODO: Reimplement the printout here.
//Hashtable<Integer, RMSRecordLoc> index = rms.getIDIndexRecord();
Vector<Integer> deletedIDs = rms.removeAll(filt);
Hashtable<Integer, String> deletedDetail = new Hashtable<Integer, String>();
for (int i = 0; i < deletedIDs.size(); i++) {
int id = deletedIDs.elementAt(i).intValue();
//RMSRecordLoc detail = index.get(new Integer(id));
RMSRecordLoc detail = null;
deletedDetail.put(new Integer(id), detail != null ? "(" + detail.rmsID + "," + detail.recID + ")" : "?");
}
deletedLog.put(key, deletedDetail);
}
//aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
private String purgeMsg (Hashtable<String, Hashtable<Integer, String>> detail) {
if (detail == null)
return "";
StringBuffer sb = new StringBuffer();
int i = 0;
for (Enumeration e = detail.keys(); e.hasMoreElements(); i++) {
String key = (String)e.nextElement();
Hashtable<Integer, String> rmsDetail = detail.get(key);
sb.append(key + "[");
int j = 0;
for (Enumeration f = rmsDetail.keys(); f.hasMoreElements(); j++) {
int id = ((Integer)f.nextElement()).intValue();
String ext = rmsDetail.get(new Integer(id));
sb.append(id + (ext != null ? ":" + ext : ""));
if (j < rmsDetail.size() - 1)
sb.append(",");
}
sb.append("]");
if (i < detail.size() - 1)
sb.append(",");
}
return sb.toString();
}
public static final String STORAGE_TABLE_GLOBAL = "GLOBAL_RESOURCE_TABLE";
private static final String STORAGE_KEY_TEMPORARY = "RESOURCE_TABLE_";
private static ResourceTable global;
/**
* @return A static resource table which
*/
public static ResourceTable RetrieveGlobalResourceTable() {
if(global == null) {
global = ResourceTable.RetrieveTable((IStorageUtilityIndexed)StorageManager.getStorage(STORAGE_TABLE_GLOBAL));
}
//Not sure if this reference is actually a good idea, or whether we should
//get the storage link every time... For now, we'll reload storage each time
return global;
}
public static ResourceTable CreateTemporaryResourceTable(String name) {
ResourceTable table = new ResourceTable();
IStorageUtilityIndexed storage = null;
String storageKey = STORAGE_KEY_TEMPORARY + name.toUpperCase();
//Check if this table already exists, and return it if so.
for(String utilityName : StorageManager.listRegisteredUtilities()) {
if(utilityName.equals(storageKey)) {
table = ResourceTable.RetrieveTable((IStorageUtilityIndexed)StorageManager.getStorage(storageKey));
}
}
//Otherwise, create a new one.
if(storage == null) {
StorageManager.registerStorage(storageKey, storageKey, Resource.class);
table = ResourceTable.RetrieveTable((IStorageUtilityIndexed)StorageManager.getStorage(storageKey));
}
return table;
}
/**
* Clear out anything which may have been left around in the temporary update table
*
* @return
*/
protected static void ClearUpdateTable() {
//TODO: This is a lot of terrible coupling with the above...
CreateTemporaryResourceTable(CommCareUpgradeState.UPGRADE_TABLE_NAME).clear();
}
public void exitApp() {
midlet.notifyDestroyed();
}
public String getOTAURL() {
String url = PropertyManager._().getSingularProperty(CommCareProperties.OTA_RESTORE_URL);
String testingURL = PropertyManager._().getSingularProperty(CommCareProperties.OTA_RESTORE_TEST_URL);
if(CommCareUtil.isTestingMode() && testingURL != null) {
url = testingURL;
}
return url;
}
//custom code for BHOMA -- don't tell anyone
class CHWReferralNumFunc implements IFunctionHandler {
Hashtable<String, String> referralCache = new Hashtable<String, String>();
public String getName() {
return "chw-referral-num";
}
public Vector getPrototypes() {
Vector p = new Vector();
p.addElement(new Class[] {String.class});
return p;
}
public boolean rawArgs() {
return false;
}
public Object eval(Object[] args, EvaluationContext ec) {
//each repeat has a hidden generated uid. we cache the generated referral code
//under this uid, so we don't regenerate it if we navigate through the repeititon
//again
String key = (String)args[0];
if (key.length() == 0) {
//referral code is non-relevant; don't generate/increment
return "_nonrelev";
} else if (referralCache.containsKey(key)) {
//fetch cached referral code
return referralCache.get(key);
} else {
//generate/increment fresh referral code and cache it
User u = CommCareContext._().getUser();
String refCode = u.getProperty("clinic_prefix") + "-" + u.getProperty("chw_zone") + "-";
String sRefCounter = u.getProperty("ref_count");
int refCounter = (sRefCounter == null ? 0 : Integer.parseInt(sRefCounter));
refCounter += 1;
if (refCounter >= 10000)
refCounter = 1;
sRefCounter = Integer.toString(refCounter);
u.setProperty("ref_count", sRefCounter);
IStorageUtility users = StorageManager.getStorage(User.STORAGE_KEY);
try {
users.write(u);
} catch (StorageFullException e) {
Logger.exception(e);
}
while (sRefCounter.length() < 4) {
sRefCounter = "0" + sRefCounter;
}
refCode += sRefCounter;
referralCache.put(key, refCode);
return refCode;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.api.java.typeutils.runtime;
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.typeutils.GenericTypeSerializerConfigSnapshot;
import org.apache.flink.api.common.typeutils.GenericTypeSerializerSnapshot;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerSchemaCompatibility;
import org.apache.flink.api.common.typeutils.TypeSerializerSnapshot;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.util.InstantiationUtil;
import com.esotericsoftware.kryo.Kryo;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Writable;
import org.objenesis.strategy.StdInstantiatorStrategy;
import java.io.IOException;
/**
* A {@link TypeSerializer} for {@link Writable}.
*
* @param <T>
*/
@Internal
public final class WritableSerializer<T extends Writable> extends TypeSerializer<T> {
private static final long serialVersionUID = 1L;
private final Class<T> typeClass;
private transient Kryo kryo;
private transient T copyInstance;
public WritableSerializer(Class<T> typeClass) {
this.typeClass = typeClass;
}
@SuppressWarnings("unchecked")
@Override
public T createInstance() {
if (typeClass == NullWritable.class) {
return (T) NullWritable.get();
}
return InstantiationUtil.instantiate(typeClass);
}
@Override
public T copy(T from) {
checkKryoInitialized();
return KryoUtils.copy(from, kryo, this);
}
@Override
public T copy(T from, T reuse) {
checkKryoInitialized();
return KryoUtils.copy(from, reuse, kryo, this);
}
@Override
public int getLength() {
return -1;
}
@Override
public void serialize(T record, DataOutputView target) throws IOException {
record.write(target);
}
@Override
public T deserialize(DataInputView source) throws IOException {
return deserialize(createInstance(), source);
}
@Override
public T deserialize(T reuse, DataInputView source) throws IOException {
reuse.readFields(source);
return reuse;
}
@Override
public void copy(DataInputView source, DataOutputView target) throws IOException {
ensureInstanceInstantiated();
copyInstance.readFields(source);
copyInstance.write(target);
}
@Override
public boolean isImmutableType() {
return false;
}
@Override
public WritableSerializer<T> duplicate() {
return new WritableSerializer<T>(typeClass);
}
// --------------------------------------------------------------------------------------------
private void ensureInstanceInstantiated() {
if (copyInstance == null) {
copyInstance = createInstance();
}
}
private void checkKryoInitialized() {
if (this.kryo == null) {
this.kryo = new Kryo();
Kryo.DefaultInstantiatorStrategy instantiatorStrategy =
new Kryo.DefaultInstantiatorStrategy();
instantiatorStrategy.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy());
kryo.setInstantiatorStrategy(instantiatorStrategy);
this.kryo.setAsmEnabled(true);
this.kryo.register(typeClass);
}
}
// --------------------------------------------------------------------------------------------
@Override
public int hashCode() {
return this.typeClass.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof WritableSerializer) {
WritableSerializer<?> other = (WritableSerializer<?>) obj;
return typeClass == other.typeClass;
} else {
return false;
}
}
// --------------------------------------------------------------------------------------------
// Serializer configuration snapshotting & compatibility
// --------------------------------------------------------------------------------------------
@Override
public TypeSerializerSnapshot<T> snapshotConfiguration() {
return new WritableSerializerSnapshot<>(typeClass);
}
/**
* The config snapshot for this serializer.
*
* @deprecated This class is no longer used as a snapshot for any serializer. It is fully
* replaced by {@link WritableSerializerSnapshot}.
*/
@Deprecated
public static final class WritableSerializerConfigSnapshot<T extends Writable>
extends GenericTypeSerializerConfigSnapshot<T> {
private static final int VERSION = 1;
/** This empty nullary constructor is required for deserializing the configuration. */
public WritableSerializerConfigSnapshot() {}
public WritableSerializerConfigSnapshot(Class<T> writableTypeClass) {
super(writableTypeClass);
}
@Override
public int getVersion() {
return VERSION;
}
@Override
public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility(
TypeSerializer<T> newSerializer) {
return new WritableSerializerSnapshot<>(getTypeClass())
.resolveSchemaCompatibility(newSerializer);
}
}
/** {@link WritableSerializer} snapshot class. */
public static final class WritableSerializerSnapshot<T extends Writable>
extends GenericTypeSerializerSnapshot<T, WritableSerializer> {
@SuppressWarnings("unused")
public WritableSerializerSnapshot() {}
WritableSerializerSnapshot(Class<T> typeClass) {
super(typeClass);
}
@Override
protected TypeSerializer<T> createSerializer(Class<T> typeClass) {
return new WritableSerializer<>(typeClass);
}
@SuppressWarnings("unchecked")
@Override
protected Class<T> getTypeClass(WritableSerializer serializer) {
return serializer.typeClass;
}
@Override
protected Class<?> serializerClass() {
return WritableSerializer.class;
}
}
}
| |
package eu.socialsensor.framework.client.mongo;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import com.mongodb.util.JSON;
import eu.socialsensor.framework.common.domain.JSONable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
/**
*
* @author etzoannos
*
*/
public class MongoHandler {
public static int ASC = 1;
public static int DESC = -1;
private static Map<String, MongoClient> connections = new HashMap<String, MongoClient>();
private static Map<String, DB> databases = new HashMap<String, DB>();
private DBCollection collection;
private DBObject sortField = new BasicDBObject("_id", -1);
private DBObject publicationTimeField = new BasicDBObject("publicationTime", -1);
private DB db = null;
private static MongoClientOptions options = MongoClientOptions.builder()
.writeConcern(WriteConcern.UNACKNOWLEDGED).build();
private Logger logger = Logger.getLogger(MongoHandler.class);
public MongoHandler(String host, String dbName, String collectionName, List<String> indexes) throws Exception {
this(host, dbName);
collection = db.getCollection(collectionName);
if (indexes != null) {
for (String index : indexes) {
collection.ensureIndex(index);
}
}
}
public MongoHandler(String hostname, String dbName) throws Exception {
String connectionKey = hostname + "#" + dbName;
db = databases.get(connectionKey);
if (db == null) {
MongoClient mongo = connections.get(hostname);
if (mongo == null) {
mongo = new MongoClient(hostname, options);
connections.put(hostname, mongo);
}
db = mongo.getDB(dbName);
databases.put(connectionKey, db);
}
}
/**
* A MongoHandler for a database with enabled authentication
*
* @param hostname
* @param dbName
* @param collectionName
* @param indexes
* @param username
* @param password
* @throws Exception
*/
public MongoHandler(String hostname, String dbName, String collectionName, List<String> indexes, String username, char[] password) throws Exception {
String connectionKey = hostname + "#" + dbName;
db = databases.get(connectionKey);
if (db == null) {
MongoClient mongo = connections.get(hostname);
if (mongo == null) {
mongo = new MongoClient(hostname, options);
connections.put(hostname, mongo);
}
db = mongo.getDB(dbName);
if (db.authenticate(username, password)) {
databases.put(connectionKey, db);
} else {
throw new RuntimeException("Could not login to " + dbName + " database with user " + username);
}
}
collection = db.getCollection(collectionName);
if (indexes != null) {
for (String index : indexes) {
collection.ensureIndex(index);
}
}
}
public boolean checkConnection(String hostname) {
MongoClient mongo = connections.get(hostname);
if (mongo == null) {
return false;
}
try {
mongo.getDatabaseNames();
}
catch(Exception e) {
logger.error("MongoDB at " + hostname + " is closed.");
return false;
}
return true;
}
public void sortBy(String field, int order) throws MongoException {
this.sortField = new BasicDBObject(field, order);
}
public void insert(JSONable jsonObject, String collName) throws MongoException {
String json = jsonObject.toJSONString();
DBObject object = (DBObject) JSON.parse(json);
DBCollection coll = db.getCollection(collName);
coll.insert(object);
}
public void insert(JSONable jsonObject) throws MongoException {
String json = jsonObject.toJSONString();
DBObject object = (DBObject) JSON.parse(json);
collection.insert(object);
}
public void insertJson(String json) {
DBObject object = (DBObject) JSON.parse(json);
collection.insert(object);
}
public void insert(Map<String, Object> map) throws MongoException {
collection.insert(new BasicDBObject(map));
}
public boolean exists(String fieldName, String fieldValue) throws MongoException {
BasicDBObject query = new BasicDBObject(fieldName, fieldValue);
DBObject result = collection.findOne(query, new BasicDBObject("_id", 1));
if (result == null) {
return false;
}
return true;
}
public String findOne() {
DBObject result = collection.findOne(new BasicDBObject());
return JSON.serialize(result);
}
public String findOne(String fieldName, String fieldValue) throws MongoException {
BasicDBObject query = new BasicDBObject(fieldName, fieldValue);
DBObject result = collection.findOne(query);
return JSON.serialize(result);
}
public Object findOneField(String fieldName, String fieldValue, String retField) throws MongoException {
BasicDBObject query = new BasicDBObject(fieldName, fieldValue);
BasicDBObject field = new BasicDBObject(retField, 1);
DBObject result = collection.findOne(query, field);
if (result == null) {
return null;
}
return result.get(retField);
}
public String findOne(Selector query) throws MongoException {
DBObject object = (DBObject) JSON.parse(query.toJSONString());
DBObject result = collection.findOne(object);
return JSON.serialize(result);
}
public int findCount(Pattern fieldValue) throws MongoException {
BasicDBObject query = new BasicDBObject("title", fieldValue);
long count = collection.count(query);
return (int) count;
}
public int findCountWithLimit(Pattern fieldValue, int limit) throws MongoException {
BasicDBObject query = new BasicDBObject("title", fieldValue);
long count = (int) collection.getCount(query, null, limit, 0);
return (int) count;
}
public List<String> findMany(int n) throws MongoException {
DBCursor cursor = collection.find(new BasicDBObject()).sort(sortField);
List<String> jsonResults = new ArrayList<String>();
if (n > 0) {
cursor = cursor.limit(n);
}
try {
while (cursor.hasNext()) {
DBObject current = cursor.next();
jsonResults.add(JSON.serialize(current));
}
} finally {
cursor.close();
}
return jsonResults;
}
public List<String> findManyWithOrDeprecated(String field, List<String> values, int n) throws MongoException {
String prefix = "{$or:[";
String jsonString = "";
int count = 1;
for (String value : values) {
jsonString = jsonString + "{\"" + field + "\":\"" + value + "\"}";
if (count != values.size()) {
jsonString = jsonString + ",";
}
count++;
}
String suffix = "]}";
jsonString = prefix + jsonString + suffix;
DBObject object = (DBObject) JSON.parse(jsonString);
DBCursor cursor = collection.find(object).sort(sortField);
if (n > 0) {
cursor = cursor.limit(n);
}
List<String> jsonResults = new ArrayList<String>();
try {
while (cursor.hasNext()) {
DBObject current = cursor.next();
jsonResults.add(JSON.serialize(current));
}
} finally {
cursor.close();
}
return jsonResults;
}
public List<String> findManyWithOr(String field, List<String> values, int n) throws MongoException {
String prefix = "{" + field + ": {$in:[";
String jsonString = "";
int count = 1;
for (String value : values) {
jsonString = jsonString + "\"" + value + "\"";
if (count != values.size()) {
jsonString = jsonString + ",";
}
count++;
}
String suffix = "]}}";
jsonString = prefix + jsonString + suffix;
System.out.println(jsonString);
DBObject object = (DBObject) JSON.parse(jsonString);
DBCursor cursor = collection.find(object).sort(sortField);
if (n > 0) {
cursor = cursor.limit(n);
}
List<String> jsonResults = new ArrayList<String>();
try {
while (cursor.hasNext()) {
DBObject current = cursor.next();
jsonResults.add(JSON.serialize(current));
}
} finally {
cursor.close();
}
return jsonResults;
}
public List<String> findManyWithOr(String fieldName, String fieldValue, String orField, List<String> values, int n) throws MongoException {
String prefix = "{\"" + fieldName + "\":\"" + fieldValue + "\"" + ",\"" + orField + "\": {$in:[";
String jsonString = "";
int count = 1;
for (String value : values) {
jsonString = jsonString + "\"" + value + "\"";
if (count != values.size()) {
jsonString = jsonString + ",";
}
count++;
}
String suffix = "]}}";
jsonString = prefix + jsonString + suffix;
System.out.println(jsonString);
DBObject object = (DBObject) JSON.parse(jsonString);
DBCursor cursor = collection.find(object).sort(sortField);
if (n > 0) {
cursor = cursor.limit(n);
}
List<String> jsonResults = new ArrayList<String>();
try {
while (cursor.hasNext()) {
DBObject current = cursor.next();
jsonResults.add(JSON.serialize(current));
}
} finally {
cursor.close();
}
return jsonResults;
}
public List<String> findMany(DBObject query, int n) throws MongoException {
DBCursor cursor = collection.find(query).sort(sortField);
List<String> jsonResults = new ArrayList<String>();
if (n > 0) {
cursor = cursor.limit(n);
}
try {
while (cursor.hasNext()) {
DBObject current = cursor.next();
jsonResults.add(JSON.serialize(current));
}
} finally {
cursor.close();
}
return jsonResults;
}
public List<String> findMany(Selector query, int n) throws MongoException {
DBObject object = (DBObject) JSON.parse(query.toJSONString());
DBCursor cursor = collection.find(object).sort(sortField);
if (n > 0) {
cursor = cursor.limit(n);
}
List<String> jsonResults = new ArrayList<String>();
try {
while (cursor.hasNext()) {
DBObject current = cursor.next();
jsonResults.add(JSON.serialize(current));
}
} finally {
cursor.close();
}
return jsonResults;
}
public List<String> findManyNoSorting(Selector query, int n) throws MongoException {
DBObject object = (DBObject) JSON.parse(query.toJSONString());
DBCursor cursor = collection.find(object);
if (n > 0) {
cursor = cursor.limit(n);
}
List<String> jsonResults = new ArrayList<String>();
try {
while (cursor.hasNext()) {
DBObject current = cursor.next();
jsonResults.add(JSON.serialize(current));
}
} finally {
cursor.close();
}
return jsonResults;
}
public List<String> findManySortedByPublicationTime(Selector query, int n) throws MongoException {
DBObject object = (DBObject) JSON.parse(query.toJSONString());
DBCursor cursor = collection.find(object).sort(publicationTimeField);
if (n > 0) {
cursor = cursor.limit(n);
}
List<String> jsonResults = new ArrayList<String>();
try {
while (cursor.hasNext()) {
DBObject current = cursor.next();
jsonResults.add(JSON.serialize(current));
}
} finally {
cursor.close();
}
return jsonResults;
}
public List<String> findMany(String fieldName, Object fieldValue, int n) throws MongoException {
DBObject query = new BasicDBObject(fieldName, fieldValue);
DBCursor cursor = collection.find(query).sort(sortField);
if (n > 0) {
cursor = cursor.limit(n);
}
List<String> jsonResults = new ArrayList<String>();
try {
while (cursor.hasNext()) {
DBObject current = cursor.next();
jsonResults.add(JSON.serialize(current));
}
} finally {
cursor.close();
}
return jsonResults;
}
public void clean() throws MongoException {
collection.drop();
}
public void close() throws MongoException {
Mongo mongo = db.getMongo();
if (mongo != null) {
mongo.close();
}
}
public boolean delete(Map<?, ?> m) throws MongoException {
DBObject ro = new BasicDBObject(m);
WriteResult result = collection.remove(ro);
if (result.getN() > 0) {
return true;
}
return false;
}
public boolean delete(String fieldName, String fieldValue) throws MongoException {
DBObject ro = new BasicDBObject(fieldName, fieldValue);
WriteResult result = collection.remove(ro);
if (result.getN() > 0) {
return true;
}
return false;
}
public boolean delete(String fieldName, String fieldValue, String collName) throws MongoException {
DBCollection coll = db.getCollection(collName);
DBObject ro = new BasicDBObject(fieldName, fieldValue);
WriteResult result = coll.remove(ro);
if (result.getN() > 0) {
return true;
}
return false;
}
public boolean delete() {
db.dropDatabase();
return true;
}
public void update(String fieldName, String fieldValue, JSONable jsonObject) throws MongoException {
BasicDBObject q = new BasicDBObject(fieldName, fieldValue);
DBObject update = (DBObject) JSON.parse(jsonObject.toJSONString());
collection.update(q, update, false, false);
}
public void update(String fieldName, String fieldValue, Map<String, Object> map) throws MongoException {
BasicDBObject q = new BasicDBObject(fieldName, fieldValue);
DBObject update = new BasicDBObject(map);
collection.update(q, update, false, false);
}
public void update(String fieldName, String fieldValue, DBObject changes) throws MongoException {
BasicDBObject q = new BasicDBObject(fieldName, fieldValue);
collection.update(q, changes);
}
public void updateOld(String fieldName, String fieldValue, JSONable jsonObject) throws MongoException {
BasicDBObject q = new BasicDBObject(fieldName, fieldValue);
DBObject update = (DBObject) JSON.parse(jsonObject.toJSONString());
BasicDBObject newDocument = new BasicDBObject();
newDocument.append("$set", update);
collection.update(q, newDocument, false, true);
}
public MongoIterator getIterator(DBObject query) {
DBCursor cursor = collection.find(query);
MongoIterator iterator = new MongoIterator(cursor);
return iterator;
}
public MongoIterator getIterator(Selector query) {
DBObject object = (DBObject) JSON.parse(query.toJSONString());
DBCursor cursor = collection.find(object);
MongoIterator iterator = new MongoIterator(cursor);
return iterator;
}
public class MongoIterator implements Iterator<String> {
private DBCursor cursor;
private MongoIterator(DBCursor cursor) {
this.cursor = cursor;
}
public String next() {
DBObject next = cursor.next();
return next.toString();
}
public boolean hasNext() {
return cursor.hasNext();
}
@Override
public void remove() {
cursor.next();
}
}
public static void main(String[] args) throws Exception {
MongoHandler handler = new MongoHandler("xxx.xxx.xxx", "Streams", "Items", null);
MongoIterator it = handler.getIterator(new BasicDBObject());
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
| |
package ua.com.fielden.platform.web_api;
import static graphql.ExecutionInput.newExecutionInput;
import static graphql.GraphQL.newGraphQL;
import static graphql.schema.FieldCoordinates.coordinates;
import static graphql.schema.GraphQLCodeRegistry.newCodeRegistry;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
import static graphql.schema.GraphQLObjectType.newObject;
import static graphql.schema.GraphQLSchema.newSchema;
import static java.lang.String.format;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang.StringUtils.uncapitalize;
import static ua.com.fielden.platform.domaintree.impl.AbstractDomainTree.reflectionProperty;
import static ua.com.fielden.platform.domaintree.impl.AbstractDomainTreeRepresentation.constructKeysAndProperties;
import static ua.com.fielden.platform.domaintree.impl.AbstractDomainTreeRepresentation.isExcluded;
import static ua.com.fielden.platform.entity.AbstractUnionEntity.unionProperties;
import static ua.com.fielden.platform.reflection.TitlesDescsGetter.getEntityTitleAndDesc;
import static ua.com.fielden.platform.streaming.ValueCollectors.toLinkedHashMap;
import static ua.com.fielden.platform.utils.EntityUtils.isIntrospectionDenied;
import static ua.com.fielden.platform.utils.EntityUtils.isUnionEntityType;
import static ua.com.fielden.platform.utils.Pair.pair;
import static ua.com.fielden.platform.web_api.FieldSchema.LIKE_ARGUMENT;
import static ua.com.fielden.platform.web_api.FieldSchema.ORDER_ARGUMENT;
import static ua.com.fielden.platform.web_api.FieldSchema.PAGE_CAPACITY_ARGUMENT;
import static ua.com.fielden.platform.web_api.FieldSchema.PAGE_NUMBER_ARGUMENT;
import static ua.com.fielden.platform.web_api.FieldSchema.bold;
import static ua.com.fielden.platform.web_api.FieldSchema.createGraphQLFieldDefinition;
import static ua.com.fielden.platform.web_api.FieldSchema.titleAndDescRepresentation;
import static ua.com.fielden.platform.web_api.RootEntityUtils.QUERY_TYPE_NAME;
import static ua.com.fielden.platform.web_api.WebApiUtils.operationName;
import static ua.com.fielden.platform.web_api.WebApiUtils.query;
import static ua.com.fielden.platform.web_api.WebApiUtils.variables;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.apache.log4j.Logger;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import graphql.GraphQL;
import graphql.analysis.MaxQueryDepthInstrumentation;
import graphql.schema.GraphQLCodeRegistry;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLList;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLObjectType.Builder;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLType;
import graphql.schema.GraphQLTypeReference;
import ua.com.fielden.platform.basic.config.IApplicationDomainProvider;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.AbstractUnionEntity;
import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder;
import ua.com.fielden.platform.security.IAuthorisationModel;
import ua.com.fielden.platform.security.provider.ISecurityTokenProvider;
import ua.com.fielden.platform.utils.EntityUtils;
import ua.com.fielden.platform.utils.IDates;
import ua.com.fielden.platform.utils.Pair;
import ua.com.fielden.platform.web_api.exceptions.WebApiException;
/**
* Represents GraphQL-based implementation of TG Web API using library <a href="https://github.com/graphql-java/graphql-java">graphql-java</a>.
* <p>
* At this stage only GraphQL {@code query} is supported.
*
* @author TG Team
*
*/
public class GraphQLService implements IWebApi {
private final Logger logger = Logger.getLogger(getClass());
private final GraphQLSchema schema;
private final Integer maxQueryDepth;
/**
* Creates GraphQLService instance based on {@code applicationDomainProvider} which contains all entity types.
* <p>
* We start by building dictionary of all our custom GraphQL types from existing domain entity types.
* Then we create GraphQL type for quering (aka GraphQL {@code query}) and assign it to the schema.
*
* @param maxQueryDepth -- the maximum depth of GraphQL query that are permitted to be executed.
* @param applicationDomainProvider
* @param coFinder
* @param dates
* @param authorisation
* @param securityTokensPackageName
* @param securityTokenProvider
*/
@Inject
public GraphQLService(
final @Named("web.api.maxQueryDepth") Integer maxQueryDepth,
final IApplicationDomainProvider applicationDomainProvider,
final ICompanionObjectFinder coFinder,
final IDates dates,
final IAuthorisationModel authorisation,
final ISecurityTokenProvider securityTokenProvider
) {
try {
logger.info("GraphQL Web API...");
if (maxQueryDepth == null || maxQueryDepth.compareTo(0) < 0) {
throw new WebApiException("GraphQL max query depth must be specified and cannot be negative.");
}
this.maxQueryDepth = maxQueryDepth;
logger.info("\tmaxQueryDepth = " + maxQueryDepth);
final GraphQLCodeRegistry.Builder codeRegistryBuilder = newCodeRegistry();
logger.info("\tBuilding dictionary...");
final Set<Class<? extends AbstractEntity<?>>> domainTypes = domainTypesOf(applicationDomainProvider, EntityUtils::isIntrospectionAllowed).stream() // synthetic / persistent without @DenyIntrospection; this includes persistent with activatable nature, synthetic based on persistent; this does not include union, functional and any other entities
.sorted((type1, type2) -> type1.getSimpleName().compareTo(type2.getSimpleName()))
.collect(toCollection(LinkedHashSet::new));
final Set<Class<? extends AbstractEntity<?>>> allTypes = new LinkedHashSet<>(domainTypes);
allTypes.addAll(domainTypesOf(applicationDomainProvider, EntityUtils::isUnionEntityType));
// dictionary must have all the types that are referenced by all types that should support querying
final Map<Class<? extends AbstractEntity<?>>, GraphQLType> dictionary = createDictionary(allTypes);
logger.info("\tBuilding query type...");
final GraphQLObjectType queryType = createQueryType(domainTypes, coFinder, dates, codeRegistryBuilder, authorisation, securityTokenProvider);
logger.info("\tBuilding field visibility...");
codeRegistryBuilder.fieldVisibility(new FieldVisibility(authorisation, domainTypes, securityTokenProvider));
logger.info("\tBuilding schema...");
schema = newSchema()
.codeRegistry(codeRegistryBuilder.build())
.query(queryType)
.additionalTypes(new LinkedHashSet<>(dictionary.values()))
.build();
logger.info("GraphQL Web API...done");
} catch (final Throwable t) {
logger.error("GraphQL Web API error.", t);
throw t;
}
}
/**
* Returns all domain types from {@code applicationDomainProvider} that do not have introspection denied and satisfy predicate {@code toInclude}.
*/
private Set<Class<? extends AbstractEntity<?>>> domainTypesOf(final IApplicationDomainProvider applicationDomainProvider, final Predicate<Class<? extends AbstractEntity<?>>> toInclude) {
return applicationDomainProvider.entityTypes().stream()
.filter(type ->
!isIntrospectionDenied(type) // ensure that only entity types that don't have @DenyIntrospection annotation are included
&& toInclude.test(type) )
.collect(toCollection(LinkedHashSet::new));
}
/**
* Executes Web API query by using internal {@link GraphQL} service with predefined schema.
* <p>
* {@inheritDoc}
*/
@Override
public Map<String, Object> execute(final Map<String, Object> input) {
return newGraphQL(schema)
.instrumentation(new MaxQueryDepthInstrumentation(maxQueryDepth)).build()
.execute(
newExecutionInput()
.query(query(input))
.operationName(operationName(input).orElse(null))
.variables(variables(input)))
.toSpecification();
}
/**
* Creates map of GraphQL dictionary (aka GraphQL "additional types") and corresponding entity types.
* <p>
* The set of resultant types can be smaller than those derived upon. See {@link #createGraphQLTypeFor(Class)} for more details.
*
* @param entityTypes
* @return
*/
private static Map<Class<? extends AbstractEntity<?>>, GraphQLType> createDictionary(final Set<Class<? extends AbstractEntity<?>>> entityTypes) {
return entityTypes.stream()
.map(GraphQLService::createGraphQLTypeFor)
.flatMap(optType -> optType.map(Stream::of).orElseGet(Stream::empty))
.sorted((pair1, pair2) -> pair1.getKey().getSimpleName().compareTo(pair2.getKey().getSimpleName()))
.collect(toLinkedHashMap(Pair::getKey, Pair::getValue));
}
/**
* Creates type for GraphQL 'query' operation to query entities from {@code dictionary}.
* <p>
* All query field names are represented as uncapitalised entity type simple names. All sub-field names are represented as entity property names.
*
* @param dictionary -- list of supported GraphQL entity types
* @param coFinder
* @param dates
* @param codeRegistryBuilder -- a place to register root data fetchers
* @param authorisation
* @param securityTokensPackageName
* @return
*/
private static GraphQLObjectType createQueryType(final Set<Class<? extends AbstractEntity<?>>> dictionary, final ICompanionObjectFinder coFinder, final IDates dates, final GraphQLCodeRegistry.Builder codeRegistryBuilder, final IAuthorisationModel authorisation, final ISecurityTokenProvider securityTokenProvider) {
final Builder queryTypeBuilder = newObject().name(QUERY_TYPE_NAME).description("Query following **entities** represented as GraphQL root fields:");
dictionary.stream().forEach(entityType -> {
final String simpleTypeName = entityType.getSimpleName();
final String fieldName = uncapitalize(simpleTypeName);
queryTypeBuilder.field(newFieldDefinition()
.name(fieldName)
.description(format("Query %s.", bold(getEntityTitleAndDesc(entityType).getKey())))
.argument(LIKE_ARGUMENT)
.argument(ORDER_ARGUMENT)
.argument(PAGE_NUMBER_ARGUMENT)
.argument(PAGE_CAPACITY_ARGUMENT)
.type(new GraphQLList(new GraphQLTypeReference(simpleTypeName)))
);
codeRegistryBuilder.dataFetcher(coordinates(QUERY_TYPE_NAME, fieldName), new RootEntityFetcher<>((Class<AbstractEntity<?>>) entityType, coFinder, dates, authorisation, securityTokenProvider));
});
return queryTypeBuilder.build();
}
/**
* Creates {@link Optional} GraphQL object type for {@code entityType}d entities querying.
* <p>
* The {@code entityType} will not have corresponding {@link GraphQLObjectType} only if there are no suitable fields for querying.
*
* @param entityType
* @return
*/
private static Optional<Pair<Class<? extends AbstractEntity<?>>, GraphQLObjectType>> createGraphQLTypeFor(final Class<? extends AbstractEntity<?>> entityType) {
if (isExcluded(entityType, "")) { // generic type exclusion logic for root types (exclude abstract entity types, exclude types without KeyType annotation etc. -- see AbstractDomainTreeRepresentation.isExcluded)
return empty();
}
final List<GraphQLFieldDefinition> graphQLFieldDefinitions = (isUnionEntityType(entityType) ? unionProperties((Class<? extends AbstractUnionEntity>) entityType) : constructKeysAndProperties(entityType, true)).stream()
.filter(field -> !isExcluded(entityType, reflectionProperty(field.getName())))
.map(field -> createGraphQLFieldDefinition(entityType, field.getName()))
.flatMap(optField -> optField.map(Stream::of).orElseGet(Stream::empty))
.collect(toList());
if (!graphQLFieldDefinitions.isEmpty()) { // ignore types that have no GraphQL field equivalents; we can not use such types for any purpose including querying
// GraphQL type names are used to reference the types in other ones when the type is not created yet.
// We argue that simple names of domain types are unique across application domain.
// So these will be used for GraphQL type naming.
return of(pair(entityType, newObject()
.name(entityType.getSimpleName())
.description(titleAndDescRepresentation(getEntityTitleAndDesc(entityType)))
.fields(graphQLFieldDefinitions).build()
));
}
return empty();
}
}
| |
/*
* Copyright 2014 Groupon, Inc
* Copyright 2014 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.billing.payment;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import org.joda.time.LocalDate;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.catalog.api.Currency;
import org.killbill.billing.invoice.api.Invoice;
import org.killbill.billing.invoice.api.InvoiceApiException;
import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.payment.api.Payment;
import org.killbill.billing.payment.api.PaymentTransaction;
import org.killbill.billing.payment.api.PaymentApiException;
import org.killbill.billing.payment.api.PaymentOptions;
import org.killbill.billing.payment.api.PluginProperty;
import org.killbill.billing.payment.api.TransactionStatus;
import org.killbill.billing.payment.api.TransactionType;
import org.killbill.billing.payment.invoice.InvoicePaymentRoutingPluginApi;
import org.killbill.billing.payment.core.janitor.Janitor;
import org.killbill.billing.payment.dao.PaymentAttemptModelDao;
import org.killbill.billing.payment.provider.MockPaymentProviderPlugin;
import org.killbill.billing.platform.api.KillbillConfigSource;
import org.killbill.bus.api.PersistentBus.EventBusException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import static org.testng.Assert.assertEquals;
public class TestJanitor extends PaymentTestSuiteWithEmbeddedDB {
final PaymentOptions INVOICE_PAYMENT = new PaymentOptions() {
@Override
public boolean isExternalPayment() {
return false;
}
@Override
public List<String> getPaymentControlPluginNames() {
return ImmutableList.of(InvoicePaymentRoutingPluginApi.PLUGIN_NAME);
}
};
@Inject
private Janitor janitor;
private Account account;
@Override
protected KillbillConfigSource getConfigSource() {
return getConfigSource("/payment.properties",
ImmutableMap.<String, String>of("org.killbill.payment.provider.default", MockPaymentProviderPlugin.PLUGIN_NAME,
"killbill.payment.engine.events.off", "false",
"org.killbill.payment.janitor.rate", "500ms")
);
}
@BeforeClass(groups = "slow")
protected void beforeClass() throws Exception {
super.beforeClass();
janitor.start();
}
@AfterClass(groups = "slow")
protected void afterClass() throws Exception {
janitor.stop();
}
@BeforeMethod(groups = "slow")
public void beforeMethod() throws Exception {
super.beforeMethod();
account = testHelper.createTestAccount("bobo@gmail.com", true);
}
@AfterMethod(groups = "slow")
public void afterMethod() throws Exception {
super.afterMethod();
}
@Test(groups = "slow")
public void testCreateSuccessPurchaseWithPaymentControl() throws PaymentApiException, InvoiceApiException, EventBusException {
final BigDecimal requestedAmount = BigDecimal.TEN;
final UUID subscriptionId = UUID.randomUUID();
final UUID bundleId = UUID.randomUUID();
final LocalDate now = clock.getUTCToday();
final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD);
final String paymentExternalKey = invoice.getId().toString();
final String transactionExternalKey = "wouf wouf";
invoice.addInvoiceItem(new MockRecurringInvoiceItem(invoice.getId(), account.getId(),
subscriptionId,
bundleId,
"test plan",
"test phase", null,
now,
now.plusMonths(1),
requestedAmount,
new BigDecimal("1.0"),
Currency.USD));
final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey,
createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext);
assertEquals(payment.getTransactions().size(), 1);
assertEquals(payment.getTransactions().get(0).getTransactionStatus(), TransactionStatus.SUCCESS);
assertEquals(payment.getTransactions().get(0).getTransactionType(), TransactionType.PURCHASE);
final List<PaymentAttemptModelDao> attempts = paymentDao.getPaymentAttempts(paymentExternalKey, internalCallContext);
assertEquals(attempts.size(), 1);
final PaymentAttemptModelDao attempt = attempts.get(0);
assertEquals(attempt.getStateName(), "SUCCESS");
// Ok now the fun part starts... we modify the attempt state to be 'INIT' and wait the the Janitor to do its job.
paymentDao.updatePaymentAttempt(attempt.getId(), attempt.getTransactionId(), "INIT", internalCallContext);
final PaymentAttemptModelDao attempt2 = paymentDao.getPaymentAttempt(attempt.getId(), internalCallContext);
assertEquals(attempt2.getStateName(), "INIT");
clock.addDays(1);
try { Thread.sleep(1500); } catch (InterruptedException e) {};
final PaymentAttemptModelDao attempt3 = paymentDao.getPaymentAttempt(attempt.getId(), internalCallContext);
assertEquals(attempt3.getStateName(), "SUCCESS");
}
@Test(groups = "slow")
public void testCreateSuccessRefundPaymentControlWithItemAdjustments() throws PaymentApiException, InvoiceApiException, EventBusException {
final BigDecimal requestedAmount = BigDecimal.TEN;
final UUID subscriptionId = UUID.randomUUID();
final UUID bundleId = UUID.randomUUID();
final LocalDate now = clock.getUTCToday();
final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD);
final String paymentExternalKey = invoice.getId().toString();
final String transactionExternalKey = "craboom";
final String transactionExternalKey2 = "qwerty";
final InvoiceItem invoiceItem = new MockRecurringInvoiceItem(invoice.getId(), account.getId(),
subscriptionId,
bundleId,
"test plan", "test phase", null,
now,
now.plusMonths(1),
requestedAmount,
new BigDecimal("1.0"),
Currency.USD);
invoice.addInvoiceItem(invoiceItem);
final Payment payment = paymentApi.createPurchaseWithPaymentControl(account, account.getPaymentMethodId(), null, requestedAmount, Currency.USD, paymentExternalKey, transactionExternalKey,
createPropertiesForInvoice(invoice), INVOICE_PAYMENT, callContext);
final List<PluginProperty> refundProperties = new ArrayList<PluginProperty>();
final HashMap<UUID, BigDecimal> uuidBigDecimalHashMap = new HashMap<UUID, BigDecimal>();
uuidBigDecimalHashMap.put(invoiceItem.getId(), new BigDecimal("1.0"));
final PluginProperty refundIdsProp = new PluginProperty(InvoicePaymentRoutingPluginApi.PROP_IPCD_REFUND_IDS_WITH_AMOUNT_KEY, uuidBigDecimalHashMap, false);
refundProperties.add(refundIdsProp);
final Payment payment2 = paymentApi.createRefundWithPaymentControl(account, payment.getId(), null, Currency.USD, transactionExternalKey2,
refundProperties, INVOICE_PAYMENT, callContext);
assertEquals(payment2.getTransactions().size(), 2);
PaymentTransaction refundTransaction = payment2.getTransactions().get(1);
assertEquals(refundTransaction.getTransactionType(), TransactionType.REFUND);
final List<PaymentAttemptModelDao> attempts = paymentDao.getPaymentAttempts(paymentExternalKey, internalCallContext);
assertEquals(attempts.size(), 2);
final PaymentAttemptModelDao refundAttempt = attempts.get(1);
assertEquals(refundAttempt.getTransactionType(), TransactionType.REFUND);
// Ok now the fun part starts... we modify the attempt state to be 'INIT' and wait the the Janitor to do its job.
paymentDao.updatePaymentAttempt(refundAttempt.getId(), refundAttempt.getTransactionId(), "INIT", internalCallContext);
final PaymentAttemptModelDao attempt2 = paymentDao.getPaymentAttempt(refundAttempt.getId(), internalCallContext);
assertEquals(attempt2.getStateName(), "INIT");
clock.addDays(1);
try { Thread.sleep(1500); } catch (InterruptedException e) {};
final PaymentAttemptModelDao attempt3 = paymentDao.getPaymentAttempt(refundAttempt.getId(), internalCallContext);
assertEquals(attempt3.getStateName(), "SUCCESS");
}
private List<PluginProperty> createPropertiesForInvoice(final Invoice invoice) {
final List<PluginProperty> result = new ArrayList<PluginProperty>();
result.add(new PluginProperty(InvoicePaymentRoutingPluginApi.PROP_IPCD_INVOICE_ID, invoice.getId().toString(), false));
return result;
}
}
| |
/*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.impl.css.flavor;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.auraframework.Aura;
import org.auraframework.css.FlavorOverrideLocation;
import org.auraframework.css.FlavorOverrideLocator;
import org.auraframework.def.BaseComponentDef;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.DefDescriptor.DefType;
import org.auraframework.def.DescriptorFilter;
import org.auraframework.def.FlavorsDef;
import org.auraframework.def.FlavorDefaultDef;
import org.auraframework.def.FlavoredStyleDef;
import org.auraframework.def.RootDefinition;
import org.auraframework.expression.Expression;
import org.auraframework.impl.css.util.Flavors;
import org.auraframework.impl.system.DefinitionImpl;
import org.auraframework.impl.util.AuraUtil;
import org.auraframework.system.AuraContext;
import org.auraframework.system.MasterDefRegistry;
import org.auraframework.throwable.AuraRuntimeException;
import org.auraframework.throwable.quickfix.InvalidDefinitionException;
import org.auraframework.throwable.quickfix.QuickFixException;
import org.auraframework.util.json.Json;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
public class FlavorDefaultDefImpl extends DefinitionImpl<FlavorDefaultDef> implements FlavorDefaultDef {
private static final long serialVersionUID = 5695464798233444175L;
private static final String ANY = "*";
private static final String REMOVE = "{!remove}";
private final String component;
private final String flavor;
private final Expression context;
private final String removeAllNamespace;
private final DescriptorFilter componentFilter;
private final DefDescriptor<ComponentDef> singleComponent;
private final DefDescriptor<? extends RootDefinition> parentDescriptor;
private final int hashCode;
public FlavorDefaultDefImpl(Builder builder) throws InvalidDefinitionException {
super(builder);
this.component = builder.component;
this.flavor = builder.flavor;
DefDescriptor<ComponentDef> singleComponent = null;
if (component.equals(ANY)) { // match any component
componentFilter = new DescriptorFilter("markup://*:*", DefType.COMPONENT);
} else if (component.contains(ANY)) { // match glob pattern
componentFilter = new DescriptorFilter("markup://" + component, DefType.COMPONENT);
} else { // match single component
componentFilter = new DescriptorFilter("markup://" + component, DefType.COMPONENT);
singleComponent = Aura.getDefinitionService().getDefDescriptor(component, ComponentDef.class);
}
this.singleComponent = singleComponent;
if (singleComponent == null && flavor.equals(REMOVE)) {
removeAllNamespace = component.split(":")[0];
} else {
removeAllNamespace = null;
}
this.parentDescriptor = builder.parentDescriptor;
this.context = builder.context;
this.hashCode = AuraUtil.hashCode(descriptor, location, component, flavor, context);
}
@Override
public Optional<Expression> getContext() {
return Optional.fromNullable(context);
}
@Override
public DefDescriptor<? extends RootDefinition> getParentDescriptor() {
return parentDescriptor;
}
@Override
public Map<DefDescriptor<ComponentDef>, String> computeFilterMatches(FlavorOverrideLocator mapping) throws QuickFixException {
if (singleComponent != null) {
return ImmutableMap.of(singleComponent, flavor);
} else if (removeAllNamespace != null) {
return ImmutableMap.of();
}
AuraContext context = Aura.getContextService().getCurrentContext();
MasterDefRegistry mdr = context.getDefRegistry();
Map<DefDescriptor<ComponentDef>, String> map = new HashMap<>();
// first check the components in the overrides list
for (DefDescriptor<ComponentDef> entry : mapping.entries()) {
if (componentFilter.matchDescriptor(entry)) {
Optional<FlavorOverrideLocation> override = mapping.getLocation(entry, flavor);
if (override.isPresent()) {
map.put(entry, flavor);
}
}
}
// go through the FlavoredStyleDefs (in component bundles) from the dependency graph,
// add any matching flavors for components not already added from the mapping.
DefDescriptor<? extends BaseComponentDef> top = context.getApplicationDescriptor();
if (top != null && top.getDefType() == DefType.APPLICATION) {
String uid = context.getUid(top);
Set<DefDescriptor<?>> dependencies = mdr.getDependencies(uid);
if (dependencies != null) {
for (DefDescriptor<?> dep : dependencies) {
if (Flavors.isStandardFlavor(dep)) {
@SuppressWarnings("unchecked")
DefDescriptor<FlavoredStyleDef> style = (DefDescriptor<FlavoredStyleDef>) dep;
DefDescriptor<ComponentDef> cmp = Flavors.getBundledComponent(style);
if (componentFilter.matchDescriptor(cmp) && !map.containsKey(cmp)
&& style.getDef().getFlavorNames().contains(flavor)) {
map.put(cmp, flavor);
}
}
}
}
}
return map;
}
// TODONM can't add validation without imposing a dependency...
// @Override
// public void validateReferences() throws QuickFixException {
// if (singleComponent != null) {
// ComponentDef def = singleComponent.getDef();
// if (!def.hasFlavorableChild() && !def.inheritsFlavorableChild() &&
// !def.isDynamicallyFlavorable()) {
// throw new InvalidDefinitionException(
// String.format("%s must contain at least one aura:flavorable element", singleComponent),
// getLocation());
// }
// }
// }
@Override
public void serialize(Json json) throws IOException {
AuraContext ctx = Aura.getContextService().getCurrentContext();
DefDescriptor<?> dd = ctx != null ? ctx.getCurrentCallingDescriptor() : null;
if (dd != null && dd.getDefType() == DefType.FLAVORS) { // fixme!
try {
FlavorOverrideLocator mapping = ((FlavorsDef) dd.getDef()).computeOverrides();
json.writeMapBegin();
if (removeAllNamespace != null) {
json.writeMapEntry("removeAll", removeAllNamespace);
if (context != null) {
json.writeMapEntry("context", context);
}
} else {
for (Entry<DefDescriptor<ComponentDef>, String> entry : computeFilterMatches(mapping).entrySet()) {
json.writeMapKey(entry.getKey().getQualifiedName());
json.writeMapBegin();
json.writeMapEntry("flavor", entry.getValue());
if (context != null) {
json.writeMapEntry("context", context);
}
json.writeMapEnd();
}
}
json.writeMapEnd();
} catch (QuickFixException e) {
throw new AuraRuntimeException(e);
}
}
}
@Override
public final int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FlavorDefaultDefImpl) {
FlavorDefaultDefImpl other = (FlavorDefaultDefImpl) obj;
return Objects.equal(descriptor, other.descriptor)
&& Objects.equal(location, other.location)
&& Objects.equal(component, other.component)
&& Objects.equal(flavor, other.flavor)
&& Objects.equal(context, other.context);
}
return false;
}
/** builder class */
public static final class Builder extends DefinitionImpl.BuilderImpl<FlavorDefaultDef> {
public Builder() {
super(FlavorDefaultDef.class);
}
private DefDescriptor<? extends RootDefinition> parentDescriptor;
private String component;
private String flavor;
private Expression context;
public Builder setParentDescriptor(DefDescriptor<? extends RootDefinition> parentDescriptor) {
this.parentDescriptor = parentDescriptor;
return this;
}
public Builder setComponent(String component) {
this.component = component.trim();
return this;
}
public Builder setFlavor(String flavor) {
this.flavor = flavor.trim();
return this;
}
public void setContext(Expression context) throws InvalidDefinitionException {
this.context = context;
}
@Override
public FlavorDefaultDef build() throws InvalidDefinitionException {
return new FlavorDefaultDefImpl(this);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.synapse.implementation;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.synapse.fluent.KustoPoolDataConnectionsClient;
import com.azure.resourcemanager.synapse.fluent.models.CheckNameResultInner;
import com.azure.resourcemanager.synapse.fluent.models.DataConnectionInner;
import com.azure.resourcemanager.synapse.fluent.models.DataConnectionValidationInner;
import com.azure.resourcemanager.synapse.fluent.models.DataConnectionValidationListResultInner;
import com.azure.resourcemanager.synapse.models.CheckNameResult;
import com.azure.resourcemanager.synapse.models.DataConnection;
import com.azure.resourcemanager.synapse.models.DataConnectionCheckNameRequest;
import com.azure.resourcemanager.synapse.models.DataConnectionValidationListResult;
import com.azure.resourcemanager.synapse.models.KustoPoolDataConnections;
import com.fasterxml.jackson.annotation.JsonIgnore;
public final class KustoPoolDataConnectionsImpl implements KustoPoolDataConnections {
@JsonIgnore private final ClientLogger logger = new ClientLogger(KustoPoolDataConnectionsImpl.class);
private final KustoPoolDataConnectionsClient innerClient;
private final com.azure.resourcemanager.synapse.SynapseManager serviceManager;
public KustoPoolDataConnectionsImpl(
KustoPoolDataConnectionsClient innerClient, com.azure.resourcemanager.synapse.SynapseManager serviceManager) {
this.innerClient = innerClient;
this.serviceManager = serviceManager;
}
public CheckNameResult checkNameAvailability(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
DataConnectionCheckNameRequest dataConnectionName) {
CheckNameResultInner inner =
this
.serviceClient()
.checkNameAvailability(
resourceGroupName, workspaceName, kustoPoolName, databaseName, dataConnectionName);
if (inner != null) {
return new CheckNameResultImpl(inner, this.manager());
} else {
return null;
}
}
public Response<CheckNameResult> checkNameAvailabilityWithResponse(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
DataConnectionCheckNameRequest dataConnectionName,
Context context) {
Response<CheckNameResultInner> inner =
this
.serviceClient()
.checkNameAvailabilityWithResponse(
resourceGroupName, workspaceName, kustoPoolName, databaseName, dataConnectionName, context);
if (inner != null) {
return new SimpleResponse<>(
inner.getRequest(),
inner.getStatusCode(),
inner.getHeaders(),
new CheckNameResultImpl(inner.getValue(), this.manager()));
} else {
return null;
}
}
public DataConnectionValidationListResult dataConnectionValidation(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
DataConnectionValidationInner parameters) {
DataConnectionValidationListResultInner inner =
this
.serviceClient()
.dataConnectionValidation(resourceGroupName, workspaceName, kustoPoolName, databaseName, parameters);
if (inner != null) {
return new DataConnectionValidationListResultImpl(inner, this.manager());
} else {
return null;
}
}
public DataConnectionValidationListResult dataConnectionValidation(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
DataConnectionValidationInner parameters,
Context context) {
DataConnectionValidationListResultInner inner =
this
.serviceClient()
.dataConnectionValidation(
resourceGroupName, workspaceName, kustoPoolName, databaseName, parameters, context);
if (inner != null) {
return new DataConnectionValidationListResultImpl(inner, this.manager());
} else {
return null;
}
}
public PagedIterable<DataConnection> listByDatabase(
String resourceGroupName, String workspaceName, String kustoPoolName, String databaseName) {
PagedIterable<DataConnectionInner> inner =
this.serviceClient().listByDatabase(resourceGroupName, workspaceName, kustoPoolName, databaseName);
return Utils.mapPage(inner, inner1 -> new DataConnectionImpl(inner1, this.manager()));
}
public PagedIterable<DataConnection> listByDatabase(
String resourceGroupName, String workspaceName, String kustoPoolName, String databaseName, Context context) {
PagedIterable<DataConnectionInner> inner =
this.serviceClient().listByDatabase(resourceGroupName, workspaceName, kustoPoolName, databaseName, context);
return Utils.mapPage(inner, inner1 -> new DataConnectionImpl(inner1, this.manager()));
}
public DataConnection get(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
String dataConnectionName) {
DataConnectionInner inner =
this.serviceClient().get(resourceGroupName, workspaceName, kustoPoolName, databaseName, dataConnectionName);
if (inner != null) {
return new DataConnectionImpl(inner, this.manager());
} else {
return null;
}
}
public Response<DataConnection> getWithResponse(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
String dataConnectionName,
Context context) {
Response<DataConnectionInner> inner =
this
.serviceClient()
.getWithResponse(
resourceGroupName, workspaceName, kustoPoolName, databaseName, dataConnectionName, context);
if (inner != null) {
return new SimpleResponse<>(
inner.getRequest(),
inner.getStatusCode(),
inner.getHeaders(),
new DataConnectionImpl(inner.getValue(), this.manager()));
} else {
return null;
}
}
public DataConnection createOrUpdate(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
String dataConnectionName,
DataConnectionInner parameters) {
DataConnectionInner inner =
this
.serviceClient()
.createOrUpdate(
resourceGroupName, workspaceName, kustoPoolName, databaseName, dataConnectionName, parameters);
if (inner != null) {
return new DataConnectionImpl(inner, this.manager());
} else {
return null;
}
}
public DataConnection createOrUpdate(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
String dataConnectionName,
DataConnectionInner parameters,
Context context) {
DataConnectionInner inner =
this
.serviceClient()
.createOrUpdate(
resourceGroupName,
workspaceName,
kustoPoolName,
databaseName,
dataConnectionName,
parameters,
context);
if (inner != null) {
return new DataConnectionImpl(inner, this.manager());
} else {
return null;
}
}
public DataConnection update(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
String dataConnectionName,
DataConnectionInner parameters) {
DataConnectionInner inner =
this
.serviceClient()
.update(resourceGroupName, workspaceName, kustoPoolName, databaseName, dataConnectionName, parameters);
if (inner != null) {
return new DataConnectionImpl(inner, this.manager());
} else {
return null;
}
}
public DataConnection update(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
String dataConnectionName,
DataConnectionInner parameters,
Context context) {
DataConnectionInner inner =
this
.serviceClient()
.update(
resourceGroupName,
workspaceName,
kustoPoolName,
databaseName,
dataConnectionName,
parameters,
context);
if (inner != null) {
return new DataConnectionImpl(inner, this.manager());
} else {
return null;
}
}
public void delete(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
String dataConnectionName) {
this.serviceClient().delete(resourceGroupName, workspaceName, kustoPoolName, databaseName, dataConnectionName);
}
public void delete(
String resourceGroupName,
String workspaceName,
String kustoPoolName,
String databaseName,
String dataConnectionName,
Context context) {
this
.serviceClient()
.delete(resourceGroupName, workspaceName, kustoPoolName, databaseName, dataConnectionName, context);
}
private KustoPoolDataConnectionsClient serviceClient() {
return this.innerClient;
}
private com.azure.resourcemanager.synapse.SynapseManager manager() {
return this.serviceManager;
}
}
| |
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ampproject;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableMap;
import com.google.javascript.jscomp.AbstractCompiler;
import com.google.javascript.jscomp.HotSwapCompilerPass;
import com.google.javascript.jscomp.NodeTraversal;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
/**
* Does a `stripTypeSuffix` which currently can't be done through
* the normal `strip` mechanisms provided by closure compiler.
* Some of the known mechanisms we tried before writing our own compiler pass
* are setStripTypes, setStripTypePrefixes, setStripNameSuffixes, setStripNamePrefixes.
* The normal mechanisms found in closure compiler can't strip the expressions we want because
* they are either prefix based and/or operate on the es6 translated code which would mean they
* operate on a qualifier string name that looks like
* "module$__$__$__$extensions$amp_test$0_1$log.dev.fine".
*
* Other custom pass examples found inside closure compiler src:
* https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/PolymerPass.java
* https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/AngularPass.java
*/
class AmpPass extends AbstractPostOrderCallback implements HotSwapCompilerPass {
final AbstractCompiler compiler;
private final ImmutableSet<String> stripTypeSuffixes;
private final ImmutableMap<String, Node> assignmentReplacements;
private final ImmutableMap<String, Node> prodAssignmentReplacements;
final boolean isProd;
public AmpPass(AbstractCompiler compiler, boolean isProd,
ImmutableSet<String> stripTypeSuffixes,
ImmutableMap<String, Node> assignmentReplacements, ImmutableMap<String, Node> prodAssignmentReplacements) {
this.compiler = compiler;
this.stripTypeSuffixes = stripTypeSuffixes;
this.isProd = isProd;
this.assignmentReplacements = assignmentReplacements;
this.prodAssignmentReplacements = prodAssignmentReplacements;
}
@Override public void process(Node externs, Node root) {
hotSwapScript(root, null);
}
@Override public void hotSwapScript(Node scriptRoot, Node originalRoot) {
NodeTraversal.traverse(compiler, scriptRoot, this);
}
@Override public void visit(NodeTraversal t, Node n, Node parent) {
if (isCallRemovable(n)) {
maybeEliminateCallExceptFirstParam(n, parent);
} else if (isAmpExtensionCall(n)) {
inlineAmpExtensionCall(n, parent);
// Remove any `getMode().localDev` and `getMode().test` calls and replace it with `false`.
} else if (isProd && isFunctionInvokeAndPropAccess(n, "$mode.getMode",
ImmutableSet.of("localDev", "test"))) {
replaceWithBooleanExpression(false, n, parent);
// Remove any `getMode().minified` calls and replace it with `true`.
} else if (isProd && isFunctionInvokeAndPropAccess(n, "$mode.getMode",
ImmutableSet.of("minified"))) {
replaceWithBooleanExpression(true, n, parent);
} else {
if (isProd) {
maybeReplaceRValueInVar(n, prodAssignmentReplacements);
}
maybeReplaceRValueInVar(n, assignmentReplacements);
}
}
/**
* We don't care about the deep GETPROP. What we care about is finding a
* call which has an `extension` name which then has `AMP` as its
* previous getprop or name, and has a function as the 2nd argument.
*
* CALL 3 [length: 96] [source_file: input0]
* GETPROP 3 [length: 37] [source_file: input0]
* GETPROP 3 [length: 24] [source_file: input0]
* GETPROP 3 [length: 20] [source_file: input0]
* NAME self 3 [length: 4] [source_file: input0]
* STRING someproperty 3 [length: 15] [source_file: input0]
* STRING AMP 3 [length: 3] [source_file: input0]
* STRING extension 3 [length: 12] [source_file: input0]
* STRING some-string 3 [length: 9] [source_file: input0]
* FUNCTION 3 [length: 46] [source_file: input0]
*/
private boolean isAmpExtensionCall(Node n) {
if (n != null && n.isCall()) {
Node getprop = n.getFirstChild();
// The AST has the last getprop higher in the hierarchy.
if (isGetPropName(getprop, "extension")) {
Node firstChild = getprop.getFirstChild();
// We have to handle both explicit/implicit top level `AMP`
if ((firstChild != null && firstChild.isName() &&
firstChild.getString() == "AMP") ||
isGetPropName(firstChild, "AMP")) {
// Child at index 1 should be the "string" value (first argument)
Node func = getAmpExtensionCallback(n);
return func != null && func.isFunction();
}
}
}
return false;
}
private boolean isGetPropName(Node n, String name) {
if (n != null && n.isGetProp()) {
Node nodeName = n.getSecondChild();
return nodeName != null && nodeName.isString() &&
nodeName.getString() == name;
}
return false;
}
/**
* This operation should be guarded stringently by `isAmpExtensionCall`
* predicate.
*
* AMP.extension('some-name', '0.1', function(AMP) {
* // BODY...
* });
*
* is turned into:
* (function(AMP) {
* // BODY...
* })(self.AMP);
*/
private void inlineAmpExtensionCall(Node n, Node expr) {
if (expr == null || !expr.isExprResult()) {
return;
}
Node func = getAmpExtensionCallback(n);
func.detachFromParent();
Node arg1 = IR.getprop(IR.name("self"), IR.string("AMP"));
arg1.setLength("self.AMP".length());
arg1.useSourceInfoIfMissingFromForTree(func);
Node newcall = IR.call(func);
newcall.putBooleanProp(Node.FREE_CALL, true);
newcall.addChildToBack(arg1);
expr.replaceChild(n, newcall);
compiler.reportChangeToEnclosingScope(expr);
}
private Node getAmpExtensionCallback(Node n) {
return n.getLastChild();
}
/**
*/
private boolean isCallRemovable(Node n) {
if (n == null || !n.isCall()) {
return false;
}
String name = buildQualifiedName(n);
for (String removable : stripTypeSuffixes) {
if (name.equals(removable)) {
return true;
}
}
return false;
}
private void maybeReplaceRValueInVar(Node n, Map<String, Node> map) {
if (n != null && (n.isVar() || n.isLet() || n.isConst())) {
Node varNode = n.getFirstChild();
if (varNode != null) {
for (Map.Entry<String, Node> mapping : map.entrySet()) {
if (varNode.getString() == mapping.getKey()) {
varNode.replaceChild(varNode.getFirstChild(), mapping.getValue());
compiler.reportChangeToEnclosingScope(varNode);
return;
}
}
}
}
}
/**
* Predicate for any <code>fnQualifiedName</code>.<code>props</code> call.
* example:
* isFunctionInvokeAndPropAccess(n, "getMode", "test"); // matches `getMode().test`
*/
private boolean isFunctionInvokeAndPropAccess(Node n, String fnQualifiedName, Set<String> props) {
// mode.getMode().localDev
// mode [property] ->
// getMode [call]
// ${property} [string]
if (!n.isGetProp()) {
return false;
}
Node call = n.getFirstChild();
if (!call.isCall()) {
return false;
}
Node fullQualifiedFnName = call.getFirstChild();
if (fullQualifiedFnName == null) {
return false;
}
String qualifiedName = fullQualifiedFnName.getQualifiedName();
if (qualifiedName != null && qualifiedName.endsWith(fnQualifiedName)) {
Node maybeProp = n.getSecondChild();
if (maybeProp != null && maybeProp.isString()) {
String name = maybeProp.getString();
for (String prop : props) {
if (prop == name) {
return true;
}
}
}
}
return false;
}
/**
* Builds a string representation of MemberExpression and CallExpressions.
*/
private String buildQualifiedName(Node n) {
StringBuilder sb = new StringBuilder();
buildQualifiedNameInternal(n, sb);
return sb.toString();
}
private void buildQualifiedNameInternal(Node n, StringBuilder sb) {
if (n == null) {
sb.append("NULL");
return;
}
if (n.isCall()) {
buildQualifiedNameInternal(n.getFirstChild(), sb);
sb.append("()");
} else if (n.isGetProp()) {
buildQualifiedNameInternal(n.getFirstChild(), sb);
sb.append(".");
buildQualifiedNameInternal(n.getSecondChild(), sb);
} else if (n.isName() || n.isString()) {
sb.append(n.getString());
} else {
sb.append("UNKNOWN");
}
}
private void replaceWithBooleanExpression(boolean bool, Node n, Node parent) {
Node booleanNode = bool ? IR.trueNode() : IR.falseNode();
booleanNode.useSourceInfoIfMissingFrom(n);
parent.replaceChild(n, booleanNode);
compiler.reportChangeToEnclosingScope(parent);
}
private void removeExpression(Node n, Node parent) {
Node scope = parent;
if (parent.isExprResult()) {
Node grandparent = parent.getParent();
grandparent.removeChild(parent);
scope = grandparent;
} else {
parent.removeChild(n);
}
compiler.reportChangeToEnclosingScope(scope);
}
private void maybeEliminateCallExceptFirstParam(Node call, Node parent) {
// Extra precaution if the item we're traversing has already been detached.
if (call == null || parent == null) {
return;
}
Node getprop = call.getFirstChild();
if (getprop == null) {
return;
}
Node firstArg = getprop.getNext();
if (firstArg == null) {
removeExpression(call, parent);
return;
}
firstArg.detachFromParent();
parent.replaceChild(call, firstArg);
compiler.reportChangeToEnclosingScope(parent);
}
/**
* Checks the nodes qualified name if it ends with one of the items in
* stripTypeSuffixes
*/
boolean qualifiedNameEndsWithStripType(Node n, Set<String> suffixes) {
String name = n.getQualifiedName();
return qualifiedNameEndsWithStripType(name, suffixes);
}
/**
* Checks if the string ends with one of the items in stripTypeSuffixes
*/
boolean qualifiedNameEndsWithStripType(String name, Set<String> suffixes) {
if (name != null) {
for (String suffix : suffixes) {
if (name.endsWith(suffix)) {
return true;
}
}
}
return false;
}
}
| |
/*
* ARX: Powerful Data Anonymization
* Copyright 2014 Karol Babioch <karol@babioch.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deidentifier.arx.gui.view.impl.wizard;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.deidentifier.arx.gui.resources.Resources;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* JDBC page
*
* This page offers means to specify connection details for a database. For
* now MS SQL, MySQL, PostgreSQL and SQLite is supported. In case of remote database
* types (i.e. MS SQL, MySQL and PostgreSQL) the user is asked for the server and a
* username and password. In case of SQLite the user can select any *.db file.
*
* After ther user specified the details a connection is established and
* passed on to {@link ImportWizardModel}.
*
* This includes:
*
* <ul>
* <li>{@link ImportWizardModel#setJdbcConnection(Connection)<li>
* <li>{@link ImportWizardModel#setJdbcTables(List)<li>
* </ul>
*
* @author Karol Babioch
* @author Fabian Prasser
*/
public class ImportWizardPageJDBC extends WizardPage {
/** Reference to the wizard containing this page. */
private ImportWizard wizardImport;
/* SWT Widgets */
/** TODO */
private Label lblType;
/** TODO */
private Combo comboType;
/** TODO */
private Composite compositeSwap;
/** TODO */
private Text txtServer;
/** TODO */
private StackLayout layout;
/** TODO */
private Composite compositeRemote;
/** TODO */
private Composite compositeLocal;
/** TODO */
private Text txtPort;
/** TODO */
private Text txtUsername;
/** TODO */
private Text txtPassword;
/** TODO */
private Text txtDatabase;
/** TODO */
private Label lblLocation;
/** TODO */
private Combo comboLocation;
/** TODO */
private Button btnChoose;
/** TODO */
private Composite container;
/* String constants for different database types */
/** TODO */
private static final String MSSQL = "MS SQL"; //$NON-NLS-1$
/** TODO */
private static final String MYSQL = "MySQL"; //$NON-NLS-1$
/** TODO */
private static final String POSTGRESQL = "PostgreSQL"; //$NON-NLS-1$
/** TODO */
private static final String SQLITE = "SQLite"; //$NON-NLS-1$
/**
* Creates a new instance of this page and sets its title and description.
*
* @param wizardImport Reference to wizard containing this page
*/
public ImportWizardPageJDBC(ImportWizard wizardImport) {
super("WizardImportJdbcPage"); //$NON-NLS-1$
setTitle("JDBC"); //$NON-NLS-1$
setDescription(Resources.getMessage("ImportWizardPageJDBC.6")); //$NON-NLS-1$
this.wizardImport = wizardImport;
}
/**
* Creates the design of this page
*
* This adds all the controls to the page along with their listeners.
*
* @param parent
* @note {@link #compositeSwap} contains the actual text fields. Depending
* upon the status of {@link #comboType}, it will either display {@link #compositeRemote} or {@link #compositeLocal}.
*/
public void createControl(Composite parent) {
container = new Composite(parent, SWT.NULL);
setControl(container);
container.setLayout(new GridLayout(2, false));
/* Type label + combobox */
lblType = new Label(container, SWT.NONE);
lblType.setText(Resources.getMessage("ImportWizardPageJDBC.7")); //$NON-NLS-1$
/* Combo for choosing database type */
comboType = new Combo(container, SWT.READ_ONLY);
comboType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
comboType.setItems(new String[] {MSSQL, MYSQL, POSTGRESQL, SQLITE});
comboType.addSelectionListener(new SelectionAdapter() {
/**
* Swaps the composites, resets it and triggers a relayout
*/
@Override
public void widgetSelected(SelectionEvent e) {
setMessage(null);
setErrorMessage(null);
setPageComplete(false);
/* Display compositeLocal in case of SQLite */
if (comboType.getText().equals(SQLITE)) {
comboLocation.removeAll();
layout.topControl = compositeLocal;
/* Display compositeRemote otherwise */
} else {
layout.topControl = compositeRemote;
/* Set default ports in case text field is empty */
if (txtPort.getText().isEmpty()) {
if (comboType.getText().equals(MSSQL)) {
txtPort.setText("1433"); //$NON-NLS-1$
} else if (comboType.getText().equals(MYSQL)) {
txtPort.setText("3306"); //$NON-NLS-1$
} else if (comboType.getText().equals(POSTGRESQL)) {
txtPort.setText("5432"); //$NON-NLS-1$
}
}
}
/* Trigger relayout */
compositeSwap.layout();
}
});
/* Placeholder */
new Label(container, SWT.NONE);
new Label(container, SWT.NONE);
/* Swap composite */
compositeSwap = new Composite(container, SWT.NONE);
layout = new StackLayout();
compositeSwap.setLayout(layout);
compositeSwap.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
/* Remote composite */
createCompositeRemote();
/* Local composite */
createCompositeLocal();
/* Mark page as incomplete by default */
setPageComplete(false);
}
/**
* Creates the content of {@link #compositeLocal}
*
* This adds a file chooser and an appropriate combo to select files.
* Selecting a file from the combo will trigger a read of the tables. If
* everything is fine, the tables from the database will be read.
*
* @see {@link #readTables()}
*/
private void createCompositeLocal() {
compositeLocal = new Composite(compositeSwap, SWT.NONE);
compositeLocal.setLayout(new GridLayout(3, false));
/* Location label */
lblLocation = new Label(compositeLocal, SWT.NONE);
lblLocation.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblLocation.setText(Resources.getMessage("ImportWizardPageJDBC.11")); //$NON-NLS-1$
/* Combo box for selection of file */
comboLocation = new Combo(compositeLocal, SWT.READ_ONLY);
comboLocation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
comboLocation.addSelectionListener(new SelectionAdapter() {
/* Read tables from file */
@Override
public void widgetSelected(SelectionEvent e) {
setPageComplete(false);
setErrorMessage(null);
connect();
readTables();
}
});
/* Button to open file selection dialog */
btnChoose = new Button(compositeLocal, SWT.NONE);
btnChoose.setText(Resources.getMessage("ImportWizardPageJDBC.12")); //$NON-NLS-1$
btnChoose.addSelectionListener(new SelectionAdapter() {
/**
* Opens a file selection dialog for "*.db" files
*
* If a valid file was selected, it is added to
* {@link #comboLocation} when it wasn't already there. It is then
* preselected within {@link #comboLocation}.
*/
@Override
public void widgetSelected(SelectionEvent arg0) {
/* Open file dialog */
final String path = wizardImport.getController().actionShowOpenFileDialog(getShell(), "*.db"); //$NON-NLS-1$
if (path == null) {
return;
}
/* Check whether path was already added */
if (comboLocation.indexOf(path) == -1) {
comboLocation.add(path, 0);
}
/* Select path and notify comboLocation about change */
comboLocation.select(comboLocation.indexOf(path));
comboLocation.notifyListeners(SWT.Selection, null);
}
});
}
/**
* Creates the content of {@link #compositeRemote}
*
* This adds all of the labels and text fields necessary to connect to a
* remote database server. If everything is fine, the tables from the
* database will be read.
*
* @see {@link #readTables()}
*/
private void createCompositeRemote() {
compositeRemote = new Composite(compositeSwap, SWT.NONE);
compositeRemote.setLayout(new GridLayout(2, false));
/**
* Tries to connect to database on traverse and focusLost events
*
* @see {@link #tryToConnect()}
*/
class ConnectionListener extends FocusAdapter implements TraverseListener {
/**
* Handles focusLost events
*
* @see {@link #tryToConnect()}
*/
@Override
public void focusLost(FocusEvent e) {
tryToConnect();
}
/**
* Handles traverse events (enter, tab, etc.)
*
* @see {@link #tryToConnect()}
*/
@Override
public void keyTraversed(TraverseEvent e) {
tryToConnect();
}
}
ConnectionListener connectionListener = new ConnectionListener();
Label lblServer = new Label(compositeRemote, SWT.NONE);
lblServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblServer.setText(Resources.getMessage("ImportWizardPageJDBC.14")); //$NON-NLS-1$
txtServer = new Text(compositeRemote, SWT.BORDER);
txtServer.setText("localhost"); //$NON-NLS-1$
txtServer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtServer.addFocusListener(connectionListener);
txtServer.addTraverseListener(connectionListener);
Label lblPort = new Label(compositeRemote, SWT.NONE);
lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblPort.setText(Resources.getMessage("ImportWizardPageJDBC.16")); //$NON-NLS-1$
txtPort = new Text(compositeRemote, SWT.BORDER);
txtPort.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtPort.addFocusListener(connectionListener);
txtPort.addTraverseListener(connectionListener);
Label lblUsername = new Label(compositeRemote, SWT.NONE);
lblUsername.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblUsername.setText(Resources.getMessage("ImportWizardPageJDBC.0")); //$NON-NLS-1$
txtUsername = new Text(compositeRemote, SWT.BORDER);
txtUsername.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtUsername.addFocusListener(connectionListener);
txtUsername.addTraverseListener(connectionListener);
Label lblPassword = new Label(compositeRemote, SWT.NONE);
lblPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblPassword.setText(Resources.getMessage("ImportWizardPageJDBC.1")); //$NON-NLS-1$
txtPassword = new Text(compositeRemote, SWT.BORDER | SWT.PASSWORD);
txtPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtPassword.addFocusListener(connectionListener);
txtPassword.addTraverseListener(connectionListener);
Label lblDatabase = new Label(compositeRemote, SWT.NONE);
lblDatabase.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblDatabase.setText(Resources.getMessage("ImportWizardPageJDBC.19")); //$NON-NLS-1$
txtDatabase = new Text(compositeRemote, SWT.BORDER);
txtDatabase.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtDatabase.addFocusListener(connectionListener);
txtDatabase.addTraverseListener(connectionListener);
}
/**
* Tries to establish a remote JDBC connection
*
* Unless all mandatory fields (everything besides the password) are
* not empty this will try to connect to the database. It sets the message
* and errors of this page accordingly and will also try to read in the
* tables once a successfull connection has been established.
*
* @see {@link #readTables()}
*/
private void tryToConnect() {
setErrorMessage(null);
setMessage(null);
String server = txtServer.getText();
String port = txtPort.getText();
String username = txtUsername.getText();
String database = txtDatabase.getText();
if (server.isEmpty() || port.isEmpty() || username.isEmpty() || database.isEmpty()) {
return;
}
setMessage(Resources.getMessage("ImportWizardPageJDBC.20"), INFORMATION); //$NON-NLS-1$
if (connect()) {
setMessage(Resources.getMessage("ImportWizardPageJDBC.21"), INFORMATION); //$NON-NLS-1$
readTables();
}
}
/**
* Connects to the database
*
* This tries to establish an JDBC connection. In case of an error
* appropriate error messages are set. Otherwise the connection is passed
* on to {@link ImportWizardModel}. The return value indicates whether a
* connection has been established.
*
* @return True if successfully connected, false otherwise
*
* @see {@link ImportWizardModel#setJdbcConnection(Connection)}
*/
protected boolean connect() {
try {
Connection connection = null;
if (comboType.getText().equals(SQLITE)) {
Class.forName("org.sqlite.JDBC"); //$NON-NLS-1$
connection = DriverManager.getConnection("jdbc:sqlite:" + comboLocation.getText()); //$NON-NLS-1$
} else if (comboType.getText().equals(MSSQL)) {
Class.forName("net.sourceforge.jtds.jdbc.Driver"); //$NON-NLS-1$
connection = DriverManager.getConnection("jdbc:jtds:sqlserver://" + txtServer.getText() + ":" + txtPort.getText() + "/" + txtDatabase.getText(), txtUsername.getText(), txtPassword.getText()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} else if (comboType.getText().equals(MYSQL)) {
Class.forName("com.mysql.jdbc.Driver"); //$NON-NLS-1$
connection = DriverManager.getConnection("jdbc:mysql://" + txtServer.getText() + ":" + txtPort.getText() + "/" + txtDatabase.getText(), txtUsername.getText(), txtPassword.getText()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} else if (comboType.getText().equals(POSTGRESQL)) {
Class.forName("org.postgresql.Driver"); //$NON-NLS-1$
connection = DriverManager.getConnection("jdbc:postgresql://" + txtServer.getText() + ":" + txtPort.getText() + "/" + txtDatabase.getText(), txtUsername.getText(), txtPassword.getText()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
try {
if (!wizardImport.getData().getJdbcConnection().isClosed()) {
wizardImport.getData().getJdbcConnection().close();
}
} catch (Exception e){
/* Die silently*/
}
wizardImport.getData().setJdbcConnection(connection);
return true;
} catch (ClassNotFoundException e) {
setErrorMessage(Resources.getMessage("ImportWizardPageJDBC.36")); //$NON-NLS-1$
return false;
} catch (SQLException e) {
/* Database connection error */
setErrorMessage(e.getLocalizedMessage());
return false;
}
}
/**
* Reads in the tables
*
* If successful, the page is marked as complete and a list of tables is
* assigned to {@link ImportWizardModel}. Otherwise an appropriate error messages
* is set.
*
* @see {@link ImportWizardModel#setJdbcTables(List)}
*/
protected void readTables() {
try {
Connection connection = wizardImport.getData().getJdbcConnection();
String[] tableTypes = {"TABLE", "VIEW"}; //$NON-NLS-1$ //$NON-NLS-2$
ResultSet rs = connection.getMetaData().getTables(null, null, "%", tableTypes); //$NON-NLS-1$
List<String> tables = new ArrayList<String>();
while(rs.next()) {
tables.add(rs.getString("TABLE_NAME")); //$NON-NLS-1$
}
wizardImport.getData().setJdbcTables(tables);
setPageComplete(true);
} catch (SQLException e) {
setErrorMessage(Resources.getMessage("ImportWizardPageJDBC.41")); //$NON-NLS-1$
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.termvector;
import com.google.common.collect.Sets;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.ValidateActions;
import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.support.single.shard.SingleShardOperationRequest;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
/**
* Request returning the term vector (doc frequency, positions, offsets) for a
* document.
* <p/>
* Note, the {@link #index()}, {@link #type(String)} and {@link #id(String)} are
* required.
*/
public class TermVectorRequest extends SingleShardOperationRequest<TermVectorRequest> {
private String type;
private String id;
private BytesReference doc;
private String routing;
protected String preference;
private static final AtomicInteger randomInt = new AtomicInteger(0);
// TODO: change to String[]
private Set<String> selectedFields;
private EnumSet<Flag> flagsEnum = EnumSet.of(Flag.Positions, Flag.Offsets, Flag.Payloads,
Flag.FieldStatistics);
public TermVectorRequest() {
}
/**
* Constructs a new term vector request for a document that will be fetch
* from the provided index. Use {@link #type(String)} and
* {@link #id(String)} to specify the document to load.
*/
public TermVectorRequest(String index, String type, String id) {
super(index);
this.id = id;
this.type = type;
}
/**
* Constructs a new term vector request for a document that will be fetch
* from the provided index. Use {@link #type(String)} and
* {@link #id(String)} to specify the document to load.
*/
public TermVectorRequest(TermVectorRequest other) {
super(other.index());
this.id = other.id();
this.type = other.type();
this.flagsEnum = other.getFlags().clone();
this.preference = other.preference();
this.routing = other.routing();
if (other.selectedFields != null) {
this.selectedFields = new HashSet<>(other.selectedFields);
}
}
public TermVectorRequest(MultiGetRequest.Item item) {
super(item.index());
this.id = item.id();
this.type = item.type();
this.selectedFields(item.fields());
this.routing(item.routing());
}
public EnumSet<Flag> getFlags() {
return flagsEnum;
}
/**
* Sets the type of document to get the term vector for.
*/
public TermVectorRequest type(String type) {
this.type = type;
return this;
}
/**
* Returns the type of document to get the term vector for.
*/
public String type() {
return type;
}
/**
* Returns the id of document the term vector is requested for.
*/
public String id() {
return id;
}
/**
* Sets the id of document the term vector is requested for.
*/
public TermVectorRequest id(String id) {
this.id = id;
return this;
}
/**
* Returns the artificial document from which term vectors are requested for.
*/
public BytesReference doc() {
return doc;
}
/**
* Sets an artificial document from which term vectors are requested for.
*/
public TermVectorRequest doc(XContentBuilder documentBuilder) {
// assign a random id to this artificial document, for routing
this.id(String.valueOf(randomInt.getAndAdd(1)));
this.doc = documentBuilder.bytes();
return this;
}
/**
* @return The routing for this request.
*/
public String routing() {
return routing;
}
public TermVectorRequest routing(String routing) {
this.routing = routing;
return this;
}
/**
* Sets the parent id of this document. Will simply set the routing to this
* value, as it is only used for routing with delete requests.
*/
public TermVectorRequest parent(String parent) {
if (routing == null) {
routing = parent;
}
return this;
}
public String preference() {
return this.preference;
}
/**
* Sets the preference to execute the search. Defaults to randomize across
* shards. Can be set to <tt>_local</tt> to prefer local shards,
* <tt>_primary</tt> to execute only on primary shards, or a custom value,
* which guarantees that the same order will be used across different
* requests.
*/
public TermVectorRequest preference(String preference) {
this.preference = preference;
return this;
}
/**
* Return the start and stop offsets for each term if they were stored or
* skip offsets.
*/
public TermVectorRequest offsets(boolean offsets) {
setFlag(Flag.Offsets, offsets);
return this;
}
/**
* @return <code>true</code> if term offsets should be returned. Otherwise
* <code>false</code>
*/
public boolean offsets() {
return flagsEnum.contains(Flag.Offsets);
}
/**
* Return the positions for each term if stored or skip.
*/
public TermVectorRequest positions(boolean positions) {
setFlag(Flag.Positions, positions);
return this;
}
/**
* @return Returns if the positions for each term should be returned if
* stored or skip.
*/
public boolean positions() {
return flagsEnum.contains(Flag.Positions);
}
/**
* @return <code>true</code> if term payloads should be returned. Otherwise
* <code>false</code>
*/
public boolean payloads() {
return flagsEnum.contains(Flag.Payloads);
}
/**
* Return the payloads for each term or skip.
*/
public TermVectorRequest payloads(boolean payloads) {
setFlag(Flag.Payloads, payloads);
return this;
}
/**
* @return <code>true</code> if term statistics should be returned.
* Otherwise <code>false</code>
*/
public boolean termStatistics() {
return flagsEnum.contains(Flag.TermStatistics);
}
/**
* Return the term statistics for each term in the shard or skip.
*/
public TermVectorRequest termStatistics(boolean termStatistics) {
setFlag(Flag.TermStatistics, termStatistics);
return this;
}
/**
* @return <code>true</code> if field statistics should be returned.
* Otherwise <code>false</code>
*/
public boolean fieldStatistics() {
return flagsEnum.contains(Flag.FieldStatistics);
}
/**
* Return the field statistics for each term in the shard or skip.
*/
public TermVectorRequest fieldStatistics(boolean fieldStatistics) {
setFlag(Flag.FieldStatistics, fieldStatistics);
return this;
}
/**
* Return only term vectors for special selected fields. Returns for term
* vectors for all fields if selectedFields == null
*/
public Set<String> selectedFields() {
return selectedFields;
}
/**
* Return only term vectors for special selected fields. Returns the term
* vectors for all fields if selectedFields == null
*/
public TermVectorRequest selectedFields(String[] fields) {
selectedFields = fields != null && fields.length != 0 ? Sets.newHashSet(fields) : null;
return this;
}
private void setFlag(Flag flag, boolean set) {
if (set && !flagsEnum.contains(flag)) {
flagsEnum.add(flag);
} else if (!set) {
flagsEnum.remove(flag);
assert (!flagsEnum.contains(flag));
}
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = super.validate();
if (type == null) {
validationException = ValidateActions.addValidationError("type is missing", validationException);
}
if (id == null && doc == null) {
validationException = ValidateActions.addValidationError("id or doc is missing", validationException);
}
return validationException;
}
public static TermVectorRequest readTermVectorRequest(StreamInput in) throws IOException {
TermVectorRequest termVectorRequest = new TermVectorRequest();
termVectorRequest.readFrom(in);
return termVectorRequest;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
if (in.getVersion().before(Version.V_1_4_0_Beta1)) {
//term vector used to read & write the index twice, here and in the parent class
in.readString();
}
type = in.readString();
id = in.readString();
if (in.getVersion().onOrAfter(Version.V_1_4_0_Beta1)) {
if (in.readBoolean()) {
doc = in.readBytesReference();
}
}
routing = in.readOptionalString();
preference = in.readOptionalString();
long flags = in.readVLong();
flagsEnum.clear();
for (Flag flag : Flag.values()) {
if ((flags & (1 << flag.ordinal())) != 0) {
flagsEnum.add(flag);
}
}
int numSelectedFields = in.readVInt();
if (numSelectedFields > 0) {
selectedFields = new HashSet<>();
for (int i = 0; i < numSelectedFields; i++) {
selectedFields.add(in.readString());
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
if (out.getVersion().before(Version.V_1_4_0_Beta1)) {
//term vector used to read & write the index twice, here and in the parent class
out.writeString(index);
}
out.writeString(type);
out.writeString(id);
if (out.getVersion().onOrAfter(Version.V_1_4_0_Beta1)) {
out.writeBoolean(doc != null);
if (doc != null) {
out.writeBytesReference(doc);
}
}
out.writeOptionalString(routing);
out.writeOptionalString(preference);
long longFlags = 0;
for (Flag flag : flagsEnum) {
longFlags |= (1 << flag.ordinal());
}
out.writeVLong(longFlags);
if (selectedFields != null) {
out.writeVInt(selectedFields.size());
for (String selectedField : selectedFields) {
out.writeString(selectedField);
}
} else {
out.writeVInt(0);
}
}
public static enum Flag {
// Do not change the order of these flags we use
// the ordinal for encoding! Only append to the end!
Positions, Offsets, Payloads, FieldStatistics, TermStatistics
}
/**
* populates a request object (pre-populated with defaults) based on a parser.
*/
public static void parseRequest(TermVectorRequest termVectorRequest, XContentParser parser) throws IOException {
XContentParser.Token token;
String currentFieldName = null;
List<String> fields = new ArrayList<>();
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (currentFieldName != null) {
if (currentFieldName.equals("fields")) {
if (token == XContentParser.Token.START_ARRAY) {
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
fields.add(parser.text());
}
} else {
throw new ElasticsearchParseException(
"The parameter fields must be given as an array! Use syntax : \"fields\" : [\"field1\", \"field2\",...]");
}
} else if (currentFieldName.equals("offsets")) {
termVectorRequest.offsets(parser.booleanValue());
} else if (currentFieldName.equals("positions")) {
termVectorRequest.positions(parser.booleanValue());
} else if (currentFieldName.equals("payloads")) {
termVectorRequest.payloads(parser.booleanValue());
} else if (currentFieldName.equals("term_statistics") || currentFieldName.equals("termStatistics")) {
termVectorRequest.termStatistics(parser.booleanValue());
} else if (currentFieldName.equals("field_statistics") || currentFieldName.equals("fieldStatistics")) {
termVectorRequest.fieldStatistics(parser.booleanValue());
} else if ("_index".equals(currentFieldName)) { // the following is important for multi request parsing.
termVectorRequest.index = parser.text();
} else if ("_type".equals(currentFieldName)) {
termVectorRequest.type = parser.text();
} else if ("_id".equals(currentFieldName)) {
if (termVectorRequest.doc != null) {
throw new ElasticsearchParseException("Either \"id\" or \"doc\" can be specified, but not both!");
}
termVectorRequest.id = parser.text();
} else if ("doc".equals(currentFieldName)) {
if (termVectorRequest.id != null) {
throw new ElasticsearchParseException("Either \"id\" or \"doc\" can be specified, but not both!");
}
termVectorRequest.doc(jsonBuilder().copyCurrentStructure(parser));
} else if ("_routing".equals(currentFieldName) || "routing".equals(currentFieldName)) {
termVectorRequest.routing = parser.text();
} else {
throw new ElasticsearchParseException("The parameter " + currentFieldName
+ " is not valid for term vector request!");
}
}
}
if (fields.size() > 0) {
String[] fieldsAsArray = new String[fields.size()];
termVectorRequest.selectedFields(fields.toArray(fieldsAsArray));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.